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.7 % 318 314
Test Date: 2026-11-21 05:38:30 Functions: 100.0 % 30 30
Branches: 60.5 % 476 288

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

Generated by: LCOV version 2.5.0-full