LCOV - code coverage report
Current view: top level - src/test/fuzz - package_eval.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 100.0 % 278 278
Test Date: 2026-07-15 07:24:03 Functions: 100.0 % 23 23
Branches: 67.6 % 432 292

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2023-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 <consensus/amount.h>
       7                 :             : #include <consensus/consensus.h>
       8                 :             : #include <consensus/validation.h>
       9                 :             : #include <node/mining_types.h>
      10                 :             : #include <policy/feerate.h>
      11                 :             : #include <policy/packages.h>
      12                 :             : #include <policy/policy.h>
      13                 :             : #include <policy/settings.h>
      14                 :             : #include <policy/truc_policy.h>
      15                 :             : #include <primitives/transaction.h>
      16                 :             : #include <script/script.h>
      17                 :             : #include <sync.h>
      18                 :             : #include <test/fuzz/FuzzedDataProvider.h>
      19                 :             : #include <test/fuzz/fuzz.h>
      20                 :             : #include <test/fuzz/util.h>
      21                 :             : #include <test/fuzz/util/mempool.h>
      22                 :             : #include <test/util/mining.h>
      23                 :             : #include <test/util/random.h>
      24                 :             : #include <test/util/script.h>
      25                 :             : #include <test/util/setup_common.h>
      26                 :             : #include <test/util/txmempool.h>
      27                 :             : #include <txmempool.h>
      28                 :             : #include <util/check.h>
      29                 :             : #include <util/hasher.h>
      30                 :             : #include <util/time.h>
      31                 :             : #include <util/translation.h>
      32                 :             : #include <validation.h>
      33                 :             : #include <validationinterface.h>
      34                 :             : 
      35                 :             : #include <cstddef>
      36                 :             : #include <cstdint>
      37                 :             : #include <functional>
      38                 :             : #include <iterator>
      39                 :             : #include <limits>
      40                 :             : #include <map>
      41                 :             : #include <memory>
      42                 :             : #include <optional>
      43                 :             : #include <set>
      44                 :             : #include <span>
      45                 :             : #include <string>
      46                 :             : #include <unordered_map>
      47                 :             : #include <utility>
      48                 :             : #include <vector>
      49                 :             : using node::NodeContext;
      50                 :             : 
      51                 :             : namespace {
      52                 :             : 
      53                 :             : const TestingSetup* g_setup;
      54                 :             : std::vector<COutPoint> g_outpoints_coinbase_init_mature;
      55                 :             : 
      56                 :             : struct MockedTxPool : public CTxMemPool {
      57                 :       80368 :     void RollingFeeUpdate() EXCLUSIVE_LOCKS_REQUIRED(!cs)
      58                 :             :     {
      59                 :       80368 :         LOCK(cs);
      60         [ +  - ]:       80368 :         lastRollingFeeUpdate = GetTime();
      61         [ +  - ]:       80368 :         blockSinceLastRollingFeeBump = true;
      62                 :       80368 :     }
      63                 :             : };
      64                 :             : 
      65                 :           2 : void initialize_tx_pool()
      66                 :             : {
      67   [ +  -  +  -  :           2 :     static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>();
                   +  - ]
      68                 :           2 :     g_setup = testing_setup.get();
      69   [ +  -  +  - ]:           6 :     SetMockTime(WITH_LOCK(g_setup->m_node.chainman->GetMutex(), return g_setup->m_node.chainman->ActiveTip()->Time()));
      70                 :             : 
      71         [ +  + ]:         402 :     for (int i = 0; i < 2 * COINBASE_MATURITY; ++i) {
      72                 :        1200 :         COutPoint prevout{MineBlock(g_setup->m_node, {
      73                 :             :             .coinbase_output_script = P2WSH_EMPTY,
      74                 :             :         })};
      75         [ +  + ]:         400 :         if (i < COINBASE_MATURITY) {
      76                 :             :             // Remember the txids to avoid expensive disk access later on
      77                 :         200 :             g_outpoints_coinbase_init_mature.push_back(prevout);
      78                 :             :         }
      79                 :             :     }
      80                 :           2 :     g_setup->m_node.validation_signals->SyncWithValidationInterfaceQueue();
      81         [ +  - ]:         402 : }
      82                 :             : 
      83                 :             : struct OutpointsUpdater final : public CValidationInterface {
      84                 :             :     std::set<COutPoint>& m_mempool_outpoints;
      85                 :             : 
      86                 :        4969 :     explicit OutpointsUpdater(std::set<COutPoint>& r)
      87                 :        4969 :         : m_mempool_outpoints{r} {}
      88                 :             : 
      89                 :      187215 :     void TransactionAddedToMempool(const NewMempoolTransactionInfo& tx, uint64_t /* mempool_sequence */) override
      90                 :             :     {
      91                 :             :         // for coins spent we always want to be able to rbf so they're not removed
      92                 :             : 
      93                 :             :         // outputs from this tx can now be spent
      94   [ -  +  +  + ]:      883982 :         for (uint32_t index{0}; index < tx.info.m_tx->vout.size(); ++index) {
      95                 :      696767 :             m_mempool_outpoints.insert(COutPoint{tx.info.m_tx->GetHash(), index});
      96                 :             :         }
      97                 :      187215 :     }
      98                 :             : 
      99                 :       75416 :     void TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t /* mempool_sequence */) override
     100                 :             :     {
     101                 :             :         // outpoints spent by this tx are now available
     102         [ +  + ]:      205661 :         for (const auto& input : tx->vin) {
     103                 :             :             // Could already exist if this was a replacement
     104                 :      130245 :             m_mempool_outpoints.insert(input.prevout);
     105                 :             :         }
     106                 :             :         // outpoints created by this tx no longer exist
     107   [ -  +  +  + ]:      292695 :         for (uint32_t index{0}; index < tx->vout.size(); ++index) {
     108                 :      217279 :             m_mempool_outpoints.erase(COutPoint{tx->GetHash(), index});
     109                 :             :         }
     110                 :       75416 :     }
     111                 :             : };
     112                 :             : 
     113                 :             : struct TransactionsDelta final : public CValidationInterface {
     114                 :             :     std::set<CTransactionRef>& m_added;
     115                 :             : 
     116                 :      315679 :     explicit TransactionsDelta(std::set<CTransactionRef>& a)
     117                 :      315679 :         : m_added{a} {}
     118                 :             : 
     119                 :       61818 :     void TransactionAddedToMempool(const NewMempoolTransactionInfo& tx, uint64_t /* mempool_sequence */) override
     120                 :             :     {
     121                 :             :         // Transactions may be entered and booted any number of times
     122                 :       61818 :         m_added.insert(tx.info.m_tx);
     123                 :       61818 :     }
     124                 :             : 
     125                 :       45600 :     void TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t /* mempool_sequence */) override
     126                 :             :     {
     127                 :             :         // Transactions may be entered and booted any number of times
     128                 :       45600 :          m_added.erase(tx);
     129                 :       45600 :     }
     130                 :             : };
     131                 :             : 
     132                 :      163591 : void MockTime(FuzzedDataProvider& fuzzed_data_provider, const Chainstate& chainstate)
     133                 :             : {
     134                 :      163591 :     const auto time = ConsumeTime(fuzzed_data_provider,
     135                 :      163591 :                                   chainstate.m_chain.Tip()->GetMedianTimePast() + 1,
     136         [ -  + ]:      163591 :                                   std::numeric_limits<decltype(chainstate.m_chain.Tip()->nTime)>::max());
     137                 :      163591 :     SetMockTime(time);
     138                 :      163591 : }
     139                 :             : 
     140                 :        2871 : std::unique_ptr<CTxMemPool> MakeMempool(FuzzedDataProvider& fuzzed_data_provider, const NodeContext& node)
     141                 :             : {
     142                 :             :     // Take the default options for tests...
     143                 :        2871 :     CTxMemPool::Options mempool_opts{MemPoolOptionsForTest(node)};
     144                 :             : 
     145                 :             : 
     146                 :             :     // ...override specific options for this specific fuzz suite
     147                 :        2871 :     mempool_opts.limits.ancestor_count = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 50);
     148                 :        2871 :     mempool_opts.limits.descendant_count = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 50);
     149                 :        2871 :     mempool_opts.max_size_bytes = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 200) * 1'000'000;
     150                 :        2871 :     mempool_opts.expiry = std::chrono::hours{fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 999)};
     151                 :             :     // Only interested in 2 cases: sigop cost 0 or when single legacy sigop cost is >> 1KvB
     152                 :        2871 :     nBytesPerSigOp = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 1) * 10'000;
     153                 :             : 
     154                 :        2871 :     mempool_opts.check_ratio = 1;
     155                 :        2871 :     mempool_opts.require_standard = fuzzed_data_provider.ConsumeBool();
     156                 :             : 
     157         [ +  - ]:        2871 :     bilingual_str error;
     158                 :             :     // ...and construct a CTxMemPool from it
     159         [ +  - ]:        2871 :     auto mempool{std::make_unique<CTxMemPool>(std::move(mempool_opts), error)};
     160                 :             :     // ... ignore the error since it might be beneficial to fuzz even when the
     161                 :             :     // mempool size is unreasonably small
     162   [ +  +  +  -  :        3929 :     Assert(error.empty() || error.original.starts_with("-maxmempool must be at least "));
                   -  + ]
     163                 :        2871 :     return mempool;
     164                 :        2871 : }
     165                 :             : 
     166                 :        2098 : std::unique_ptr<CTxMemPool> MakeEphemeralMempool(const NodeContext& node)
     167                 :             : {
     168                 :             :     // Take the default options for tests...
     169                 :        2098 :     CTxMemPool::Options mempool_opts{MemPoolOptionsForTest(node)};
     170                 :             : 
     171                 :        2098 :     mempool_opts.check_ratio = 1;
     172                 :             : 
     173                 :             :     // Require standardness rules otherwise ephemeral dust is no-op
     174                 :        2098 :     mempool_opts.require_standard = true;
     175                 :             : 
     176                 :             :     // And set minrelay to 0 to allow ephemeral parent tx even with non-TRUC
     177         [ +  - ]:        2098 :     mempool_opts.min_relay_feerate = CFeeRate(0);
     178                 :             : 
     179         [ +  - ]:        2098 :     bilingual_str error;
     180                 :             :     // ...and construct a CTxMemPool from it
     181         [ +  - ]:        2098 :     auto mempool{std::make_unique<CTxMemPool>(std::move(mempool_opts), error)};
     182         [ -  + ]:        2098 :     Assert(error.empty());
     183                 :        2098 :     return mempool;
     184                 :        2098 : }
     185                 :             : 
     186                 :             : // Scan mempool for a tx that has spent dust and return a
     187                 :             : // prevout of the child that isn't the dusty parent itself.
     188                 :             : // This is used to double-spend the child out of the mempool,
     189                 :             : // leaving the parent childless.
     190                 :             : // This assumes CheckMempoolEphemeralInvariants has passed for tx_pool.
     191                 :      175411 : std::optional<COutPoint> GetChildEvictingPrevout(const CTxMemPool& tx_pool)
     192                 :             : {
     193                 :      175411 :     LOCK(tx_pool.cs);
     194   [ +  -  +  + ]:     6950601 :     for (const auto& tx_info : tx_pool.infoAll()) {
     195   [ +  -  -  + ]:     6780739 :         const auto& entry = *Assert(tx_pool.GetEntry(tx_info.tx->GetHash()));
     196         [ +  - ]:     6780739 :         std::vector<uint32_t> dust_indexes{GetDust(*tx_info.tx, tx_pool.m_opts.dust_relay_feerate)};
     197         [ +  + ]:     6780739 :         if (!dust_indexes.empty()) {
     198         [ +  - ]:       11700 :             const auto& children = tx_pool.GetChildren(entry);
     199         [ +  + ]:       11700 :             if (!children.empty()) {
     200   [ -  +  -  + ]:        6269 :                 Assert(children.size() == 1);
     201                 :             :                 // Find an input that doesn't spend from parent's txid
     202                 :        6269 :                 const auto& only_child = children.begin()->get().GetTx();
     203         [ +  + ]:       11683 :                 for (const auto& tx_input : only_child.vin) {
     204         [ +  + ]:       10963 :                     if (tx_input.prevout.hash != tx_info.tx->GetHash()) {
     205                 :        5549 :                         return tx_input.prevout;
     206                 :             :                     }
     207                 :             :                 }
     208                 :             :             }
     209                 :       11700 :         }
     210                 :     6950601 :     }
     211                 :             : 
     212                 :      169862 :     return std::nullopt;
     213                 :      175411 : }
     214                 :             : 
     215         [ +  - ]:        2570 : FUZZ_TARGET(ephemeral_package_eval, .init = initialize_tx_pool)
     216                 :             : {
     217                 :        2098 :     SeedRandomStateForTest(SeedRand::ZEROS);
     218                 :        2098 :     FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
     219                 :        2098 :     const auto& node = g_setup->m_node;
     220                 :        2098 :     auto& chainstate{static_cast<DummyChainState&>(node.chainman->ActiveChainstate())};
     221                 :             : 
     222                 :        2098 :     MockTime(fuzzed_data_provider, chainstate);
     223                 :             : 
     224                 :             :     // All RBF-spendable outpoints outside of the unsubmitted package
     225         [ +  - ]:        2098 :     std::set<COutPoint> mempool_outpoints;
     226         [ +  - ]:        2098 :     std::unordered_map<COutPoint, CAmount, SaltedOutpointHasher> outpoints_value;
     227         [ +  + ]:      211898 :     for (const auto& outpoint : g_outpoints_coinbase_init_mature) {
     228         [ +  - ]:      209800 :         Assert(mempool_outpoints.insert(outpoint).second);
     229         [ +  - ]:      209800 :         outpoints_value[outpoint] = 50 * COIN;
     230                 :             :     }
     231                 :             : 
     232         [ +  - ]:        2098 :     auto outpoints_updater = std::make_shared<OutpointsUpdater>(mempool_outpoints);
     233   [ +  -  +  - ]:        4196 :     node.validation_signals->RegisterSharedValidationInterface(outpoints_updater);
     234                 :             : 
     235         [ +  - ]:        2098 :     auto tx_pool_{MakeEphemeralMempool(node)};
     236                 :        2098 :     MockedTxPool& tx_pool = *static_cast<MockedTxPool*>(tx_pool_.get());
     237                 :             : 
     238                 :        2098 :     chainstate.SetMempool(&tx_pool);
     239                 :             : 
     240   [ +  +  +  + ]:      381892 :     LIMITED_WHILE (fuzzed_data_provider.remaining_bytes() > 0, 300) {
     241         [ -  + ]:      379794 :         Assert(!mempool_outpoints.empty());
     242                 :             : 
     243                 :      379794 :         std::vector<CTransactionRef> txs;
     244                 :             : 
     245                 :             :         // Find something we may want to double-spend with two input single tx
     246   [ +  +  +  - ]:      379794 :         std::optional<COutPoint> outpoint_to_rbf{fuzzed_data_provider.ConsumeBool() ? GetChildEvictingPrevout(tx_pool) : std::nullopt};
     247                 :             : 
     248                 :             :         // Make small packages
     249         [ +  + ]:      379794 :         const auto num_txs = outpoint_to_rbf ? 1 : fuzzed_data_provider.ConsumeIntegralInRange<size_t>(1, 4);
     250                 :             : 
     251                 :      379794 :         std::set<COutPoint> package_outpoints;
     252   [ -  +  +  + ]:     1253611 :         while (txs.size() < num_txs) {
     253                 :             :             // Create transaction to add to the mempool
     254         [ +  - ]:     1747634 :             txs.emplace_back([&] {
     255                 :      873817 :                 CMutableTransaction tx_mut;
     256                 :      873817 :                 tx_mut.version = CTransaction::CURRENT_VERSION;
     257                 :      873817 :                 tx_mut.nLockTime = 0;
     258                 :             :                 // Last transaction in a package needs to be a child of parents to get further in validation
     259                 :             :                 // so the last transaction to be generated(in a >1 package) must spend all package-made outputs
     260                 :             :                 // Note that this test currently only spends package outputs in last transaction.
     261   [ +  +  -  +  :      873817 :                 bool last_tx = num_txs > 1 && txs.size() == num_txs - 1;
                   +  + ]
     262         [ +  + ]:      873817 :                 const auto num_in = outpoint_to_rbf ? 2 :
     263         [ +  + ]:      868268 :                     last_tx ? fuzzed_data_provider.ConsumeIntegralInRange<int>(package_outpoints.size()/2 + 1, package_outpoints.size()) :
     264                 :      614268 :                     fuzzed_data_provider.ConsumeIntegralInRange<int>(1, 4);
     265         [ +  + ]:      873817 :                 const auto num_out = outpoint_to_rbf ? 1 : fuzzed_data_provider.ConsumeIntegralInRange<int>(1, 4);
     266                 :             : 
     267         [ +  + ]:      873817 :                 auto& outpoints = last_tx ? package_outpoints : mempool_outpoints;
     268                 :             : 
     269   [ +  -  -  +  :      873817 :                 Assert((int)outpoints.size() >= num_in && num_in > 0);
                   -  + ]
     270                 :             : 
     271                 :             :                 CAmount amount_in{0};
     272         [ +  + ]:     3259379 :                 for (int i = 0; i < num_in; ++i) {
     273                 :             :                     // Pop random outpoint. We erase them to avoid double-spending
     274                 :             :                     // while in this loop, but later add them back (unless last_tx).
     275                 :     2385562 :                     auto pop = outpoints.begin();
     276                 :     2385562 :                     std::advance(pop, fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, outpoints.size() - 1));
     277         [ +  + ]:     2385562 :                     auto outpoint = *pop;
     278                 :             : 
     279   [ +  +  +  + ]:     2385562 :                     if (i == 0 && outpoint_to_rbf) {
     280                 :        5549 :                         outpoint = *outpoint_to_rbf;
     281                 :        5549 :                         outpoints.erase(outpoint);
     282                 :             :                     } else {
     283                 :     2380013 :                         outpoints.erase(pop);
     284                 :             :                     }
     285                 :             :                     // no need to update or erase from outpoints_value
     286         [ +  - ]:     2385562 :                     amount_in += outpoints_value.at(outpoint);
     287                 :             : 
     288                 :             :                     // Create input
     289                 :     2385562 :                     CTxIn in;
     290                 :     2385562 :                     in.prevout = outpoint;
     291         [ +  - ]:     2385562 :                     in.scriptWitness.stack = P2WSH_EMPTY_TRUE_STACK;
     292                 :             : 
     293         [ +  - ]:     2385562 :                     tx_mut.vin.push_back(in);
     294                 :     2385562 :                 }
     295                 :             : 
     296                 :      873817 :                 const auto amount_fee = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(0, amount_in);
     297                 :      873817 :                 const auto amount_out = (amount_in - amount_fee) / num_out;
     298         [ +  + ]:     2895488 :                 for (int i = 0; i < num_out; ++i) {
     299         [ +  - ]:     2021671 :                     tx_mut.vout.emplace_back(amount_out, P2WSH_EMPTY);
     300                 :             :                 }
     301                 :             : 
     302                 :             :                 // Note output amounts can naturally drop to dust on their own.
     303   [ +  +  +  + ]:      873817 :                 if (!outpoint_to_rbf && fuzzed_data_provider.ConsumeBool()) {
     304                 :      280326 :                     uint32_t dust_index = fuzzed_data_provider.ConsumeIntegralInRange<uint32_t>(0, num_out);
     305   [ +  -  +  - ]:      280326 :                     tx_mut.vout.insert(tx_mut.vout.begin() + dust_index, CTxOut(0, P2WSH_EMPTY));
     306                 :             :                 }
     307                 :             : 
     308         [ +  - ]:      873817 :                 auto tx = MakeTransactionRef(tx_mut);
     309                 :             :                 // Restore previously removed outpoints, except in-package outpoints (to allow RBF)
     310         [ +  + ]:      873817 :                 if (!last_tx) {
     311         [ +  + ]:     1999774 :                     for (const auto& in : tx->vin) {
     312         [ +  - ]:     2759914 :                         Assert(outpoints.insert(in.prevout).second);
     313                 :             :                     }
     314                 :             :                     // Cache the in-package outpoints being made
     315   [ -  +  +  + ]:     2180465 :                     for (size_t i = 0; i < tx->vout.size(); ++i) {
     316         [ +  - ]:     1560648 :                         package_outpoints.emplace(tx->GetHash(), i);
     317                 :             :                     }
     318                 :             :                 }
     319                 :             :                 // We need newly-created values for the duration of this run
     320   [ -  +  +  + ]:     3175814 :                 for (size_t i = 0; i < tx->vout.size(); ++i) {
     321         [ +  - ]:     2301997 :                     outpoints_value[COutPoint(tx->GetHash(), i)] = tx->vout[i].nValue;
     322                 :             :                 }
     323                 :      873817 :                 return tx;
     324         [ +  - ]:     2621451 :             }());
     325                 :             :         }
     326                 :             : 
     327         [ +  + ]:      379794 :         if (fuzzed_data_provider.ConsumeBool()) {
     328         [ +  + ]:      152689 :             const auto& txid = fuzzed_data_provider.ConsumeBool() ?
     329                 :       50407 :                                    txs.back()->GetHash() :
     330                 :      102282 :                                    PickValue(fuzzed_data_provider, mempool_outpoints).hash;
     331                 :      152689 :             const auto delta = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-50 * COIN, +50 * COIN);
     332                 :             :             // We only prioritise out of mempool transactions since PrioritiseTransaction doesn't
     333                 :             :             // filter for ephemeral dust
     334   [ +  -  +  + ]:      152689 :             if (tx_pool.exists(txid)) {
     335         [ +  - ]:       43122 :                 const auto tx_info{tx_pool.info(txid)};
     336   [ +  -  +  + ]:       43122 :                 if (GetDust(*tx_info.tx, tx_pool.m_opts.dust_relay_feerate).empty()) {
     337         [ +  - ]:       42944 :                     tx_pool.PrioritiseTransaction(txid, delta);
     338                 :             :                 }
     339                 :       43122 :             }
     340                 :             :         }
     341                 :             : 
     342         [ -  + ]:      379794 :         auto single_submit = txs.size() == 1;
     343                 :             : 
     344         [ +  - ]:     1139382 :         const auto result_package = WITH_LOCK(::cs_main,
     345                 :             :                                     return ProcessNewPackage(chainstate, tx_pool, txs, /*test_accept=*/single_submit, /*client_maxfeerate=*/{}));
     346                 :             : 
     347   [ +  -  +  - ]:     1139382 :         const auto res = WITH_LOCK(::cs_main, return AcceptToMemoryPool(chainstate, txs.back(), GetTime(),
     348                 :             :                                    /*bypass_limits=*/false, /*test_accept=*/!single_submit));
     349                 :             : 
     350   [ +  +  +  + ]:      379794 :         if (!single_submit && result_package.m_state.GetResult() != PackageValidationResult::PCKG_POLICY) {
     351                 :             :             // We don't know anything about the validity since transactions were randomly generated, so
     352                 :             :             // just use result_package.m_state here. This makes the expect_valid check meaningless, but
     353                 :             :             // we can still verify that the contents of m_tx_results are consistent with m_state.
     354         [ +  - ]:      144673 :             const bool expect_valid{result_package.m_state.IsValid()};
     355   [ +  -  -  + ]:      144673 :             Assert(!CheckPackageMempoolAcceptResult(txs, result_package, expect_valid, &tx_pool));
     356                 :             :         }
     357                 :             : 
     358         [ +  - ]:      379794 :         node.validation_signals->SyncWithValidationInterfaceQueue();
     359                 :             : 
     360         [ +  - ]:      379794 :         CheckMempoolEphemeralInvariants(tx_pool);
     361                 :      379794 :     }
     362                 :             : 
     363   [ +  -  +  - ]:        4196 :     node.validation_signals->UnregisterSharedValidationInterface(outpoints_updater);
     364                 :             : 
     365   [ +  +  +  -  :        6294 :     WITH_LOCK(::cs_main, tx_pool.check(chainstate.CoinsTip(), chainstate.m_chain.Height() + 1));
                   +  - ]
     366         [ +  - ]:        4196 : }
     367                 :             : 
     368                 :             : 
     369         [ +  - ]:        3343 : FUZZ_TARGET(tx_package_eval, .init = initialize_tx_pool)
     370                 :             : {
     371                 :        2871 :     SeedRandomStateForTest(SeedRand::ZEROS);
     372                 :        2871 :     FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
     373                 :        2871 :     const auto& node = g_setup->m_node;
     374                 :        2871 :     auto& chainstate{static_cast<DummyChainState&>(node.chainman->ActiveChainstate())};
     375                 :             : 
     376                 :        2871 :     MockTime(fuzzed_data_provider, chainstate);
     377                 :             : 
     378                 :             :     // All RBF-spendable outpoints outside of the unsubmitted package
     379         [ +  - ]:        2871 :     std::set<COutPoint> mempool_outpoints;
     380         [ +  - ]:        2871 :     std::unordered_map<COutPoint, CAmount, SaltedOutpointHasher> outpoints_value;
     381         [ +  + ]:      289971 :     for (const auto& outpoint : g_outpoints_coinbase_init_mature) {
     382         [ +  - ]:      287100 :         Assert(mempool_outpoints.insert(outpoint).second);
     383         [ +  - ]:      287100 :         outpoints_value[outpoint] = 50 * COIN;
     384                 :             :     }
     385                 :             : 
     386         [ +  - ]:        2871 :     auto outpoints_updater = std::make_shared<OutpointsUpdater>(mempool_outpoints);
     387   [ +  -  +  - ]:        5742 :     node.validation_signals->RegisterSharedValidationInterface(outpoints_updater);
     388                 :             : 
     389         [ +  - ]:        2871 :     auto tx_pool_{MakeMempool(fuzzed_data_provider, node)};
     390                 :        2871 :     MockedTxPool& tx_pool = *static_cast<MockedTxPool*>(tx_pool_.get());
     391                 :             : 
     392                 :        2871 :     chainstate.SetMempool(&tx_pool);
     393                 :             : 
     394   [ +  +  +  + ]:      318550 :     LIMITED_WHILE (fuzzed_data_provider.remaining_bytes() > 0, 300) {
     395         [ -  + ]:      315679 :         Assert(!mempool_outpoints.empty());
     396                 :             : 
     397                 :      315679 :         std::vector<CTransactionRef> txs;
     398                 :             : 
     399                 :             :         // Make packages of 1-to-26 transactions
     400                 :      315679 :         const auto num_txs = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(1, 26);
     401                 :      315679 :         std::set<COutPoint> package_outpoints;
     402   [ -  +  +  + ]:     1092740 :         while (txs.size() < num_txs) {
     403                 :             :             // Create transaction to add to the mempool
     404         [ +  - ]:     1554122 :             txs.emplace_back([&] {
     405                 :      777061 :                 CMutableTransaction tx_mut;
     406         [ +  + ]:      777061 :                 tx_mut.version = fuzzed_data_provider.ConsumeBool() ? TRUC_VERSION : CTransaction::CURRENT_VERSION;
     407         [ +  + ]:      777061 :                 tx_mut.nLockTime = fuzzed_data_provider.ConsumeBool() ? 0 : fuzzed_data_provider.ConsumeIntegral<uint32_t>();
     408                 :             :                 // Last transaction in a package needs to be a child of parents to get further in validation
     409                 :             :                 // so the last transaction to be generated(in a >1 package) must spend all package-made outputs
     410                 :             :                 // Note that this test currently only spends package outputs in last transaction.
     411   [ +  +  -  +  :      777061 :                 bool last_tx = num_txs > 1 && txs.size() == num_txs - 1;
                   +  + ]
     412                 :      777061 :                 const auto num_in = last_tx ? package_outpoints.size()  : fuzzed_data_provider.ConsumeIntegralInRange<int>(1, mempool_outpoints.size());
     413                 :      777061 :                 auto num_out = fuzzed_data_provider.ConsumeIntegralInRange<int>(1, mempool_outpoints.size() * 2);
     414                 :             : 
     415         [ +  + ]:      777061 :                 auto& outpoints = last_tx ? package_outpoints : mempool_outpoints;
     416                 :             : 
     417         [ -  + ]:      777061 :                 Assert(!outpoints.empty());
     418                 :             : 
     419                 :             :                 CAmount amount_in{0};
     420         [ +  + ]:    14962170 :                 for (size_t i = 0; i < num_in; ++i) {
     421                 :             :                     // Pop random outpoint. We erase them to avoid double-spending
     422                 :             :                     // while in this loop, but later add them back (unless last_tx).
     423                 :    14185109 :                     auto pop = outpoints.begin();
     424                 :    14185109 :                     std::advance(pop, fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, outpoints.size() - 1));
     425                 :    14185109 :                     const auto outpoint = *pop;
     426                 :    14185109 :                     outpoints.erase(pop);
     427                 :             :                     // no need to update or erase from outpoints_value
     428         [ +  - ]:    14185109 :                     amount_in += outpoints_value.at(outpoint);
     429                 :             : 
     430                 :             :                     // Create input
     431                 :    14185109 :                     const auto sequence = ConsumeSequence(fuzzed_data_provider);
     432                 :    14185109 :                     const auto script_sig = CScript{};
     433   [ +  +  +  - ]:    22531245 :                     const auto script_wit_stack = fuzzed_data_provider.ConsumeBool() ? P2WSH_EMPTY_TRUE_STACK : P2WSH_EMPTY_TWO_STACK;
     434                 :             : 
     435                 :    14185109 :                     CTxIn in;
     436                 :    14185109 :                     in.prevout = outpoint;
     437                 :    14185109 :                     in.nSequence = sequence;
     438                 :    14185109 :                     in.scriptSig = script_sig;
     439         [ +  - ]:    14185109 :                     in.scriptWitness.stack = script_wit_stack;
     440                 :             : 
     441         [ +  - ]:    14185109 :                     tx_mut.vin.push_back(in);
     442                 :    14185109 :                 }
     443                 :             : 
     444                 :             :                 // Duplicate an input
     445                 :      777061 :                 bool dup_input = fuzzed_data_provider.ConsumeBool();
     446         [ +  + ]:      777061 :                 if (dup_input) {
     447         [ +  - ]:      248094 :                     tx_mut.vin.push_back(tx_mut.vin.back());
     448                 :             :                 }
     449                 :             : 
     450                 :             :                 // Refer to a non-existent input
     451         [ +  + ]:      777061 :                 if (fuzzed_data_provider.ConsumeBool()) {
     452         [ +  - ]:      225367 :                     tx_mut.vin.emplace_back();
     453                 :             :                 }
     454                 :             : 
     455                 :             :                 // Make a p2pk output to make sigops adjusted vsize to violate TRUC rules, potentially, which is never spent
     456   [ +  +  +  + ]:      777061 :                 if (last_tx && amount_in > 1000 && fuzzed_data_provider.ConsumeBool()) {
     457   [ +  -  +  -  :      115122 :                     tx_mut.vout.emplace_back(1000, CScript() << std::vector<unsigned char>(33, 0x02) << OP_CHECKSIG);
                   +  - ]
     458                 :             :                     // Don't add any other outputs.
     459                 :       38374 :                     num_out = 1;
     460                 :       38374 :                     amount_in -= 1000;
     461                 :             :                 }
     462                 :             : 
     463                 :      777061 :                 const auto amount_fee = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(0, amount_in);
     464                 :      777061 :                 const auto amount_out = (amount_in - amount_fee) / num_out;
     465         [ +  + ]:    18641815 :                 for (int i = 0; i < num_out; ++i) {
     466         [ +  - ]:    17864754 :                     tx_mut.vout.emplace_back(amount_out, P2WSH_EMPTY);
     467                 :             :                 }
     468         [ +  - ]:      777061 :                 auto tx = MakeTransactionRef(tx_mut);
     469                 :             :                 // Restore previously removed outpoints, except in-package outpoints
     470         [ +  + ]:      777061 :                 if (!last_tx) {
     471         [ +  + ]:     7769347 :                     for (const auto& in : tx->vin) {
     472                 :             :                         // It's a fake input, or a new input, or a duplicate
     473   [ +  +  +  -  :    14397741 :                         Assert(in == CTxIn() || outpoints.insert(in.prevout).second || dup_input);
          +  +  +  -  -  
                      + ]
     474                 :             :                     }
     475                 :             :                     // Cache the in-package outpoints being made
     476   [ -  +  +  + ]:    17236110 :                     for (size_t i = 0; i < tx->vout.size(); ++i) {
     477         [ +  - ]:    16556733 :                         package_outpoints.emplace(tx->GetHash(), i);
     478                 :             :                     }
     479                 :             :                 }
     480                 :             :                 // We need newly-created values for the duration of this run
     481   [ -  +  +  + ]:    18680189 :                 for (size_t i = 0; i < tx->vout.size(); ++i) {
     482         [ +  - ]:    17903128 :                     outpoints_value[COutPoint(tx->GetHash(), i)] = tx->vout[i].nValue;
     483                 :             :                 }
     484                 :      777061 :                 return tx;
     485         [ +  - ]:     2331183 :             }());
     486                 :             :         }
     487                 :             : 
     488         [ +  + ]:      315679 :         if (fuzzed_data_provider.ConsumeBool()) {
     489         [ +  - ]:      158622 :             MockTime(fuzzed_data_provider, chainstate);
     490                 :             :         }
     491         [ +  + ]:      315679 :         if (fuzzed_data_provider.ConsumeBool()) {
     492         [ +  - ]:       80368 :             tx_pool.RollingFeeUpdate();
     493                 :             :         }
     494         [ +  + ]:      315679 :         if (fuzzed_data_provider.ConsumeBool()) {
     495         [ +  + ]:      101350 :             const auto& txid = fuzzed_data_provider.ConsumeBool() ?
     496                 :       50348 :                                    txs.back()->GetHash() :
     497                 :       51002 :                                    PickValue(fuzzed_data_provider, mempool_outpoints).hash;
     498                 :      101350 :             const auto delta = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-50 * COIN, +50 * COIN);
     499         [ +  - ]:      101350 :             tx_pool.PrioritiseTransaction(txid, delta);
     500                 :             :         }
     501                 :             : 
     502                 :             :         // Remember all added transactions
     503         [ +  - ]:      315679 :         std::set<CTransactionRef> added;
     504         [ +  - ]:      315679 :         auto txr = std::make_shared<TransactionsDelta>(added);
     505   [ +  -  +  - ]:      631358 :         node.validation_signals->RegisterSharedValidationInterface(txr);
     506                 :             : 
     507                 :             :         // When there are multiple transactions in the package, we call ProcessNewPackage(txs, test_accept=false)
     508                 :             :         // and AcceptToMemoryPool(txs.back(), test_accept=true). When there is only 1 transaction, we might flip it
     509                 :             :         // (the package is a test accept and ATMP is a submission).
     510   [ -  +  +  +  :      533674 :         auto single_submit = txs.size() == 1 && fuzzed_data_provider.ConsumeBool();
                   +  + ]
     511                 :             : 
     512                 :             :         // Exercise client_maxfeerate logic
     513                 :      315679 :         std::optional<CFeeRate> client_maxfeerate{};
     514         [ +  + ]:      315679 :         if (fuzzed_data_provider.ConsumeBool()) {
     515         [ +  - ]:       73277 :             client_maxfeerate = CFeeRate(fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-1, 50 * COIN), 100);
     516                 :             :         }
     517                 :             : 
     518         [ +  - ]:      947037 :         const auto result_package = WITH_LOCK(::cs_main,
     519                 :             :                                     return ProcessNewPackage(chainstate, tx_pool, txs, /*test_accept=*/single_submit, client_maxfeerate));
     520                 :             : 
     521                 :             :         // Always set bypass_limits to false because it is not supported in ProcessNewPackage and
     522                 :             :         // can be a source of divergence.
     523   [ +  -  +  - ]:      947037 :         const auto res = WITH_LOCK(::cs_main, return AcceptToMemoryPool(chainstate, txs.back(), GetTime(),
     524                 :             :                                    /*bypass_limits=*/false, /*test_accept=*/!single_submit));
     525                 :      315679 :         const bool passed = res.m_result_type == MempoolAcceptResult::ResultType::VALID;
     526                 :             : 
     527         [ +  - ]:      315679 :         node.validation_signals->SyncWithValidationInterfaceQueue();
     528   [ +  -  +  - ]:      631358 :         node.validation_signals->UnregisterSharedValidationInterface(txr);
     529                 :             : 
     530                 :             :         // There is only 1 transaction in the package. We did a test-package-accept and a ATMP
     531         [ +  + ]:      315679 :         if (single_submit) {
     532         [ -  + ]:       32558 :             Assert(passed != added.empty());
     533         [ -  + ]:       32558 :             Assert(passed == res.m_state.IsValid());
     534         [ +  + ]:       32558 :             if (passed) {
     535         [ -  + ]:        3855 :                 Assert(added.size() == 1);
     536         [ -  + ]:        3855 :                 Assert(txs.back() == *added.begin());
     537                 :             :             }
     538         [ +  + ]:      283121 :         } else if (result_package.m_state.GetResult() != PackageValidationResult::PCKG_POLICY) {
     539                 :             :             // We don't know anything about the validity since transactions were randomly generated, so
     540                 :             :             // just use result_package.m_state here. This makes the expect_valid check meaningless, but
     541                 :             :             // we can still verify that the contents of m_tx_results are consistent with m_state.
     542         [ +  - ]:      235287 :             const bool expect_valid{result_package.m_state.IsValid()};
     543   [ +  -  -  + ]:      235287 :             Assert(!CheckPackageMempoolAcceptResult(txs, result_package, expect_valid, &tx_pool));
     544                 :             :         } else {
     545                 :             :             // This is empty if it fails early checks, or "full" if transactions are looked at deeper
     546   [ -  +  +  +  :       89446 :             Assert(result_package.m_tx_results.size() == txs.size() || result_package.m_tx_results.empty());
             +  -  -  + ]
     547                 :             :         }
     548                 :             : 
     549         [ +  - ]:      315679 :         CheckMempoolTRUCInvariants(tx_pool);
     550                 :             : 
     551                 :             :         // Dust checks only make sense when dust is enforced
     552         [ +  + ]:      315679 :         if (tx_pool.m_opts.require_standard) {
     553         [ +  - ]:      181958 :             CheckMempoolEphemeralInvariants(tx_pool);
     554                 :             :         }
     555         [ +  - ]:      631358 :     }
     556                 :             : 
     557   [ +  -  +  - ]:        5742 :     node.validation_signals->UnregisterSharedValidationInterface(outpoints_updater);
     558                 :             : 
     559   [ +  +  +  -  :        8613 :     WITH_LOCK(::cs_main, tx_pool.check(chainstate.CoinsTip(), chainstate.m_chain.Height() + 1));
                   +  - ]
     560         [ +  - ]:        5742 : }
     561                 :             : } // namespace
        

Generated by: LCOV version 2.0-1