LCOV - code coverage report
Current view: top level - src/test/fuzz - package_eval.cpp (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 12 180 6.7 %
Date: 2024-01-03 14:57:27 Functions: 1 22 4.5 %
Branches: 16 276 5.8 %

           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                 :            : #include <util/rbf.h>
      18                 :            : #include <validation.h>
      19                 :            : #include <validationinterface.h>
      20                 :            : 
      21                 :            : using node::NodeContext;
      22         [ +  - ]:          2 : 
      23                 :          2 : namespace {
      24         [ +  - ]:          2 : 
      25 [ +  - ][ +  - ]:          2 : const TestingSetup* g_setup;
                 [ +  - ]
      26                 :            : std::vector<COutPoint> g_outpoints_coinbase_init_mature;
      27                 :            : 
      28                 :            : struct MockedTxPool : public CTxMemPool {
      29                 :          0 :     void RollingFeeUpdate() EXCLUSIVE_LOCKS_REQUIRED(!cs)
      30 [ +  - ][ +  - ]:          2 :     {
                 [ #  # ]
      31 [ +  - ][ +  - ]:          2 :         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_EMPTY)};
      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 NewMempoolTransactionInfo& 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.info.m_tx->vout.size(); ++index) {
      64                 :          0 :             m_mempool_outpoints.insert(COutPoint{tx.info.m_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                 :            :     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 NewMempoolTransactionInfo& tx, uint64_t /* mempool_sequence */) override
      89                 :            :     {
      90                 :            :         // Transactions may be entered and booted any number of times
      91                 :          0 :         m_added.insert(tx.info.m_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.check_ratio = 1;
     125                 :          0 :     mempool_opts.require_standard = fuzzed_data_provider.ConsumeBool();
     126                 :            : 
     127                 :            :     // ...and construct a CTxMemPool from it
     128                 :          0 :     return CTxMemPool{mempool_opts};
     129                 :            : }
     130                 :            : 
     131         [ +  - ]:          4 : FUZZ_TARGET(tx_package_eval, .init = initialize_tx_pool)
     132                 :            : {
     133                 :          0 :     FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
     134                 :          0 :     const auto& node = g_setup->m_node;
     135                 :          0 :     auto& chainstate{static_cast<DummyChainState&>(node.chainman->ActiveChainstate())};
     136                 :            : 
     137                 :          0 :     MockTime(fuzzed_data_provider, chainstate);
     138                 :            : 
     139                 :            :     // All RBF-spendable outpoints outside of the unsubmitted package
     140                 :          0 :     std::set<COutPoint> mempool_outpoints;
     141                 :          0 :     std::map<COutPoint, CAmount> outpoints_value;
     142         [ #  # ]:          0 :     for (const auto& outpoint : g_outpoints_coinbase_init_mature) {
     143 [ #  # ][ #  # ]:          0 :         Assert(mempool_outpoints.insert(outpoint).second);
     144         [ #  # ]:          0 :         outpoints_value[outpoint] = 50 * COIN;
     145                 :            :     }
     146                 :            : 
     147         [ #  # ]:          0 :     auto outpoints_updater = std::make_shared<OutpointsUpdater>(mempool_outpoints);
     148         [ #  # ]:          0 :     RegisterSharedValidationInterface(outpoints_updater);
     149                 :            : 
     150         [ #  # ]:          0 :     CTxMemPool tx_pool_{MakeMempool(fuzzed_data_provider, node)};
     151                 :          0 :     MockedTxPool& tx_pool = *static_cast<MockedTxPool*>(&tx_pool_);
     152                 :            : 
     153         [ #  # ]:          0 :     chainstate.SetMempool(&tx_pool);
     154                 :            : 
     155 [ #  # ][ #  # ]:          0 :     LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 300)
                 [ #  # ]
     156                 :            :     {
     157         [ #  # ]:          0 :         Assert(!mempool_outpoints.empty());
     158                 :            : 
     159                 :          0 :         std::vector<CTransactionRef> txs;
     160                 :            : 
     161                 :            :         // Make packages of 1-to-26 transactions
     162         [ #  # ]:          0 :         const auto num_txs = (size_t) fuzzed_data_provider.ConsumeIntegralInRange<int>(1, 26);
     163                 :          0 :         std::set<COutPoint> package_outpoints;
     164         [ #  # ]:          0 :         while (txs.size() < num_txs) {
     165                 :            : 
     166                 :            :             // Last transaction in a package needs to be a child of parents to get further in validation
     167                 :            :             // so the last transaction to be generated(in a >1 package) must spend all package-made outputs
     168                 :            :             // Note that this test currently only spends package outputs in last transaction.
     169         [ #  # ]:          0 :             bool last_tx = num_txs > 1 && txs.size() == num_txs - 1;
     170                 :            : 
     171                 :            :             // Create transaction to add to the mempool
     172         [ #  # ]:          0 :             const CTransactionRef tx = [&] {
     173                 :          0 :                 CMutableTransaction tx_mut;
     174                 :          0 :                 tx_mut.nVersion = CTransaction::CURRENT_VERSION;
     175 [ #  # ][ #  # ]:          0 :                 tx_mut.nLockTime = fuzzed_data_provider.ConsumeBool() ? 0 : fuzzed_data_provider.ConsumeIntegral<uint32_t>();
                 [ #  # ]
     176                 :            :                 // Last tx will sweep all outpoints in package
     177         [ #  # ]:          0 :                 const auto num_in = last_tx ? package_outpoints.size()  : fuzzed_data_provider.ConsumeIntegralInRange<int>(1, mempool_outpoints.size());
     178                 :          0 :                 const auto num_out = fuzzed_data_provider.ConsumeIntegralInRange<int>(1, mempool_outpoints.size() * 2);
     179                 :            : 
     180         [ #  # ]:          0 :                 auto& outpoints = last_tx ? package_outpoints : mempool_outpoints;
     181                 :            : 
     182         [ #  # ]:          0 :                 Assert(!outpoints.empty());
     183                 :            : 
     184                 :          0 :                 CAmount amount_in{0};
     185         [ #  # ]:          0 :                 for (size_t i = 0; i < num_in; ++i) {
     186                 :            :                     // Pop random outpoint
     187                 :          0 :                     auto pop = outpoints.begin();
     188 [ #  # ][ #  # ]:          0 :                     std::advance(pop, fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, outpoints.size() - 1));
     189                 :          0 :                     const auto outpoint = *pop;
     190         [ #  # ]:          0 :                     outpoints.erase(pop);
     191                 :            :                     // no need to update or erase from outpoints_value
     192         [ #  # ]:          0 :                     amount_in += outpoints_value.at(outpoint);
     193                 :            : 
     194                 :            :                     // Create input
     195                 :          0 :                     const auto sequence = ConsumeSequence(fuzzed_data_provider);
     196         [ #  # ]:          0 :                     const auto script_sig = CScript{};
     197 [ #  # ][ #  # ]:          0 :                     const auto script_wit_stack = fuzzed_data_provider.ConsumeBool() ? P2WSH_EMPTY_TRUE_STACK : P2WSH_EMPTY_TWO_STACK;
                 [ #  # ]
     198                 :            : 
     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                 :            : 
     208                 :            :                 // Duplicate an input
     209         [ #  # ]:          0 :                 bool dup_input = fuzzed_data_provider.ConsumeBool();
     210         [ #  # ]:          0 :                 if (dup_input) {
     211         [ #  # ]:          0 :                     tx_mut.vin.push_back(tx_mut.vin.back());
     212                 :          0 :                 }
     213                 :            : 
     214                 :            :                 // Refer to a non-existant input
     215 [ #  # ][ #  # ]:          0 :                 if (fuzzed_data_provider.ConsumeBool()) {
     216         [ #  # ]:          0 :                     tx_mut.vin.emplace_back();
     217                 :          0 :                 }
     218                 :            : 
     219         [ #  # ]:          0 :                 const auto amount_fee = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(0, amount_in);
     220                 :          0 :                 const auto amount_out = (amount_in - amount_fee) / num_out;
     221         [ #  # ]:          0 :                 for (int i = 0; i < num_out; ++i) {
     222         [ #  # ]:          0 :                     tx_mut.vout.emplace_back(amount_out, P2WSH_EMPTY);
     223                 :          0 :                 }
     224                 :            :                 // TODO vary transaction sizes to catch size-related issues
     225         [ #  # ]:          0 :                 auto tx = MakeTransactionRef(tx_mut);
     226                 :            :                 // Restore previously removed outpoints, except in-package outpoints
     227         [ #  # ]:          0 :                 if (!last_tx) {
     228         [ #  # ]:          0 :                     for (const auto& in : tx->vin) {
     229                 :            :                         // It's a fake input, or a new input, or a duplicate
     230 [ #  # ][ #  # ]:          0 :                         Assert(in == CTxIn() || outpoints.insert(in.prevout).second || dup_input);
         [ #  # ][ #  # ]
         [ #  # ][ #  # ]
     231                 :            :                     }
     232                 :            :                     // Cache the in-package outpoints being made
     233         [ #  # ]:          0 :                     for (size_t i = 0; i < tx->vout.size(); ++i) {
     234 [ #  # ][ #  # ]:          0 :                         package_outpoints.emplace(tx->GetHash(), i);
     235                 :          0 :                     }
     236                 :          0 :                 }
     237                 :            :                 // We need newly-created values for the duration of this run
     238         [ #  # ]:          0 :                 for (size_t i = 0; i < tx->vout.size(); ++i) {
     239 [ #  # ][ #  # ]:          0 :                     outpoints_value[COutPoint(tx->GetHash(), i)] = tx->vout[i].nValue;
                 [ #  # ]
     240                 :          0 :                 }
     241                 :          0 :                 return tx;
     242         [ #  # ]:          0 :             }();
     243         [ #  # ]:          0 :             txs.push_back(tx);
     244                 :          0 :         }
     245                 :            : 
     246 [ #  # ][ #  # ]:          0 :         if (fuzzed_data_provider.ConsumeBool()) {
     247         [ #  # ]:          0 :             MockTime(fuzzed_data_provider, chainstate);
     248                 :          0 :         }
     249 [ #  # ][ #  # ]:          0 :         if (fuzzed_data_provider.ConsumeBool()) {
     250         [ #  # ]:          0 :             tx_pool.RollingFeeUpdate();
     251                 :          0 :         }
     252 [ #  # ][ #  # ]:          0 :         if (fuzzed_data_provider.ConsumeBool()) {
     253 [ #  # ][ #  # ]:          0 :             const auto& txid = fuzzed_data_provider.ConsumeBool() ?
     254         [ #  # ]:          0 :                                    txs.back()->GetHash() :
     255         [ #  # ]:          0 :                                    PickValue(fuzzed_data_provider, mempool_outpoints).hash;
     256         [ #  # ]:          0 :             const auto delta = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-50 * COIN, +50 * COIN);
     257 [ #  # ][ #  # ]:          0 :             tx_pool.PrioritiseTransaction(txid.ToUint256(), delta);
     258                 :          0 :         }
     259                 :            : 
     260                 :            :         // Remember all added transactions
     261                 :          0 :         std::set<CTransactionRef> added;
     262         [ #  # ]:          0 :         auto txr = std::make_shared<TransactionsDelta>(added);
     263         [ #  # ]:          0 :         RegisterSharedValidationInterface(txr);
     264         [ #  # ]:          0 :         const bool bypass_limits = fuzzed_data_provider.ConsumeBool();
     265                 :            : 
     266                 :            :         // When there are multiple transactions in the package, we call ProcessNewPackage(txs, test_accept=false)
     267                 :            :         // and AcceptToMemoryPool(txs.back(), test_accept=true). When there is only 1 transaction, we might flip it
     268                 :            :         // (the package is a test accept and ATMP is a submission).
     269 [ #  # ][ #  # ]:          0 :         auto single_submit = txs.size() == 1 && fuzzed_data_provider.ConsumeBool();
     270                 :            : 
     271 [ #  # ][ #  # ]:          0 :         const auto result_package = WITH_LOCK(::cs_main,
                 [ #  # ]
     272                 :            :                                     return ProcessNewPackage(chainstate, tx_pool, txs, /*test_accept=*/single_submit));
     273                 :            : 
     274 [ #  # ][ #  # ]:          0 :         const auto res = WITH_LOCK(::cs_main, return AcceptToMemoryPool(chainstate, txs.back(), GetTime(), bypass_limits, /*test_accept=*/!single_submit));
         [ #  # ][ #  # ]
     275                 :          0 :         const bool accepted = res.m_result_type == MempoolAcceptResult::ResultType::VALID;
     276                 :            : 
     277         [ #  # ]:          0 :         SyncWithValidationInterfaceQueue();
     278         [ #  # ]:          0 :         UnregisterSharedValidationInterface(txr);
     279                 :            : 
     280                 :            :         // There is only 1 transaction in the package. We did a test-package-accept and a ATMP
     281         [ #  # ]:          0 :         if (single_submit) {
     282         [ #  # ]:          0 :             Assert(accepted != added.empty());
     283 [ #  # ][ #  # ]:          0 :             Assert(accepted == res.m_state.IsValid());
     284         [ #  # ]:          0 :             if (accepted) {
     285         [ #  # ]:          0 :                 Assert(added.size() == 1);
     286         [ #  # ]:          0 :                 Assert(txs.back() == *added.begin());
     287                 :          0 :             }
     288 [ #  # ][ #  # ]:          0 :         } else if (result_package.m_state.GetResult() != PackageValidationResult::PCKG_POLICY) {
     289                 :            :             // We don't know anything about the validity since transactions were randomly generated, so
     290                 :            :             // just use result_package.m_state here. This makes the expect_valid check meaningless, but
     291                 :            :             // we can still verify that the contents of m_tx_results are consistent with m_state.
     292         [ #  # ]:          0 :             const bool expect_valid{result_package.m_state.IsValid()};
     293 [ #  # ][ #  # ]:          0 :             Assert(!CheckPackageMempoolAcceptResult(txs, result_package, expect_valid, nullptr));
     294                 :          0 :         } else {
     295                 :            :             // This is empty if it fails early checks, or "full" if transactions are looked at deeper
     296 [ #  # ][ #  # ]:          0 :             Assert(result_package.m_tx_results.size() == txs.size() || result_package.m_tx_results.empty());
     297                 :            :         }
     298                 :          0 :     }
     299                 :            : 
     300         [ #  # ]:          0 :     UnregisterSharedValidationInterface(outpoints_updater);
     301                 :            : 
     302 [ #  # ][ #  # ]:          0 :     WITH_LOCK(::cs_main, tx_pool.check(chainstate.CoinsTip(), chainstate.m_chain.Height() + 1));
         [ #  # ][ #  # ]
                 [ #  # ]
     303                 :          0 : }
     304                 :            : } // namespace

Generated by: LCOV version 1.14