LCOV - code coverage report
Current view: top level - src/test/fuzz - tx_pool.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 98.0 % 304 298
Test Date: 2026-08-29 05:53:03 Functions: 100.0 % 28 28
Branches: 59.7 % 509 304

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2021-present 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 <chain.h>
       6                 :             : #include <coins.h>
       7                 :             : #include <consensus/amount.h>
       8                 :             : #include <consensus/consensus.h>
       9                 :             : #include <consensus/validation.h>
      10                 :             : #include <node/miner.h>
      11                 :             : #include <node/mining_types.h>
      12                 :             : #include <policy/feerate.h>
      13                 :             : #include <policy/packages.h>
      14                 :             : #include <policy/policy.h>
      15                 :             : #include <policy/truc_policy.h>
      16                 :             : #include <primitives/block.h>
      17                 :             : #include <primitives/transaction.h>
      18                 :             : #include <script/script.h>
      19                 :             : #include <sync.h>
      20                 :             : #include <test/fuzz/FuzzedDataProvider.h>
      21                 :             : #include <test/fuzz/fuzz.h>
      22                 :             : #include <test/fuzz/util.h>
      23                 :             : #include <test/fuzz/util/mempool.h>
      24                 :             : #include <test/util/mining.h>
      25                 :             : #include <test/util/random.h>
      26                 :             : #include <test/util/script.h>
      27                 :             : #include <test/util/setup_common.h>
      28                 :             : #include <test/util/txmempool.h>
      29                 :             : #include <txmempool.h>
      30                 :             : #include <util/check.h>
      31                 :             : #include <util/string.h>
      32                 :             : #include <util/time.h>
      33                 :             : #include <util/translation.h>
      34                 :             : #include <validation.h>
      35                 :             : #include <validationinterface.h>
      36                 :             : 
      37                 :             : #include <cstddef>
      38                 :             : #include <cstdint>
      39                 :             : #include <functional>
      40                 :             : #include <iterator>
      41                 :             : #include <limits>
      42                 :             : #include <map>
      43                 :             : #include <memory>
      44                 :             : #include <optional>
      45                 :             : #include <set>
      46                 :             : #include <span>
      47                 :             : #include <string>
      48                 :             : #include <utility>
      49                 :             : #include <vector>
      50                 :             : using node::BlockAssembler;
      51                 :             : using node::BlockCreateOptions;
      52                 :             : using node::NodeContext;
      53                 :             : using util::ToString;
      54                 :             : 
      55                 :             : namespace {
      56                 :             : 
      57                 :             : const TestingSetup* g_setup;
      58                 :             : std::vector<COutPoint> g_outpoints_coinbase_init_mature;
      59                 :             : std::vector<COutPoint> g_outpoints_coinbase_init_immature;
      60                 :             : 
      61                 :             : struct MockedTxPool : public CTxMemPool {
      62                 :      572026 :     void RollingFeeUpdate() EXCLUSIVE_LOCKS_REQUIRED(!cs)
      63                 :             :     {
      64                 :      572026 :         LOCK(cs);
      65         [ +  - ]:      572026 :         lastRollingFeeUpdate = GetTime();
      66         [ +  - ]:      572026 :         blockSinceLastRollingFeeBump = true;
      67                 :      572026 :     }
      68                 :             : };
      69                 :             : 
      70                 :           2 : void initialize_tx_pool()
      71                 :             : {
      72   [ +  -  +  -  :           2 :     static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>();
                   +  - ]
      73                 :           2 :     g_setup = testing_setup.get();
      74   [ +  -  +  - ]:           6 :     SetMockTime(WITH_LOCK(g_setup->m_node.chainman->GetMutex(), return g_setup->m_node.chainman->ActiveTip()->Time()));
      75                 :             : 
      76         [ +  + ]:         402 :     for (int i = 0; i < 2 * COINBASE_MATURITY; ++i) {
      77                 :        1200 :         COutPoint prevout{MineBlock(g_setup->m_node, {
      78                 :             :             .coinbase_output_script = P2WSH_OP_TRUE,
      79                 :             :         })};
      80                 :             :         // Remember the txids to avoid expensive disk access later on
      81         [ +  + ]:         400 :         auto& outpoints = i < COINBASE_MATURITY ?
      82                 :             :                               g_outpoints_coinbase_init_mature :
      83                 :             :                               g_outpoints_coinbase_init_immature;
      84                 :         400 :         outpoints.push_back(prevout);
      85                 :             :     }
      86                 :           2 :     g_setup->m_node.validation_signals->SyncWithValidationInterfaceQueue();
      87         [ +  - ]:         402 : }
      88                 :             : 
      89                 :             : struct TransactionsDelta final : public CValidationInterface {
      90                 :             :     std::set<CTransactionRef>& m_removed;
      91                 :             :     std::set<CTransactionRef>& m_added;
      92                 :             : 
      93                 :      146030 :     explicit TransactionsDelta(std::set<CTransactionRef>& r, std::set<CTransactionRef>& a)
      94                 :      146030 :         : m_removed{r}, m_added{a} {}
      95                 :             : 
      96                 :       52845 :     void TransactionAddedToMempool(const NewMempoolTransactionInfo& tx, uint64_t /* mempool_sequence */) override
      97                 :             :     {
      98         [ -  + ]:       52845 :         Assert(m_added.insert(tx.info.m_tx).second);
      99                 :       52845 :     }
     100                 :             : 
     101                 :       15358 :     void TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t /* mempool_sequence */) override
     102                 :             :     {
     103         [ -  + ]:       15358 :         Assert(m_removed.insert(tx).second);
     104                 :       15358 :     }
     105                 :             : };
     106                 :             : 
     107                 :       14361 : void SetMempoolConstraints(ArgsManager& args, FuzzedDataProvider& fuzzed_data_provider)
     108                 :             : {
     109   [ +  -  +  - ]:       28722 :     args.ForceSetArg("-limitclustercount",
     110                 :       14361 :                      ToString(fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(1, 64)));
     111   [ +  -  +  - ]:       28722 :     args.ForceSetArg("-limitclustersize",
     112                 :       14361 :                      ToString(fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(1, 250)));
     113   [ +  -  +  - ]:       28722 :     args.ForceSetArg("-maxmempool",
     114                 :       14361 :                      ToString(fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 200)));
     115   [ +  -  +  - ]:       28722 :     args.ForceSetArg("-mempoolexpiry",
     116                 :       14361 :                      ToString(fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 999)));
     117                 :       14361 : }
     118                 :             : 
     119                 :             : /** Get a list of wtxids to query from the mempool for relay. Make the list heterogeneous with
     120                 :             :  * wtxids of mempool transactions, non-mempool transactions, and duplicates. */
     121                 :       14361 : std::vector<Wtxid> WtxidsToRelay(FuzzedDataProvider& fuzzed_data_provider, const MockedTxPool& tx_pool)
     122                 :             : {
     123                 :       14361 :     LOCK(tx_pool.cs);
     124                 :       14361 :     std::vector<Wtxid> res;
     125                 :             : 
     126                 :       14361 :     uint8_t dummy{0};
     127         [ +  - ]:       14361 :     const auto mempool_entries{tx_pool.entryAll()};
     128   [ +  +  +  + ]:       68397 :     LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 100) {
     129   [ +  +  +  + ]:       98006 :         if (!mempool_entries.empty() && fuzzed_data_provider.ConsumeBool()) {
     130                 :             :             // Wtxid of an in-mempool transaction
     131         [ +  - ]:       37137 :             const auto& entry_ref{PickValue(fuzzed_data_provider, mempool_entries).get()};
     132         [ +  - ]:       37137 :             res.push_back(entry_ref.GetTx().GetWitnessHash());
     133                 :             :             // Don't remove it from the mempool, so the next pick is possibly a duplicate
     134                 :             :         } else {
     135                 :             :             // Wtxid of a not-in-mempool transaction
     136         [ +  - ]:       16899 :             res.push_back(Wtxid::FromUint256(uint256{dummy}));
     137                 :             :             // Possibly make the next wtxid of a not-in-mempool transaction, a duplicate
     138         [ +  + ]:       16899 :             if (fuzzed_data_provider.ConsumeBool()) dummy++;
     139                 :             :         }
     140                 :             :     }
     141                 :             : 
     142                 :       14361 :     return res;
     143         [ +  - ]:       28722 : }
     144                 :             : 
     145                 :       14361 : void Finish(FuzzedDataProvider& fuzzed_data_provider, MockedTxPool& tx_pool, Chainstate& chainstate)
     146                 :             : {
     147   [ -  +  +  -  :       43083 :     WITH_LOCK(::cs_main, tx_pool.check(chainstate.CoinsTip(), chainstate.m_chain.Height() + 1));
                   +  - ]
     148                 :       14361 :     {
     149                 :       14361 :         BlockCreateOptions options{
     150                 :       14361 :             .block_min_fee_rate = CFeeRate{ConsumeMoney(fuzzed_data_provider, /*max=*/COIN)},
     151         [ +  - ]:       14361 :             .block_max_weight = fuzzed_data_provider.ConsumeIntegralInRange<uint64_t>(DEFAULT_BLOCK_RESERVED_WEIGHT, MAX_BLOCK_WEIGHT),
     152         [ +  - ]:       14361 :         };
     153         [ +  - ]:       14361 :         auto assembler = BlockAssembler{chainstate, &tx_pool, options};
     154         [ +  - ]:       14361 :         auto block_template = assembler.CreateNewBlock();
     155   [ -  +  -  + ]:       14361 :         Assert(block_template->block.vtx.size() >= 1);
     156                 :             : 
     157                 :             :         // Try updating the mempool for this block, as though it were mined.
     158   [ +  -  +  - ]:       14361 :         LOCK2(::cs_main, tx_pool.cs);
     159         [ +  - ]:       14361 :         tx_pool.removeForBlock(block_template->block.vtx);
     160                 :             : 
     161                 :             :         // Now try to add those transactions back, as though a reorg happened.
     162                 :       14361 :         std::vector<Txid> hashes_to_update;
     163         [ +  + ]:      112180 :         for (const auto& tx : block_template->block.vtx) {
     164   [ +  -  +  - ]:       97819 :             const auto res = AcceptToMemoryPool(chainstate, tx, GetTime(), true, /*test_accept=*/false);
     165         [ +  + ]:       97819 :             if (res.m_result_type == MempoolAcceptResult::ResultType::VALID) {
     166         [ +  - ]:       83458 :                 hashes_to_update.push_back(tx->GetHash());
     167                 :             :             } else {
     168         [ +  - ]:       14361 :                 tx_pool.removeRecursive(*tx, MemPoolRemovalReason::REORG);
     169                 :             :             }
     170                 :       97819 :         }
     171         [ +  - ]:       14361 :         tx_pool.UpdateTransactionsFromBlock(hashes_to_update);
     172   [ +  -  +  - ]:       57444 :     }
     173                 :       14361 :     const auto info_all = tx_pool.infoAll();
     174         [ +  + ]:       14361 :     if (!info_all.empty()) {
     175         [ +  - ]:       10574 :         const auto& tx_to_remove = *PickValue(fuzzed_data_provider, info_all).tx;
     176   [ +  -  +  - ]:       31722 :         WITH_LOCK(tx_pool.cs, tx_pool.removeRecursive(tx_to_remove, MemPoolRemovalReason::BLOCK /* dummy */));
     177   [ +  -  -  +  :       10574 :         assert(tx_pool.size() < info_all.size());
                   -  + ]
     178                 :             :     }
     179                 :             : 
     180                 :             :     // Query a number of mempool entries as if to relay them, and assert some invariants on the result.
     181         [ +  - ]:       14361 :     auto wtxids_to_relay{WtxidsToRelay(fuzzed_data_provider, tx_pool)};
     182         [ -  + ]:       14361 :     const auto wtxids_count_before{wtxids_to_relay.size()};
     183                 :       14361 :     const auto n_to_sort{fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 100)};
     184   [ +  -  +  - ]:       43083 :     const auto sorted_iter{WITH_LOCK(tx_pool.cs, return tx_pool.ExtractBestByMiningScoreWithTopology(wtxids_to_relay, n_to_sort))};
     185         [ +  + ]:       14361 :     const auto expected_count{std::min(n_to_sort, wtxids_count_before)};
     186                 :             :     // We removed at least as many transactions from the list as we expected sorted entries.
     187   [ -  +  -  + ]:       14361 :     Assert(wtxids_to_relay.size() <= wtxids_count_before - expected_count);
     188                 :             :     // When there is enough non-duplicate in-mempool transactions (list of remaining wtxids is
     189                 :             :     // non-empty), we must have received the expected number of entries.
     190   [ -  +  +  +  :       16034 :     Assert(sorted_iter.size() == expected_count || wtxids_to_relay.empty());
             +  -  -  + ]
     191         [ +  + ]:       14361 :     if (n_to_sort > 0) {
     192                 :             :         // If we asked for a positive number of entries, we must have removed all wtxids that do
     193                 :             :         // not correspond to a mempool entry..
     194         [ +  - ]:         688 :         const auto is_in_mempool = [&](const auto& wtxid) EXCLUSIVE_LOCKS_REQUIRED(tx_pool.cs) { return tx_pool.GetIter(wtxid).has_value(); };
     195   [ +  -  -  +  :       11412 :         Assert(WITH_LOCK(tx_pool.cs, return std::ranges::all_of(wtxids_to_relay, is_in_mempool)));
             +  -  +  - ]
     196                 :             :         // ..As well as all duplicates.
     197         [ -  + ]:        3804 :         const auto wtxids_count{wtxids_to_relay.size()};
     198         [ +  - ]:        3804 :         const std::set<Wtxid> unique_wtxids{std::make_move_iterator(wtxids_to_relay.begin()), std::make_move_iterator(wtxids_to_relay.end())};
     199         [ -  + ]:        3804 :         Assert(unique_wtxids.size() == wtxids_count);
     200                 :        3804 :     }
     201                 :             : 
     202         [ +  + ]:       14361 :     if (fuzzed_data_provider.ConsumeBool()) {
     203                 :             :         // Try eviction
     204   [ +  -  +  - ]:        2800 :         LOCK2(::cs_main, tx_pool.cs);
     205   [ +  -  +  - ]:        2800 :         tx_pool.TrimToSize(fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0U, tx_pool.DynamicMemoryUsage() * 2));
     206         [ +  - ]:        5600 :     }
     207         [ +  + ]:       14361 :     if (fuzzed_data_provider.ConsumeBool()) {
     208                 :             :         // Try expiry
     209   [ +  -  +  - ]:        2878 :         LOCK2(::cs_main, tx_pool.cs);
     210   [ +  -  +  - ]:        2878 :         tx_pool.Expire(GetMockTime() - std::chrono::seconds(fuzzed_data_provider.ConsumeIntegral<uint32_t>()));
     211         [ +  - ]:        5756 :     }
     212   [ +  -  -  +  :       43083 :     WITH_LOCK(::cs_main, tx_pool.check(chainstate.CoinsTip(), chainstate.m_chain.Height() + 1));
             +  -  +  - ]
     213         [ +  - ]:       14361 :     g_setup->m_node.validation_signals->SyncWithValidationInterfaceQueue();
     214                 :       14361 : }
     215                 :             : 
     216                 :      567343 : void MockTime(FuzzedDataProvider& fuzzed_data_provider, const Chainstate& chainstate)
     217                 :             : {
     218                 :      567343 :     const auto time = ConsumeTime(fuzzed_data_provider,
     219                 :      567343 :                                   chainstate.m_chain.Tip()->GetMedianTimePast() + 1,
     220         [ -  + ]:      567343 :                                   std::numeric_limits<decltype(chainstate.m_chain.Tip()->nTime)>::max());
     221                 :      567343 :     SetMockTime(time);
     222                 :      567343 : }
     223                 :             : 
     224                 :       14361 : std::unique_ptr<CTxMemPool> MakeMempool(FuzzedDataProvider& fuzzed_data_provider, const NodeContext& node)
     225                 :             : {
     226                 :             :     // Take the default options for tests...
     227                 :       14361 :     CTxMemPool::Options mempool_opts{MemPoolOptionsForTest(node)};
     228                 :             : 
     229                 :             :     // ...override specific options for this specific fuzz suite
     230                 :       14361 :     mempool_opts.check_ratio = 1;
     231                 :       14361 :     mempool_opts.require_standard = fuzzed_data_provider.ConsumeBool();
     232                 :             : 
     233                 :             :     // ...and construct a CTxMemPool from it
     234         [ +  - ]:       14361 :     bilingual_str error;
     235         [ +  - ]:       14361 :     auto mempool{std::make_unique<CTxMemPool>(std::move(mempool_opts), error)};
     236                 :             :     // ... ignore the error since it might be beneficial to fuzz even when the
     237                 :             :     // mempool size is unreasonably small
     238   [ +  +  +  -  :       14983 :     Assert(error.empty() || error.original.starts_with("-maxmempool must be at least "));
                   -  + ]
     239                 :       14361 :     return mempool;
     240                 :       14361 : }
     241                 :             : 
     242                 :      146030 : void CheckATMPInvariants(const MempoolAcceptResult& res, bool txid_in_mempool, bool wtxid_in_mempool)
     243                 :             : {
     244                 :             : 
     245   [ +  +  -  -  :      146030 :     switch (res.m_result_type) {
                      - ]
     246                 :       52845 :     case MempoolAcceptResult::ResultType::VALID:
     247                 :       52845 :     {
     248         [ -  + ]:       52845 :         Assert(txid_in_mempool);
     249         [ -  + ]:       52845 :         Assert(wtxid_in_mempool);
     250         [ -  + ]:       52845 :         Assert(res.m_state.IsValid());
     251         [ -  + ]:       52845 :         Assert(!res.m_state.IsInvalid());
     252         [ -  + ]:       52845 :         Assert(res.m_vsize);
     253         [ -  + ]:       52845 :         Assert(res.m_base_fees);
     254         [ -  + ]:       52845 :         Assert(res.m_effective_feerate);
     255         [ -  + ]:       52845 :         Assert(res.m_wtxids_fee_calculations);
     256         [ -  + ]:       52845 :         Assert(!res.m_other_wtxid);
     257                 :             :         break;
     258                 :             :     }
     259                 :       93185 :     case MempoolAcceptResult::ResultType::INVALID:
     260                 :       93185 :     {
     261                 :             :         // It may be already in the mempool since in ATMP cases we don't set MEMPOOL_ENTRY or DIFFERENT_WITNESS
     262         [ -  + ]:       93185 :         Assert(!res.m_state.IsValid());
     263         [ -  + ]:       93185 :         Assert(res.m_state.IsInvalid());
     264                 :             : 
     265         [ -  + ]:       93185 :         const bool is_reconsiderable{res.m_state.GetResult() == TxValidationResult::TX_RECONSIDERABLE};
     266         [ -  + ]:       93185 :         Assert(!res.m_vsize);
     267         [ -  + ]:       93185 :         Assert(!res.m_base_fees);
     268                 :             :         // Fee information is provided if the failure is TX_RECONSIDERABLE.
     269                 :             :         // In other cases, validation may be unable or unwilling to calculate the fees.
     270         [ -  + ]:       93185 :         Assert(res.m_effective_feerate.has_value() == is_reconsiderable);
     271         [ -  + ]:       93185 :         Assert(res.m_wtxids_fee_calculations.has_value() == is_reconsiderable);
     272         [ -  + ]:       93185 :         Assert(!res.m_other_wtxid);
     273                 :             :         break;
     274                 :             :     }
     275                 :           0 :     case MempoolAcceptResult::ResultType::MEMPOOL_ENTRY:
     276                 :           0 :     {
     277                 :             :         // ATMP never sets this; only set in package settings
     278                 :           0 :         Assert(false);
     279                 :             :         break;
     280                 :             :     }
     281                 :           0 :     case MempoolAcceptResult::ResultType::DIFFERENT_WITNESS:
     282                 :           0 :     {
     283                 :             :         // ATMP never sets this; only set in package settings
     284                 :           0 :         Assert(false);
     285                 :             :         break;
     286                 :             :     }
     287                 :             :     }
     288                 :      146030 : }
     289                 :             : 
     290         [ +  - ]:        4578 : FUZZ_TARGET(tx_pool_standard, .init = initialize_tx_pool)
     291                 :             : {
     292                 :        4102 :     SeedRandomStateForTest(SeedRand::ZEROS);
     293                 :        4102 :     FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
     294                 :        4102 :     const auto& node = g_setup->m_node;
     295                 :        4102 :     auto& chainstate{static_cast<DummyChainState&>(node.chainman->ActiveChainstate())};
     296                 :             : 
     297                 :        4102 :     MockTime(fuzzed_data_provider, chainstate);
     298                 :             : 
     299                 :             :     // All RBF-spendable outpoints
     300                 :        4102 :     std::set<COutPoint> outpoints_rbf;
     301                 :             :     // All outpoints counting toward the total supply (subset of outpoints_rbf)
     302                 :        4102 :     std::set<COutPoint> outpoints_supply;
     303         [ +  + ]:      414302 :     for (const auto& outpoint : g_outpoints_coinbase_init_mature) {
     304         [ +  - ]:      820400 :         Assert(outpoints_supply.insert(outpoint).second);
     305                 :             :     }
     306         [ +  - ]:        4102 :     outpoints_rbf = outpoints_supply;
     307                 :             : 
     308                 :             :     // The sum of the values of all spendable outpoints
     309                 :        4102 :     constexpr CAmount SUPPLY_TOTAL{COINBASE_MATURITY * 50 * COIN};
     310                 :             : 
     311         [ +  - ]:        4102 :     SetMempoolConstraints(*node.args, fuzzed_data_provider);
     312         [ +  - ]:        4102 :     auto tx_pool_{MakeMempool(fuzzed_data_provider, node)};
     313         [ +  - ]:        4102 :     MockedTxPool& tx_pool = *static_cast<MockedTxPool*>(tx_pool_.get());
     314                 :             : 
     315         [ +  - ]:        4102 :     chainstate.SetMempool(&tx_pool);
     316                 :             : 
     317                 :             :     // Helper to query an amount
     318   [ +  -  +  - ]:       12306 :     const CCoinsViewMemPool amount_view{WITH_LOCK(::cs_main, return &chainstate.CoinsTip()), tx_pool};
           [ +  -  +  - ]
     319                 :    27746124 :     const auto GetAmount = [&](const COutPoint& outpoint) {
     320         [ +  - ]:    27742022 :         auto coin{amount_view.GetCoin(outpoint).value()};
     321                 :    27742022 :         return coin.out.nValue;
     322                 :    27746124 :     };
     323                 :             : 
     324   [ +  +  +  + ]:      150132 :     LIMITED_WHILE (fuzzed_data_provider.ConsumeBool(), 100) {
     325                 :      146030 :         {
     326                 :             :             // Total supply is the mempool fee + all outpoints
     327 [ +  - ][ +  - ]:      292060 :             CAmount supply_now{WITH_LOCK(tx_pool.cs, return tx_pool.GetTotalFee())};
     328         [ +  + ]:    24953858 :             for (const auto& op : outpoints_supply) {
     329         [ +  - ]:    24807828 :                 supply_now += GetAmount(op);
     330                 :             :             }
     331         [ -  + ]:      146030 :             Assert(supply_now == SUPPLY_TOTAL);
     332                 :             :         }
     333         [ -  + ]:      146030 :         Assert(!outpoints_supply.empty());
     334                 :             : 
     335                 :             :         // Create transaction to add to the mempool
     336                 :      292060 :         const CTransactionRef tx = [&] {
     337                 :      146030 :             CMutableTransaction tx_mut;
     338         [ +  + ]:      146030 :             tx_mut.version = fuzzed_data_provider.ConsumeBool() ? TRUC_VERSION : CTransaction::CURRENT_VERSION;
     339         [ +  + ]:      146030 :             tx_mut.nLockTime = fuzzed_data_provider.ConsumeBool() ? 0 : fuzzed_data_provider.ConsumeIntegral<uint32_t>();
     340                 :      146030 :             const auto num_in = fuzzed_data_provider.ConsumeIntegralInRange<int>(1, outpoints_rbf.size());
     341                 :      146030 :             const auto num_out = fuzzed_data_provider.ConsumeIntegralInRange<int>(1, outpoints_rbf.size() * 2);
     342                 :             : 
     343                 :      146030 :             CAmount amount_in{0};
     344         [ +  + ]:     3080224 :             for (int i = 0; i < num_in; ++i) {
     345                 :             :                 // Pop random outpoint
     346                 :     2934194 :                 auto pop = outpoints_rbf.begin();
     347                 :     2934194 :                 std::advance(pop, fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, outpoints_rbf.size() - 1));
     348                 :     2934194 :                 const auto outpoint = *pop;
     349                 :     2934194 :                 outpoints_rbf.erase(pop);
     350         [ +  - ]:     2934194 :                 amount_in += GetAmount(outpoint);
     351                 :             : 
     352                 :             :                 // Create input
     353                 :     2934194 :                 const auto sequence = ConsumeSequence(fuzzed_data_provider);
     354                 :     2934194 :                 const auto script_sig = CScript{};
     355   [ -  +  +  +  :     5868388 :                 const auto script_wit_stack = std::vector<std::vector<uint8_t>>{WITNESS_STACK_ELEM_OP_TRUE};
                   -  - ]
     356                 :     2934194 :                 CTxIn in;
     357                 :     2934194 :                 in.prevout = outpoint;
     358                 :     2934194 :                 in.nSequence = sequence;
     359                 :     2934194 :                 in.scriptSig = script_sig;
     360         [ +  - ]:     2934194 :                 in.scriptWitness.stack = script_wit_stack;
     361                 :             : 
     362         [ +  - ]:     2934194 :                 tx_mut.vin.push_back(in);
     363                 :     2934194 :             }
     364                 :             : 
     365                 :             :             // Check sigops in mempool + block template creation
     366                 :      146030 :             bool add_sigops{fuzzed_data_provider.ConsumeBool()};
     367                 :             : 
     368                 :      146030 :             const auto amount_fee = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-1000, amount_in);
     369                 :      146030 :             const auto amount_out = (amount_in - amount_fee) / num_out;
     370         [ +  + ]:    10562431 :             for (int i = 0; i < num_out; ++i) {
     371         [ +  + ]:    10416401 :                 if (i == 0 && add_sigops) {
     372   [ +  -  +  -  :      365478 :                     tx_mut.vout.emplace_back(amount_out, CScript() << std::vector<unsigned char>(33, 0x02) << OP_CHECKSIG);
                   +  - ]
     373                 :             :                 } else {
     374         [ +  - ]:    10294575 :                     tx_mut.vout.emplace_back(amount_out, P2WSH_OP_TRUE);
     375                 :             :                 }
     376                 :             :             }
     377                 :             : 
     378         [ +  - ]:      146030 :             auto tx = MakeTransactionRef(tx_mut);
     379                 :             :             // Restore previously removed outpoints
     380         [ +  + ]:     3080224 :             for (const auto& in : tx->vin) {
     381         [ +  - ]:     5868388 :                 Assert(outpoints_rbf.insert(in.prevout).second);
     382                 :             :             }
     383                 :      146030 :             return tx;
     384 [ +  - ][ +  - ]:     3226254 :         }();
     385                 :             : 
     386         [ +  + ]:      146030 :         if (fuzzed_data_provider.ConsumeBool()) {
     387         [ +  - ]:       99827 :             MockTime(fuzzed_data_provider, chainstate);
     388                 :             :         }
     389         [ +  + ]:      146030 :         if (fuzzed_data_provider.ConsumeBool()) {
     390         [ +  - ]:       93003 :             tx_pool.RollingFeeUpdate();
     391                 :             :         }
     392         [ +  + ]:      146030 :         if (fuzzed_data_provider.ConsumeBool()) {
     393         [ +  + ]:       94951 :             const auto& txid = fuzzed_data_provider.ConsumeBool() ?
     394                 :       77172 :                                    tx->GetHash() :
     395                 :       17779 :                                    PickValue(fuzzed_data_provider, outpoints_rbf).hash;
     396                 :       94951 :             const auto delta = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-50 * COIN, +50 * COIN);
     397         [ +  - ]:       94951 :             tx_pool.PrioritiseTransaction(txid, delta);
     398                 :             :         }
     399                 :             : 
     400                 :             :         // Remember all removed and added transactions
     401         [ +  - ]:      146030 :         std::set<CTransactionRef> removed;
     402                 :      146030 :         std::set<CTransactionRef> added;
     403         [ +  - ]:      146030 :         auto txr = std::make_shared<TransactionsDelta>(removed, added);
     404   [ +  -  +  - ]:      292060 :         node.validation_signals->RegisterSharedValidationInterface(txr);
     405                 :             : 
     406                 :             :         // Make sure ProcessNewPackage on one transaction works.
     407                 :             :         // The result is not guaranteed to be the same as what is returned by ATMP.
     408         [ +  - ]:      730150 :         const auto result_package = WITH_LOCK(::cs_main,
           [ +  -  +  -  
          +  -  +  +  +  
             -  -  -  -  
                      - ]
     409                 :             :                                     return ProcessNewPackage(chainstate, tx_pool, {tx}, true, /*client_maxfeerate=*/{}));
     410                 :             :         // If something went wrong due to a package-specific policy, it might not return a
     411                 :             :         // validation result for the transaction.
     412         [ +  + ]:      146030 :         if (result_package.m_state.GetResult() != PackageValidationResult::PCKG_POLICY) {
     413                 :      143622 :             auto it = result_package.m_tx_results.find(tx->GetWitnessHash());
     414         [ -  + ]:      143622 :             Assert(it != result_package.m_tx_results.end());
     415   [ +  +  +  -  :      235045 :             Assert(it->second.m_result_type == MempoolAcceptResult::ResultType::VALID ||
                   -  + ]
     416                 :             :                    it->second.m_result_type == MempoolAcceptResult::ResultType::INVALID);
     417                 :             :         }
     418                 :             : 
     419         [ +  - ]:      438090 :         const auto res = WITH_LOCK(::cs_main, return AcceptToMemoryPool(chainstate, tx, GetTime(), /*bypass_limits=*/false, /*test_accept=*/false));
           [ +  -  +  - ]
     420                 :      146030 :         const bool accepted = res.m_result_type == MempoolAcceptResult::ResultType::VALID;
     421         [ +  - ]:      146030 :         node.validation_signals->SyncWithValidationInterfaceQueue();
     422   [ +  -  +  - ]:      292060 :         node.validation_signals->UnregisterSharedValidationInterface(txr);
     423                 :             : 
     424         [ +  - ]:      146030 :         bool txid_in_mempool = tx_pool.exists(tx->GetHash());
     425         [ +  - ]:      146030 :         bool wtxid_in_mempool = tx_pool.exists(tx->GetWitnessHash());
     426         [ +  - ]:      146030 :         CheckATMPInvariants(res, txid_in_mempool, wtxid_in_mempool);
     427                 :             : 
     428         [ -  + ]:      146030 :         Assert(accepted != added.empty());
     429         [ +  + ]:      146030 :         if (accepted) {
     430         [ -  + ]:       52845 :             Assert(added.size() == 1); // For now, no package acceptance
     431         [ -  + ]:       52845 :             Assert(tx == *added.begin());
     432         [ +  - ]:       52845 :             CheckMempoolTRUCInvariants(tx_pool);
     433                 :             :         } else {
     434                 :             :             // Do not consider rejected transaction removed
     435                 :       93185 :             removed.erase(tx);
     436                 :             :         }
     437                 :             : 
     438                 :             :         // Helper to insert spent and created outpoints of a tx into collections
     439                 :      146030 :         using Sets = std::vector<std::reference_wrapper<std::set<COutPoint>>>;
     440                 :      210791 :         const auto insert_tx = [](Sets created_by_tx, Sets consumed_by_tx, const auto& tx) {
     441   [ -  +  +  + ]:     1351179 :             for (size_t i{0}; i < tx.vout.size(); ++i) {
     442         [ +  + ]:     3753970 :                 for (auto& set : created_by_tx) {
     443         [ -  + ]:     2467552 :                     Assert(set.get().emplace(tx.GetHash(), i).second);
     444                 :             :                 }
     445                 :             :             }
     446         [ +  + ]:      204236 :             for (const auto& in : tx.vin) {
     447         [ +  + ]:      278950 :                 for (auto& set : consumed_by_tx) {
     448         [ -  + ]:      139475 :                     Assert(set.get().insert(in.prevout).second);
     449                 :             :                 }
     450                 :             :             }
     451                 :       64761 :         };
     452                 :             :         // Add created outpoints, remove spent outpoints
     453                 :      146030 :         {
     454                 :             :             // Outpoints that no longer exist at all
     455                 :      146030 :             std::set<COutPoint> consumed_erased;
     456                 :             :             // Outpoints that no longer count toward the total supply
     457                 :      146030 :             std::set<COutPoint> consumed_supply;
     458         [ +  + ]:      157946 :             for (const auto& removed_tx : removed) {
     459   [ +  -  +  -  :       23832 :                 insert_tx(/*created_by_tx=*/{consumed_erased}, /*consumed_by_tx=*/{outpoints_supply}, /*tx=*/*removed_tx);
                   +  - ]
     460                 :             :             }
     461         [ +  + ]:      198875 :             for (const auto& added_tx : added) {
     462   [ +  -  +  -  :      105690 :                 insert_tx(/*created_by_tx=*/{outpoints_supply, outpoints_rbf}, /*consumed_by_tx=*/{consumed_supply}, /*tx=*/*added_tx);
                   +  - ]
     463                 :             :             }
     464         [ +  + ]:      251314 :             for (const auto& p : consumed_erased) {
     465         [ -  + ]:      105284 :                 Assert(outpoints_supply.erase(p) == 1);
     466         [ -  + ]:      105284 :                 Assert(outpoints_rbf.erase(p) == 1);
     467                 :             :             }
     468         [ +  + ]:      256548 :             for (const auto& p : consumed_supply) {
     469         [ -  + ]:      110518 :                 Assert(outpoints_supply.erase(p) == 1);
     470                 :             :             }
     471                 :      146030 :         }
     472   [ +  -  +  - ]:      438090 :     }
     473         [ +  - ]:        4102 :     Finish(fuzzed_data_provider, tx_pool, chainstate);
     474                 :        4102 : }
     475                 :             : 
     476         [ +  - ]:       10735 : FUZZ_TARGET(tx_pool, .init = initialize_tx_pool)
     477                 :             : {
     478                 :       10259 :     SeedRandomStateForTest(SeedRand::ZEROS);
     479                 :       10259 :     FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
     480                 :       10259 :     const auto& node = g_setup->m_node;
     481                 :       10259 :     auto& chainstate{static_cast<DummyChainState&>(node.chainman->ActiveChainstate())};
     482                 :             : 
     483                 :       10259 :     MockTime(fuzzed_data_provider, chainstate);
     484                 :             : 
     485                 :       10259 :     std::vector<Txid> txids;
     486   [ -  +  +  - ]:       10259 :     txids.reserve(g_outpoints_coinbase_init_mature.size());
     487         [ +  + ]:     1036159 :     for (const auto& outpoint : g_outpoints_coinbase_init_mature) {
     488         [ +  - ]:     1025900 :         txids.push_back(outpoint.hash);
     489                 :             :     }
     490         [ +  + ]:       51295 :     for (int i{0}; i <= 3; ++i) {
     491                 :             :         // Add some immature and non-existent outpoints
     492   [ +  -  +  - ]:       41036 :         txids.push_back(g_outpoints_coinbase_init_immature.at(i).hash);
     493         [ +  - ]:       41036 :         txids.push_back(Txid::FromUint256(ConsumeUInt256(fuzzed_data_provider)));
     494                 :             :     }
     495                 :             : 
     496         [ +  - ]:       10259 :     SetMempoolConstraints(*node.args, fuzzed_data_provider);
     497         [ +  - ]:       10259 :     auto tx_pool_{MakeMempool(fuzzed_data_provider, node)};
     498                 :       10259 :     MockedTxPool& tx_pool = *static_cast<MockedTxPool*>(tx_pool_.get());
     499                 :             : 
     500                 :       10259 :     chainstate.SetMempool(&tx_pool);
     501                 :             : 
     502                 :             :     // If we ever bypass limits, do not do TRUC invariants checks
     503                 :       10259 :     bool ever_bypassed_limits{false};
     504                 :             : 
     505   [ +  +  +  + ]:      738648 :     LIMITED_WHILE (fuzzed_data_provider.ConsumeBool(), 300) {
     506         [ +  - ]:      728389 :         const auto mut_tx = ConsumeTransaction(fuzzed_data_provider, txids);
     507                 :             : 
     508         [ +  + ]:      728389 :         if (fuzzed_data_provider.ConsumeBool()) {
     509         [ +  - ]:      453155 :             MockTime(fuzzed_data_provider, chainstate);
     510                 :             :         }
     511         [ +  + ]:      728389 :         if (fuzzed_data_provider.ConsumeBool()) {
     512         [ +  - ]:      479023 :             tx_pool.RollingFeeUpdate();
     513                 :             :         }
     514         [ +  + ]:      728389 :         if (fuzzed_data_provider.ConsumeBool()) {
     515         [ +  + ]:      394971 :             const auto txid = fuzzed_data_provider.ConsumeBool() ?
     516         [ +  - ]:      324361 :                                    mut_tx.GetHash() :
     517                 :       70610 :                                    PickValue(fuzzed_data_provider, txids);
     518                 :      394971 :             const auto delta = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-50 * COIN, +50 * COIN);
     519         [ +  - ]:      394971 :             tx_pool.PrioritiseTransaction(txid, delta);
     520                 :             :         }
     521                 :             : 
     522                 :      728389 :         const bool bypass_limits{fuzzed_data_provider.ConsumeBool()};
     523                 :      728389 :         ever_bypassed_limits |= bypass_limits;
     524                 :             : 
     525         [ +  - ]:      728389 :         const auto tx = MakeTransactionRef(mut_tx);
     526         [ +  - ]:     2185167 :         const auto res = WITH_LOCK(::cs_main, return AcceptToMemoryPool(chainstate, tx, GetTime(), bypass_limits, /*test_accept=*/false));
           [ +  -  +  - ]
     527                 :      728389 :         const bool accepted = res.m_result_type == MempoolAcceptResult::ResultType::VALID;
     528         [ +  + ]:      728389 :         if (accepted) {
     529         [ +  - ]:      149670 :             txids.push_back(tx->GetHash());
     530         [ +  + ]:      149670 :             if (!ever_bypassed_limits) {
     531         [ +  - ]:        9274 :                 CheckMempoolTRUCInvariants(tx_pool);
     532                 :             :             }
     533                 :             :         }
     534         [ +  - ]:     2185167 :     }
     535         [ +  - ]:       10259 :     Finish(fuzzed_data_provider, tx_pool, chainstate);
     536                 :       10259 : }
     537                 :             : } // namespace
        

Generated by: LCOV version 2.5.0-full