LCOV - code coverage report
Current view: top level - src/test/fuzz - package_eval.cpp (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 10 175 5.7 %
Date: 2023-11-06 23:13:05 Functions: 1 23 4.3 %
Branches: 10 242 4.1 %

           Branch data     Line data    Source code
       1                 :            : // Copyright (c) 2023 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 <consensus/validation.h>
       6                 :            : #include <node/context.h>
       7                 :            : #include <node/mempool_args.h>
       8                 :            : #include <node/miner.h>
       9                 :            : #include <test/fuzz/FuzzedDataProvider.h>
      10                 :            : #include <test/fuzz/fuzz.h>
      11         [ +  - ]:          2 : #include <test/fuzz/util.h>
      12         [ +  - ]:          2 : #include <test/fuzz/util/mempool.h>
      13                 :          2 : #include <test/util/mining.h>
      14         [ +  - ]:          2 : #include <test/util/script.h>
      15 [ +  - ][ +  - ]:          2 : #include <test/util/setup_common.h>
                 [ +  - ]
      16                 :            : #include <test/util/txmempool.h>
      17         [ +  - ]:          2 : #include <util/rbf.h>
      18         [ +  - ]:          2 : #include <validation.h>
      19                 :            : #include <validationinterface.h>
      20                 :            : 
      21                 :            : using node::NodeContext;
      22                 :            : 
      23                 :            : namespace {
      24                 :            : 
      25                 :            : const TestingSetup* g_setup;
      26                 :          2 : std::vector<COutPoint> g_outpoints_coinbase_init_mature;
      27                 :            : 
      28                 :            : struct MockedTxPool : public CTxMemPool {
      29                 :          0 :     void RollingFeeUpdate() EXCLUSIVE_LOCKS_REQUIRED(!cs)
      30                 :            :     {
      31                 :          0 :         LOCK(cs);
      32         [ #  # ]:          0 :         lastRollingFeeUpdate = GetTime();
      33                 :          0 :         blockSinceLastRollingFeeBump = true;
      34                 :          0 :     }
      35                 :            : };
      36                 :            : 
      37                 :          0 : void initialize_tx_pool()
      38                 :            : {
      39 [ #  # ][ #  # ]:          0 :     static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>();
                 [ #  # ]
      40                 :          0 :     g_setup = testing_setup.get();
      41                 :            : 
      42         [ #  # ]:          0 :     for (int i = 0; i < 2 * COINBASE_MATURITY; ++i) {
      43                 :          0 :         COutPoint prevout{MineBlock(g_setup->m_node, P2WSH_OP_TRUE)};
      44         [ #  # ]:          0 :         if (i < COINBASE_MATURITY) {
      45                 :            :             // Remember the txids to avoid expensive disk access later on
      46                 :          0 :             g_outpoints_coinbase_init_mature.push_back(prevout);
      47                 :          0 :         }
      48                 :          0 :     }
      49                 :          0 :     SyncWithValidationInterfaceQueue();
      50                 :          0 : }
      51                 :            : 
      52                 :            : struct OutpointsUpdater final : public CValidationInterface {
      53                 :            :     std::set<COutPoint>& m_mempool_outpoints;
      54                 :            : 
      55                 :          0 :     explicit OutpointsUpdater(std::set<COutPoint>& r)
      56                 :          0 :         : m_mempool_outpoints{r} {}
      57                 :            : 
      58                 :          0 :     void TransactionAddedToMempool(const CTransactionRef& tx, uint64_t /* mempool_sequence */) override
      59                 :            :     {
      60                 :            :         // for coins spent we always want to be able to rbf so they're not removed
      61                 :            : 
      62                 :            :         // outputs from this tx can now be spent
      63         [ #  # ]:          0 :         for (uint32_t index{0}; index < tx->vout.size(); ++index) {
      64                 :          0 :             m_mempool_outpoints.insert(COutPoint{tx->GetHash(), index});
      65                 :          0 :         }
      66                 :          0 :     }
      67                 :            : 
      68                 :          0 :     void TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t /* mempool_sequence */) override
      69                 :            :     {
      70                 :            :         // outpoints spent by this tx are now available
      71         [ #  # ]:          0 :         for (const auto& input : tx->vin) {
      72                 :            :             // Could already exist if this was a replacement
      73                 :          0 :             m_mempool_outpoints.insert(input.prevout);
      74                 :            :         }
      75                 :            :         // outpoints created by this tx no longer exist
      76         [ #  # ]:          0 :         for (uint32_t index{0}; index < tx->vout.size(); ++index) {
      77                 :          0 :             m_mempool_outpoints.erase(COutPoint{tx->GetHash(), index});
      78                 :          0 :         }
      79                 :          0 :     }
      80                 :            : };
      81                 :            : 
      82                 :            : struct TransactionsDelta final : public CValidationInterface {
      83         [ +  - ]:          2 :     std::set<CTransactionRef>& m_added;
      84                 :            : 
      85                 :          0 :     explicit TransactionsDelta(std::set<CTransactionRef>& a)
      86                 :          0 :         : m_added{a} {}
      87                 :            : 
      88                 :          0 :     void TransactionAddedToMempool(const CTransactionRef& tx, uint64_t /* mempool_sequence */) override
      89                 :            :     {
      90                 :            :         // Transactions may be entered and booted any number of times
      91                 :          0 :         m_added.insert(tx);
      92                 :          0 :     }
      93                 :            : 
      94                 :          0 :     void TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t /* mempool_sequence */) override
      95                 :            :     {
      96                 :            :         // Transactions may be entered and booted any number of times
      97                 :          0 :          m_added.erase(tx);
      98                 :          0 :     }
      99                 :            : };
     100                 :            : 
     101                 :          0 : void MockTime(FuzzedDataProvider& fuzzed_data_provider, const Chainstate& chainstate)
     102                 :            : {
     103                 :          0 :     const auto time = ConsumeTime(fuzzed_data_provider,
     104                 :          0 :                                   chainstate.m_chain.Tip()->GetMedianTimePast() + 1,
     105                 :          0 :                                   std::numeric_limits<decltype(chainstate.m_chain.Tip()->nTime)>::max());
     106                 :          0 :     SetMockTime(time);
     107                 :          0 : }
     108                 :            : 
     109                 :          0 : CTxMemPool MakeMempool(FuzzedDataProvider& fuzzed_data_provider, const NodeContext& node)
     110                 :            : {
     111                 :            :     // Take the default options for tests...
     112                 :          0 :     CTxMemPool::Options mempool_opts{MemPoolOptionsForTest(node)};
     113                 :            : 
     114                 :            : 
     115                 :            :     // ...override specific options for this specific fuzz suite
     116                 :          0 :     mempool_opts.limits.ancestor_count = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 50);
     117                 :          0 :     mempool_opts.limits.ancestor_size_vbytes = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 202) * 1'000;
     118                 :          0 :     mempool_opts.limits.descendant_count = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 50);
     119                 :          0 :     mempool_opts.limits.descendant_size_vbytes = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 202) * 1'000;
     120                 :          0 :     mempool_opts.max_size_bytes = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 200) * 1'000'000;
     121                 :          0 :     mempool_opts.expiry = std::chrono::hours{fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 999)};
     122                 :          0 :     nBytesPerSigOp = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(1, 999);
     123                 :            : 
     124                 :          0 :     mempool_opts.estimator = nullptr;
     125                 :          0 :     mempool_opts.check_ratio = 1;
     126                 :          0 :     mempool_opts.require_standard = fuzzed_data_provider.ConsumeBool();
     127                 :            : 
     128                 :            :     // ...and construct a CTxMemPool from it
     129                 :          0 :     return CTxMemPool{mempool_opts};
     130                 :            : }
     131                 :            : 
     132         [ +  - ]:          4 : FUZZ_TARGET(tx_package_eval, .init = initialize_tx_pool)
     133                 :            : {
     134                 :          0 :     FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
     135                 :          0 :     const auto& node = g_setup->m_node;
     136                 :          0 :     auto& chainstate{static_cast<DummyChainState&>(node.chainman->ActiveChainstate())};
     137                 :            : 
     138                 :          0 :     MockTime(fuzzed_data_provider, chainstate);
     139                 :            : 
     140                 :            :     // All RBF-spendable outpoints outside of the unsubmitted package
     141                 :          0 :     std::set<COutPoint> mempool_outpoints;
     142                 :          0 :     std::map<COutPoint, CAmount> outpoints_value;
     143         [ #  # ]:          0 :     for (const auto& outpoint : g_outpoints_coinbase_init_mature) {
     144 [ #  # ][ #  # ]:          0 :         Assert(mempool_outpoints.insert(outpoint).second);
     145         [ #  # ]:          0 :         outpoints_value[outpoint] = 50 * COIN;
     146                 :            :     }
     147                 :            : 
     148         [ #  # ]:          0 :     auto outpoints_updater = std::make_shared<OutpointsUpdater>(mempool_outpoints);
     149         [ #  # ]:          0 :     RegisterSharedValidationInterface(outpoints_updater);
     150                 :            : 
     151         [ #  # ]:          0 :     CTxMemPool tx_pool_{MakeMempool(fuzzed_data_provider, node)};
     152                 :          0 :     MockedTxPool& tx_pool = *static_cast<MockedTxPool*>(&tx_pool_);
     153                 :            : 
     154         [ #  # ]:          0 :     chainstate.SetMempool(&tx_pool);
     155                 :            : 
     156 [ #  # ][ #  # ]:          0 :     LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 300)
                 [ #  # ]
     157                 :            :     {
     158         [ #  # ]:          0 :         Assert(!mempool_outpoints.empty());
     159                 :            : 
     160                 :          0 :         std::vector<CTransactionRef> txs;
     161                 :            : 
     162                 :            :         // Make packages of 1-to-26 transactions
     163         [ #  # ]:          0 :         const auto num_txs = (size_t) fuzzed_data_provider.ConsumeIntegralInRange<int>(1, 26);
     164                 :          0 :         std::set<COutPoint> package_outpoints;
     165         [ #  # ]:          0 :         while (txs.size() < num_txs) {
     166                 :            : 
     167                 :            :             // Last transaction in a package needs to be a child of parents to get further in validation
     168                 :            :             // so the last transaction to be generated(in a >1 package) must spend all package-made outputs
     169                 :            :             // Note that this test currently only spends package outputs in last transaction.
     170         [ #  # ]:          0 :             bool last_tx = num_txs > 1 && txs.size() == num_txs - 1;
     171                 :            : 
     172                 :            :             // Create transaction to add to the mempool
     173         [ #  # ]:          0 :             const CTransactionRef tx = [&] {
     174                 :          0 :                 CMutableTransaction tx_mut;
     175                 :          0 :                 tx_mut.nVersion = CTransaction::CURRENT_VERSION;
     176 [ #  # ][ #  # ]:          0 :                 tx_mut.nLockTime = fuzzed_data_provider.ConsumeBool() ? 0 : fuzzed_data_provider.ConsumeIntegral<uint32_t>();
                 [ #  # ]
     177                 :            :                 // Last tx will sweep all outpoints in package
     178         [ #  # ]:          0 :                 const auto num_in = last_tx ? package_outpoints.size()  : fuzzed_data_provider.ConsumeIntegralInRange<int>(1, mempool_outpoints.size());
     179                 :          0 :                 const auto num_out = fuzzed_data_provider.ConsumeIntegralInRange<int>(1, mempool_outpoints.size() * 2);
     180                 :            : 
     181         [ #  # ]:          0 :                 auto& outpoints = last_tx ? package_outpoints : mempool_outpoints;
     182                 :            : 
     183         [ #  # ]:          0 :                 Assert(!outpoints.empty());
     184                 :            : 
     185                 :          0 :                 CAmount amount_in{0};
     186         [ #  # ]:          0 :                 for (size_t i = 0; i < num_in; ++i) {
     187                 :            :                     // Pop random outpoint
     188                 :          0 :                     auto pop = outpoints.begin();
     189 [ #  # ][ #  # ]:          0 :                     std::advance(pop, fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, outpoints.size() - 1));
     190                 :          0 :                     const auto outpoint = *pop;
     191         [ #  # ]:          0 :                     outpoints.erase(pop);
     192                 :            :                     // no need to update or erase from outpoints_value
     193         [ #  # ]:          0 :                     amount_in += outpoints_value.at(outpoint);
     194                 :            : 
     195                 :            :                     // Create input
     196                 :          0 :                     const auto sequence = ConsumeSequence(fuzzed_data_provider);
     197         [ #  # ]:          0 :                     const auto script_sig = CScript{};
     198 [ #  # ][ #  # ]:          0 :                     const auto script_wit_stack = std::vector<std::vector<uint8_t>>{WITNESS_STACK_ELEM_OP_TRUE};
     199         [ #  # ]:          0 :                     CTxIn in;
     200                 :          0 :                     in.prevout = outpoint;
     201                 :          0 :                     in.nSequence = sequence;
     202         [ #  # ]:          0 :                     in.scriptSig = script_sig;
     203         [ #  # ]:          0 :                     in.scriptWitness.stack = script_wit_stack;
     204                 :            : 
     205         [ #  # ]:          0 :                     tx_mut.vin.push_back(in);
     206                 :          0 :                 }
     207         [ #  # ]:          0 :                 const auto amount_fee = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(0, amount_in);
     208                 :          0 :                 const auto amount_out = (amount_in - amount_fee) / num_out;
     209         [ #  # ]:          0 :                 for (int i = 0; i < num_out; ++i) {
     210         [ #  # ]:          0 :                     tx_mut.vout.emplace_back(amount_out, P2WSH_OP_TRUE);
     211                 :          0 :                 }
     212                 :            :                 // TODO vary transaction sizes to catch size-related issues
     213         [ #  # ]:          0 :                 auto tx = MakeTransactionRef(tx_mut);
     214                 :            :                 // Restore previously removed outpoints, except in-package outpoints
     215         [ #  # ]:          0 :                 if (!last_tx) {
     216         [ #  # ]:          0 :                     for (const auto& in : tx->vin) {
     217 [ #  # ][ #  # ]:          0 :                         Assert(outpoints.insert(in.prevout).second);
     218                 :            :                     }
     219                 :            :                     // Cache the in-package outpoints being made
     220         [ #  # ]:          0 :                     for (size_t i = 0; i < tx->vout.size(); ++i) {
     221 [ #  # ][ #  # ]:          0 :                         package_outpoints.emplace(tx->GetHash(), i);
     222                 :          0 :                     }
     223                 :          0 :                 }
     224                 :            :                 // We need newly-created values for the duration of this run
     225         [ #  # ]:          0 :                 for (size_t i = 0; i < tx->vout.size(); ++i) {
     226 [ #  # ][ #  # ]:          0 :                     outpoints_value[COutPoint(tx->GetHash(), i)] = tx->vout[i].nValue;
                 [ #  # ]
     227                 :          0 :                 }
     228                 :          0 :                 return tx;
     229         [ #  # ]:          0 :             }();
     230         [ #  # ]:          0 :             txs.push_back(tx);
     231                 :          0 :         }
     232                 :            : 
     233 [ #  # ][ #  # ]:          0 :         if (fuzzed_data_provider.ConsumeBool()) {
     234         [ #  # ]:          0 :             MockTime(fuzzed_data_provider, chainstate);
     235                 :          0 :         }
     236 [ #  # ][ #  # ]:          0 :         if (fuzzed_data_provider.ConsumeBool()) {
     237         [ #  # ]:          0 :             tx_pool.RollingFeeUpdate();
     238                 :          0 :         }
     239 [ #  # ][ #  # ]:          0 :         if (fuzzed_data_provider.ConsumeBool()) {
     240 [ #  # ][ #  # ]:          0 :             const auto& txid = fuzzed_data_provider.ConsumeBool() ?
     241         [ #  # ]:          0 :                                    txs.back()->GetHash() :
     242         [ #  # ]:          0 :                                    PickValue(fuzzed_data_provider, mempool_outpoints).hash;
     243         [ #  # ]:          0 :             const auto delta = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-50 * COIN, +50 * COIN);
     244         [ #  # ]:          0 :             tx_pool.PrioritiseTransaction(txid, delta);
     245                 :          0 :         }
     246                 :            : 
     247                 :            :         // Remember all added transactions
     248                 :          0 :         std::set<CTransactionRef> added;
     249         [ #  # ]:          0 :         auto txr = std::make_shared<TransactionsDelta>(added);
     250         [ #  # ]:          0 :         RegisterSharedValidationInterface(txr);
     251         [ #  # ]:          0 :         const bool bypass_limits = fuzzed_data_provider.ConsumeBool();
     252                 :            : 
     253                 :            :         // When there are multiple transactions in the package, we call ProcessNewPackage(txs, test_accept=false)
     254                 :            :         // and AcceptToMemoryPool(txs.back(), test_accept=true). When there is only 1 transaction, we might flip it
     255                 :            :         // (the package is a test accept and ATMP is a submission).
     256 [ #  # ][ #  # ]:          0 :         auto single_submit = txs.size() == 1 && fuzzed_data_provider.ConsumeBool();
     257                 :            : 
     258 [ #  # ][ #  # ]:          0 :         const auto result_package = WITH_LOCK(::cs_main,
                 [ #  # ]
     259                 :            :                                     return ProcessNewPackage(chainstate, tx_pool, txs, /*test_accept=*/single_submit));
     260                 :            :         // If something went wrong due to a package-specific policy, it might not return a
     261                 :            :         // validation result for the transaction.
     262 [ #  # ][ #  # ]:          0 :         if (result_package.m_state.GetResult() != PackageValidationResult::PCKG_POLICY) {
     263 [ #  # ][ #  # ]:          0 :             auto it = result_package.m_tx_results.find(txs.back()->GetWitnessHash());
     264         [ #  # ]:          0 :             Assert(it != result_package.m_tx_results.end());
     265 [ #  # ][ #  # ]:          0 :             Assert(it->second.m_result_type == MempoolAcceptResult::ResultType::VALID ||
                 [ #  # ]
     266                 :            :                    it->second.m_result_type == MempoolAcceptResult::ResultType::INVALID ||
     267                 :            :                    it->second.m_result_type == MempoolAcceptResult::ResultType::MEMPOOL_ENTRY);
     268                 :          0 :         }
     269                 :            : 
     270 [ #  # ][ #  # ]:          0 :         const auto res = WITH_LOCK(::cs_main, return AcceptToMemoryPool(chainstate, txs.back(), GetTime(), bypass_limits, /*test_accept=*/!single_submit));
         [ #  # ][ #  # ]
     271                 :          0 :         const bool accepted = res.m_result_type == MempoolAcceptResult::ResultType::VALID;
     272                 :            : 
     273         [ #  # ]:          0 :         SyncWithValidationInterfaceQueue();
     274         [ #  # ]:          0 :         UnregisterSharedValidationInterface(txr);
     275                 :            : 
     276                 :            :         // There is only 1 transaction in the package. We did a test-package-accept and a ATMP
     277         [ #  # ]:          0 :         if (single_submit) {
     278         [ #  # ]:          0 :             Assert(accepted != added.empty());
     279 [ #  # ][ #  # ]:          0 :             Assert(accepted == res.m_state.IsValid());
     280         [ #  # ]:          0 :             if (accepted) {
     281         [ #  # ]:          0 :                 Assert(added.size() == 1);
     282         [ #  # ]:          0 :                 Assert(txs.back() == *added.begin());
     283                 :          0 :             }
     284                 :          0 :         } else {
     285                 :            :             // This is empty if it fails early checks, or "full" if transactions are looked at deeper
     286 [ #  # ][ #  # ]:          0 :             Assert(result_package.m_tx_results.size() == txs.size() || result_package.m_tx_results.empty());
     287                 :            :         }
     288                 :          0 :     }
     289                 :            : 
     290         [ #  # ]:          0 :     UnregisterSharedValidationInterface(outpoints_updater);
     291                 :            : 
     292 [ #  # ][ #  # ]:          0 :     WITH_LOCK(::cs_main, tx_pool.check(chainstate.CoinsTip(), chainstate.m_chain.Height() + 1));
         [ #  # ][ #  # ]
                 [ #  # ]
     293                 :          0 : }
     294                 :            : } // namespace

Generated by: LCOV version 1.14