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 % 280 280
Test Date: 2025-01-22 04:09:46 Functions: 100.0 % 22 22
Branches: 68.7 % 402 276

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

Generated by: LCOV version 2.0-1