LCOV - code coverage report
Current view: top level - src/test/fuzz - package_eval.cpp (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 184 185 99.5 %
Date: 2023-11-12 01:39:15 Functions: 16 26 61.5 %
Branches: 171 280 61.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                 :          2 : using node::NodeContext;
      22         [ +  - ]:          2 : 
      23                 :          2 : namespace {
      24         [ +  - ]:          2 : 
      25 [ +  - ][ +  - ]:          2 : const TestingSetup* g_setup;
                 [ +  - ]
      26                 :          2 : std::vector<COutPoint> g_outpoints_coinbase_init_mature;
      27                 :            : 
      28                 :            : struct MockedTxPool : public CTxMemPool {
      29                 :      10667 :     void RollingFeeUpdate() EXCLUSIVE_LOCKS_REQUIRED(!cs)
      30 [ +  - ][ +  - ]:          2 :     {
                 [ #  # ]
      31 [ +  - ][ +  - ]:      10669 :         LOCK(cs);
                 [ #  # ]
      32         [ +  - ]:      10667 :         lastRollingFeeUpdate = GetTime();
      33                 :      10667 :         blockSinceLastRollingFeeBump = true;
      34                 :      10667 :     }
      35                 :            : };
      36                 :            : 
      37                 :          1 : void initialize_tx_pool()
      38                 :            : {
      39 [ +  - ][ -  + ]:          1 :     static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>();
                 [ +  - ]
      40                 :          1 :     g_setup = testing_setup.get();
      41                 :            : 
      42         [ +  + ]:        201 :     for (int i = 0; i < 2 * COINBASE_MATURITY; ++i) {
      43                 :        200 :         COutPoint prevout{MineBlock(g_setup->m_node, P2WSH_EMPTY)};
      44         [ +  + ]:        200 :         if (i < COINBASE_MATURITY) {
      45                 :            :             // Remember the txids to avoid expensive disk access later on
      46                 :        100 :             g_outpoints_coinbase_init_mature.push_back(prevout);
      47                 :        100 :         }
      48                 :        200 :     }
      49                 :          1 :     SyncWithValidationInterfaceQueue();
      50                 :          1 : }
      51                 :            : 
      52                 :            : struct OutpointsUpdater final : public CValidationInterface {
      53                 :            :     std::set<COutPoint>& m_mempool_outpoints;
      54                 :            : 
      55                 :        542 :     explicit OutpointsUpdater(std::set<COutPoint>& r)
      56                 :        542 :         : m_mempool_outpoints{r} {}
      57                 :            : 
      58                 :       7026 :     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         [ +  + ]:      99047 :         for (uint32_t index{0}; index < tx->vout.size(); ++index) {
      64                 :      92021 :             m_mempool_outpoints.insert(COutPoint{tx->GetHash(), index});
      65                 :      92021 :         }
      66                 :       7026 :     }
      67                 :            : 
      68                 :       6044 :     void TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t /* mempool_sequence */) override
      69                 :            :     {
      70                 :            :         // outpoints spent by this tx are now available
      71         [ +  + ]:      13221 :         for (const auto& input : tx->vin) {
      72                 :            :             // Could already exist if this was a replacement
      73                 :       7177 :             m_mempool_outpoints.insert(input.prevout);
      74                 :            :         }
      75                 :            :         // outpoints created by this tx no longer exist
      76         [ +  + ]:      27162 :         for (uint32_t index{0}; index < tx->vout.size(); ++index) {
      77                 :      21118 :             m_mempool_outpoints.erase(COutPoint{tx->GetHash(), index});
      78                 :      21118 :         }
      79                 :       6044 :     }
      80                 :            : };
      81                 :            : 
      82                 :            : struct TransactionsDelta final : public CValidationInterface {
      83                 :            :     std::set<CTransactionRef>& m_added;
      84                 :            : 
      85                 :      19952 :     explicit TransactionsDelta(std::set<CTransactionRef>& a)
      86                 :      19952 :         : m_added{a} {}
      87                 :            : 
      88                 :       7026 :     void TransactionAddedToMempool(const CTransactionRef& tx, uint64_t /* mempool_sequence */) override
      89                 :            :     {
      90                 :            :         // Transactions may be entered and booted any number of times
      91                 :       7026 :         m_added.insert(tx);
      92                 :       7026 :     }
      93                 :            : 
      94                 :       6044 :     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                 :       6044 :          m_added.erase(tx);
      98                 :       6044 :     }
      99                 :            : };
     100                 :            : 
     101                 :      15803 : void MockTime(FuzzedDataProvider& fuzzed_data_provider, const Chainstate& chainstate)
     102                 :            : {
     103                 :      31606 :     const auto time = ConsumeTime(fuzzed_data_provider,
     104                 :      15803 :                                   chainstate.m_chain.Tip()->GetMedianTimePast() + 1,
     105                 :      15803 :                                   std::numeric_limits<decltype(chainstate.m_chain.Tip()->nTime)>::max());
     106                 :      15803 :     SetMockTime(time);
     107                 :      15803 : }
     108                 :            : 
     109                 :        542 : CTxMemPool MakeMempool(FuzzedDataProvider& fuzzed_data_provider, const NodeContext& node)
     110                 :            : {
     111                 :            :     // Take the default options for tests...
     112                 :        542 :     CTxMemPool::Options mempool_opts{MemPoolOptionsForTest(node)};
     113                 :            : 
     114                 :            : 
     115                 :            :     // ...override specific options for this specific fuzz suite
     116                 :        542 :     mempool_opts.limits.ancestor_count = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 50);
     117                 :        542 :     mempool_opts.limits.ancestor_size_vbytes = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 202) * 1'000;
     118                 :        542 :     mempool_opts.limits.descendant_count = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 50);
     119                 :        542 :     mempool_opts.limits.descendant_size_vbytes = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 202) * 1'000;
     120                 :        542 :     mempool_opts.max_size_bytes = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 200) * 1'000'000;
     121                 :        542 :     mempool_opts.expiry = std::chrono::hours{fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 999)};
     122                 :        542 :     nBytesPerSigOp = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(1, 999);
     123                 :            : 
     124                 :        542 :     mempool_opts.estimator = nullptr;
     125                 :        542 :     mempool_opts.check_ratio = 1;
     126                 :        542 :     mempool_opts.require_standard = fuzzed_data_provider.ConsumeBool();
     127                 :            : 
     128                 :            :     // ...and construct a CTxMemPool from it
     129                 :        542 :     return CTxMemPool{mempool_opts};
     130                 :            : }
     131                 :            : 
     132         [ +  - ]:        546 : FUZZ_TARGET(tx_package_eval, .init = initialize_tx_pool)
     133                 :            : {
     134                 :        542 :     FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
     135                 :        542 :     const auto& node = g_setup->m_node;
     136                 :        542 :     auto& chainstate{static_cast<DummyChainState&>(node.chainman->ActiveChainstate())};
     137                 :            : 
     138                 :        542 :     MockTime(fuzzed_data_provider, chainstate);
     139                 :            : 
     140                 :            :     // All RBF-spendable outpoints outside of the unsubmitted package
     141                 :        542 :     std::set<COutPoint> mempool_outpoints;
     142                 :        542 :     std::map<COutPoint, CAmount> outpoints_value;
     143         [ +  + ]:      54742 :     for (const auto& outpoint : g_outpoints_coinbase_init_mature) {
     144 [ +  - ][ +  - ]:      54200 :         Assert(mempool_outpoints.insert(outpoint).second);
     145         [ +  - ]:      54200 :         outpoints_value[outpoint] = 50 * COIN;
     146                 :            :     }
     147                 :            : 
     148         [ +  - ]:        542 :     auto outpoints_updater = std::make_shared<OutpointsUpdater>(mempool_outpoints);
     149         [ +  - ]:        542 :     RegisterSharedValidationInterface(outpoints_updater);
     150                 :            : 
     151         [ +  - ]:        542 :     CTxMemPool tx_pool_{MakeMempool(fuzzed_data_provider, node)};
     152                 :        542 :     MockedTxPool& tx_pool = *static_cast<MockedTxPool*>(&tx_pool_);
     153                 :            : 
     154         [ +  - ]:        542 :     chainstate.SetMempool(&tx_pool);
     155                 :            : 
     156 [ +  - ][ +  + ]:      20494 :     LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 300)
                 [ +  + ]
     157                 :            :     {
     158         [ +  - ]:      19952 :         Assert(!mempool_outpoints.empty());
     159                 :            : 
     160                 :      19952 :         std::vector<CTransactionRef> txs;
     161                 :            : 
     162                 :            :         // Make packages of 1-to-26 transactions
     163         [ -  + ]:      19952 :         const auto num_txs = (size_t) fuzzed_data_provider.ConsumeIntegralInRange<int>(1, 26);
     164                 :      19952 :         std::set<COutPoint> package_outpoints;
     165         [ +  + ]:      56413 :         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         [ +  + ]:      36461 :             bool last_tx = num_txs > 1 && txs.size() == num_txs - 1;
     171                 :            : 
     172                 :            :             // Create transaction to add to the mempool
     173         [ +  - ]:      72922 :             const CTransactionRef tx = [&] {
     174                 :      36461 :                 CMutableTransaction tx_mut;
     175                 :      36461 :                 tx_mut.nVersion = CTransaction::CURRENT_VERSION;
     176 [ +  - ][ +  + ]:      36461 :                 tx_mut.nLockTime = fuzzed_data_provider.ConsumeBool() ? 0 : fuzzed_data_provider.ConsumeIntegral<uint32_t>();
                 [ +  - ]
     177                 :            :                 // Last tx will sweep all outpoints in package
     178         [ +  + ]:      36461 :                 const auto num_in = last_tx ? package_outpoints.size()  : fuzzed_data_provider.ConsumeIntegralInRange<int>(1, mempool_outpoints.size());
     179                 :      36461 :                 const auto num_out = fuzzed_data_provider.ConsumeIntegralInRange<int>(1, mempool_outpoints.size() * 2);
     180                 :            : 
     181         [ +  + ]:      36461 :                 auto& outpoints = last_tx ? package_outpoints : mempool_outpoints;
     182                 :            : 
     183         [ +  - ]:      36461 :                 Assert(!outpoints.empty());
     184                 :            : 
     185                 :      36461 :                 CAmount amount_in{0};
     186         [ +  + ]:     226305 :                 for (size_t i = 0; i < num_in; ++i) {
     187                 :            :                     // Pop random outpoint
     188                 :     189844 :                     auto pop = outpoints.begin();
     189 [ +  - ][ +  - ]:     189844 :                     std::advance(pop, fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, outpoints.size() - 1));
     190                 :     189844 :                     const auto outpoint = *pop;
     191         [ +  - ]:     189844 :                     outpoints.erase(pop);
     192                 :            :                     // no need to update or erase from outpoints_value
     193         [ +  - ]:     189844 :                     amount_in += outpoints_value.at(outpoint);
     194                 :            : 
     195                 :            :                     // Create input
     196                 :     189844 :                     const auto sequence = ConsumeSequence(fuzzed_data_provider);
     197         [ +  - ]:     189844 :                     const auto script_sig = CScript{};
     198 [ +  - ][ +  + ]:     189844 :                     const auto script_wit_stack = fuzzed_data_provider.ConsumeBool() ? P2WSH_EMPTY_TRUE_STACK : P2WSH_EMPTY_TWO_STACK;
                 [ +  - ]
     199                 :            : 
     200         [ -  + ]:     189844 :                     CTxIn in;
     201                 :     189844 :                     in.prevout = outpoint;
     202                 :     189844 :                     in.nSequence = sequence;
     203         [ +  - ]:     189844 :                     in.scriptSig = script_sig;
     204         [ +  - ]:     189844 :                     in.scriptWitness.stack = script_wit_stack;
     205                 :            : 
     206         [ +  - ]:     189844 :                     tx_mut.vin.push_back(in);
     207                 :     189844 :                 }
     208                 :            : 
     209                 :            :                 // Duplicate an input
     210         [ +  - ]:      36461 :                 bool dup_input = fuzzed_data_provider.ConsumeBool();
     211         [ +  + ]:      36461 :                 if (dup_input) {
     212         [ +  - ]:      13076 :                     tx_mut.vin.push_back(tx_mut.vin.back());
     213                 :      13076 :                 }
     214                 :            : 
     215                 :            :                 // Refer to a non-existant input
     216 [ +  - ][ +  + ]:      36461 :                 if (fuzzed_data_provider.ConsumeBool()) {
     217         [ +  - ]:       9326 :                     tx_mut.vin.emplace_back();
     218                 :       9326 :                 }
     219                 :            : 
     220         [ +  - ]:      36461 :                 const auto amount_fee = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(0, amount_in);
     221                 :      36461 :                 const auto amount_out = (amount_in - amount_fee) / num_out;
     222         [ +  + ]:     578423 :                 for (int i = 0; i < num_out; ++i) {
     223         [ +  - ]:     541962 :                     tx_mut.vout.emplace_back(amount_out, P2WSH_EMPTY);
     224                 :     541962 :                 }
     225                 :            :                 // TODO vary transaction sizes to catch size-related issues
     226         [ +  - ]:      36461 :                 auto tx = MakeTransactionRef(tx_mut);
     227                 :            :                 // Restore previously removed outpoints, except in-package outpoints
     228         [ +  + ]:      36461 :                 if (!last_tx) {
     229         [ +  + ]:     136811 :                     for (const auto& in : tx->vin) {
     230                 :            :                         // It's a fake input, or a new input, or a duplicate
     231 [ +  - ][ +  - ]:     111418 :                         Assert(in == CTxIn() || outpoints.insert(in.prevout).second || dup_input);
         [ +  + ][ +  - ]
         [ +  + ][ +  - ]
     232                 :            :                     }
     233                 :            :                     // Cache the in-package outpoints being made
     234         [ +  + ]:     420800 :                     for (size_t i = 0; i < tx->vout.size(); ++i) {
     235 [ +  - ][ +  - ]:     395407 :                         package_outpoints.emplace(tx->GetHash(), i);
     236                 :     395407 :                     }
     237                 :      25393 :                 }
     238                 :            :                 // We need newly-created values for the duration of this run
     239         [ +  + ]:     578423 :                 for (size_t i = 0; i < tx->vout.size(); ++i) {
     240 [ +  - ][ +  - ]:     541962 :                     outpoints_value[COutPoint(tx->GetHash(), i)] = tx->vout[i].nValue;
                 [ +  - ]
     241                 :     541962 :                 }
     242                 :      36461 :                 return tx;
     243         [ +  - ]:      36461 :             }();
     244         [ +  - ]:      36461 :             txs.push_back(tx);
     245                 :      36461 :         }
     246                 :            : 
     247 [ +  - ][ +  + ]:      19952 :         if (fuzzed_data_provider.ConsumeBool()) {
     248         [ +  - ]:      15261 :             MockTime(fuzzed_data_provider, chainstate);
     249                 :      15261 :         }
     250 [ +  - ][ +  + ]:      19952 :         if (fuzzed_data_provider.ConsumeBool()) {
     251         [ +  - ]:      10667 :             tx_pool.RollingFeeUpdate();
     252                 :      10667 :         }
     253 [ +  - ][ +  + ]:      19952 :         if (fuzzed_data_provider.ConsumeBool()) {
     254 [ +  - ][ +  + ]:      22024 :             const auto& txid = fuzzed_data_provider.ConsumeBool() ?
     255 [ +  - ][ +  - ]:      10402 :                                    txs.back()->GetHash().ToUint256() :
     256         [ +  - ]:        610 :                                    PickValue(fuzzed_data_provider, mempool_outpoints).hash;
     257         [ +  - ]:      11012 :             const auto delta = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-50 * COIN, +50 * COIN);
     258         [ +  - ]:      11012 :             tx_pool.PrioritiseTransaction(txid, delta);
     259                 :      11012 :         }
     260                 :            : 
     261                 :            :         // Remember all added transactions
     262                 :      19952 :         std::set<CTransactionRef> added;
     263         [ +  - ]:      19952 :         auto txr = std::make_shared<TransactionsDelta>(added);
     264         [ +  - ]:      19952 :         RegisterSharedValidationInterface(txr);
     265         [ +  - ]:      19952 :         const bool bypass_limits = fuzzed_data_provider.ConsumeBool();
     266                 :            : 
     267                 :            :         // When there are multiple transactions in the package, we call ProcessNewPackage(txs, test_accept=false)
     268                 :            :         // and AcceptToMemoryPool(txs.back(), test_accept=true). When there is only 1 transaction, we might flip it
     269                 :            :         // (the package is a test accept and ATMP is a submission).
     270 [ +  + ][ +  - ]:      28836 :         auto single_submit = txs.size() == 1 && fuzzed_data_provider.ConsumeBool();
     271                 :            : 
     272 [ +  - ][ +  - ]:      39904 :         const auto result_package = WITH_LOCK(::cs_main,
                 [ +  - ]
     273                 :            :                                     return ProcessNewPackage(chainstate, tx_pool, txs, /*test_accept=*/single_submit));
     274                 :            : 
     275 [ +  - ][ +  - ]:      39904 :         const auto res = WITH_LOCK(::cs_main, return AcceptToMemoryPool(chainstate, txs.back(), GetTime(), bypass_limits, /*test_accept=*/!single_submit));
         [ +  - ][ +  - ]
     276                 :      19952 :         const bool accepted = res.m_result_type == MempoolAcceptResult::ResultType::VALID;
     277                 :            : 
     278         [ +  - ]:      19952 :         SyncWithValidationInterfaceQueue();
     279         [ +  - ]:      19952 :         UnregisterSharedValidationInterface(txr);
     280                 :            : 
     281                 :            :         // There is only 1 transaction in the package. We did a test-package-accept and a ATMP
     282         [ +  + ]:      19952 :         if (single_submit) {
     283         [ +  - ]:       7197 :             Assert(accepted != added.empty());
     284 [ +  - ][ +  - ]:       7197 :             Assert(accepted == res.m_state.IsValid());
     285         [ +  + ]:       7197 :             if (accepted) {
     286         [ +  - ]:       4553 :                 Assert(added.size() == 1);
     287         [ +  - ]:       4553 :                 Assert(txs.back() == *added.begin());
     288                 :       4553 :             }
     289 [ +  - ][ +  + ]:      19952 :         } else if (result_package.m_state.GetResult() != PackageValidationResult::PCKG_POLICY) {
     290                 :            :             // We don't know anything about the validity since transactions were randomly generated, so
     291                 :            :             // just use result_package.m_state here. This makes the expect_valid check meaningless, but
     292                 :            :             // we can still verify that the contents of m_tx_results are consistent with m_state.
     293         [ +  - ]:       8153 :             const bool expect_valid{result_package.m_state.IsValid()};
     294 [ +  - ][ +  - ]:       8153 :             Assert(!CheckPackageMempoolAcceptResult(txs, result_package, expect_valid, nullptr));
     295                 :       8153 :         } else {
     296                 :            :             // This is empty if it fails early checks, or "full" if transactions are looked at deeper
     297 [ +  + ][ +  - ]:       4602 :             Assert(result_package.m_tx_results.size() == txs.size() || result_package.m_tx_results.empty());
     298                 :            :         }
     299                 :      19952 :     }
     300                 :            : 
     301         [ +  - ]:        542 :     UnregisterSharedValidationInterface(outpoints_updater);
     302                 :            : 
     303 [ +  - ][ +  - ]:       1084 :     WITH_LOCK(::cs_main, tx_pool.check(chainstate.CoinsTip(), chainstate.m_chain.Height() + 1));
         [ +  - ][ +  - ]
                 [ +  - ]
     304                 :        542 : }
     305                 :            : } // namespace

Generated by: LCOV version 1.14