LCOV - code coverage report
Current view: top level - src/test/util - setup_common.h (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 6 8 75.0 %
Date: 2023-11-10 23:46:46 Functions: 3 6 50.0 %
Branches: 3 6 50.0 %

           Branch data     Line data    Source code
       1                 :            : // Copyright (c) 2015-2022 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                 :            : #ifndef BITCOIN_TEST_UTIL_SETUP_COMMON_H
       6                 :            : #define BITCOIN_TEST_UTIL_SETUP_COMMON_H
       7                 :            : 
       8                 :            : #include <common/args.h>
       9                 :            : #include <key.h>
      10                 :            : #include <node/caches.h>
      11                 :            : #include <node/context.h> // IWYU pragma: export
      12                 :            : #include <primitives/transaction.h>
      13                 :            : #include <pubkey.h>
      14                 :            : #include <stdexcept>
      15                 :            : #include <util/chaintype.h>
      16                 :            : #include <util/check.h>
      17                 :            : #include <util/fs.h>
      18                 :            : #include <util/string.h>
      19                 :            : #include <util/vector.h>
      20                 :            : 
      21                 :            : #include <functional>
      22                 :            : #include <type_traits>
      23                 :            : #include <vector>
      24                 :            : 
      25                 :            : class CFeeRate;
      26                 :            : class Chainstate;
      27                 :            : class FastRandomContext;
      28                 :            : 
      29                 :            : /** This is connected to the logger. Can be used to redirect logs to any other log */
      30                 :            : extern const std::function<void(const std::string&)> G_TEST_LOG_FUN;
      31                 :            : 
      32                 :            : /** Retrieve the command line arguments. */
      33                 :            : extern const std::function<std::vector<const char*>()> G_TEST_COMMAND_LINE_ARGUMENTS;
      34                 :            : 
      35                 :            : // Enable BOOST_CHECK_EQUAL for enum class types
      36                 :            : namespace std {
      37                 :            : template <typename T>
      38                 :            : std::ostream& operator<<(typename std::enable_if<std::is_enum<T>::value, std::ostream>::type& stream, const T& e)
      39                 :            : {
      40                 :            :     return stream << static_cast<typename std::underlying_type<T>::type>(e);
      41                 :            : }
      42                 :            : } // namespace std
      43                 :            : 
      44                 :            : static constexpr CAmount CENT{1000000};
      45                 :            : 
      46                 :            : /** Basic testing setup.
      47                 :            :  * This just configures logging, data dir and chain parameters.
      48                 :            :  */
      49                 :            : struct BasicTestingSetup {
      50                 :            :     node::NodeContext m_node; // keep as first member to be destructed last
      51                 :            : 
      52                 :            :     explicit BasicTestingSetup(const ChainType chainType = ChainType::MAIN, const std::vector<const char*>& extra_args = {});
      53                 :            :     ~BasicTestingSetup();
      54                 :            : 
      55                 :            :     const fs::path m_path_root;
      56                 :            :     ArgsManager m_args;
      57                 :            : };
      58                 :            : 
      59                 :            : /** Testing setup that performs all steps up until right before
      60                 :            :  * ChainstateManager gets initialized. Meant for testing ChainstateManager
      61                 :            :  * initialization behaviour.
      62                 :            :  */
      63                 :            : struct ChainTestingSetup : public BasicTestingSetup {
      64                 :            :     node::CacheSizes m_cache_sizes{};
      65                 :            :     bool m_coins_db_in_memory{true};
      66                 :            :     bool m_block_tree_db_in_memory{true};
      67                 :            : 
      68                 :            :     explicit ChainTestingSetup(const ChainType chainType = ChainType::MAIN, const std::vector<const char*>& extra_args = {});
      69                 :            :     ~ChainTestingSetup();
      70                 :            : 
      71                 :            :     // Supplies a chainstate, if one is needed
      72                 :            :     void LoadVerifyActivateChainstate();
      73                 :            : };
      74                 :            : 
      75                 :            : /** Testing setup that configures a complete environment.
      76                 :            :  */
      77                 :          0 : struct TestingSetup : public ChainTestingSetup {
      78                 :            :     explicit TestingSetup(
      79                 :            :         const ChainType chainType = ChainType::MAIN,
      80                 :            :         const std::vector<const char*>& extra_args = {},
      81                 :            :         const bool coins_db_in_memory = true,
      82                 :            :         const bool block_tree_db_in_memory = true);
      83                 :            : };
      84                 :            : 
      85                 :            : /** Identical to TestingSetup, but chain set to regtest */
      86                 :            : struct RegTestingSetup : public TestingSetup {
      87                 :            :     RegTestingSetup()
      88                 :            :         : TestingSetup{ChainType::REGTEST} {}
      89                 :            : };
      90                 :            : 
      91                 :            : class CBlock;
      92                 :            : struct CMutableTransaction;
      93                 :            : class CScript;
      94                 :            : 
      95                 :            : /**
      96                 :            :  * Testing fixture that pre-creates a 100-block REGTEST-mode block chain
      97                 :            :  */
      98                 :          0 : struct TestChain100Setup : public TestingSetup {
      99                 :            :     TestChain100Setup(
     100                 :            :         const ChainType chain_type = ChainType::REGTEST,
     101                 :            :         const std::vector<const char*>& extra_args = {},
     102                 :            :         const bool coins_db_in_memory = true,
     103                 :            :         const bool block_tree_db_in_memory = true);
     104                 :            : 
     105                 :            :     /**
     106                 :            :      * Create a new block with just given transactions, coinbase paying to
     107                 :            :      * scriptPubKey, and try to add it to the current chain.
     108                 :            :      * If no chainstate is specified, default to the active.
     109                 :            :      */
     110                 :            :     CBlock CreateAndProcessBlock(const std::vector<CMutableTransaction>& txns,
     111                 :            :                                  const CScript& scriptPubKey,
     112                 :            :                                  Chainstate* chainstate = nullptr);
     113                 :            : 
     114                 :            :     /**
     115                 :            :      * Create a new block with just given transactions, coinbase paying to
     116                 :            :      * scriptPubKey.
     117                 :            :      */
     118                 :            :     CBlock CreateBlock(
     119                 :            :         const std::vector<CMutableTransaction>& txns,
     120                 :            :         const CScript& scriptPubKey,
     121                 :            :         Chainstate& chainstate);
     122                 :            : 
     123                 :            :     //! Mine a series of new blocks on the active chain.
     124                 :            :     void mineBlocks(int num_blocks);
     125                 :            : 
     126                 :            :     /**
     127                 :            :     * Create a transaction, optionally setting the fee based on the feerate.
     128                 :            :     * Note: The feerate may not be met exactly depending on whether the signatures can have different sizes.
     129                 :            :     *
     130                 :            :     * @param input_transactions   The transactions to spend
     131                 :            :     * @param inputs               Outpoints with which to construct transaction vin.
     132                 :            :     * @param input_height         The height of the block that included the input transactions.
     133                 :            :     * @param input_signing_keys   The keys to spend the input transactions.
     134                 :            :     * @param outputs              Transaction vout.
     135                 :            :     * @param feerate              The feerate the transaction should pay.
     136                 :            :     * @param fee_output           The index of the output to take the fee from.
     137                 :            :     * @return The transaction and the fee it pays
     138                 :            :     */
     139                 :            :     std::pair<CMutableTransaction, CAmount> CreateValidTransaction(const std::vector<CTransactionRef>& input_transactions,
     140                 :            :                                                                    const std::vector<COutPoint>& inputs,
     141                 :            :                                                                    int input_height,
     142                 :            :                                                                    const std::vector<CKey>& input_signing_keys,
     143                 :            :                                                                    const std::vector<CTxOut>& outputs,
     144                 :            :                                                                    const std::optional<CFeeRate>& feerate,
     145                 :            :                                                                    const std::optional<uint32_t>& fee_output);
     146                 :            :     /**
     147                 :            :      * Create a transaction and, optionally, submit to the mempool.
     148                 :            :      *
     149                 :            :      * @param input_transactions   The transactions to spend
     150                 :            :      * @param inputs               Outpoints with which to construct transaction vin.
     151                 :            :      * @param input_height         The height of the block that included the input transaction(s).
     152                 :            :      * @param input_signing_keys   The keys to spend inputs.
     153                 :            :      * @param outputs              Transaction vout.
     154                 :            :      * @param submit               Whether or not to submit to mempool
     155                 :            :      */
     156                 :            :     CMutableTransaction CreateValidMempoolTransaction(const std::vector<CTransactionRef>& input_transactions,
     157                 :            :                                                       const std::vector<COutPoint>& inputs,
     158                 :            :                                                       int input_height,
     159                 :            :                                                       const std::vector<CKey>& input_signing_keys,
     160                 :            :                                                       const std::vector<CTxOut>& outputs,
     161                 :            :                                                       bool submit = true);
     162                 :            : 
     163                 :            :     /**
     164                 :            :      * Create a 1-in-1-out transaction and, optionally, submit to the mempool.
     165                 :            :      *
     166                 :            :      * @param input_transaction  The transaction to spend
     167                 :            :      * @param input_vout         The vout to spend from the input_transaction
     168                 :            :      * @param input_height       The height of the block that included the input_transaction
     169                 :            :      * @param input_signing_key  The key to spend the input_transaction
     170                 :            :      * @param output_destination Where to send the output
     171                 :            :      * @param output_amount      How much to send
     172                 :            :      * @param submit             Whether or not to submit to mempool
     173                 :            :      */
     174                 :            :     CMutableTransaction CreateValidMempoolTransaction(CTransactionRef input_transaction,
     175                 :            :                                                       uint32_t input_vout,
     176                 :            :                                                       int input_height,
     177                 :            :                                                       CKey input_signing_key,
     178                 :            :                                                       CScript output_destination,
     179                 :            :                                                       CAmount output_amount = CAmount(1 * COIN),
     180                 :            :                                                       bool submit = true);
     181                 :            : 
     182                 :            :     /** Create transactions spending from m_coinbase_txns. These transactions will only spend coins
     183                 :            :      * that exist in the current chain, but may be premature coinbase spends, have missing
     184                 :            :      * signatures, or violate some other consensus rules. They should only be used for testing
     185                 :            :      * mempool consistency. All transactions will have some random number of inputs and outputs
     186                 :            :      * (between 1 and 24). Transactions may or may not be dependent upon each other; if dependencies
     187                 :            :      * exit, every parent will always be somewhere in the list before the child so each transaction
     188                 :            :      * can be submitted in the same order they appear in the list.
     189                 :            :      * @param[in]   submit      When true, submit transactions to the mempool.
     190                 :            :      *                          When false, return them but don't submit them.
     191                 :            :      * @returns A vector of transactions that can be submitted to the mempool.
     192                 :            :      */
     193                 :            :     std::vector<CTransactionRef> PopulateMempool(FastRandomContext& det_rand, size_t num_transactions, bool submit);
     194                 :            : 
     195                 :            :     /** Mock the mempool minimum feerate by adding a transaction and calling TrimToSize(0),
     196                 :            :      * simulating the mempool "reaching capacity" and evicting by descendant feerate.  Note that
     197                 :            :      * this clears the mempool, and the new minimum feerate will depend on the maximum feerate of
     198                 :            :      * transactions removed, so this must be called while the mempool is empty.
     199                 :            :      *
     200                 :            :      * @param target_feerate    The new mempool minimum feerate after this function returns.
     201                 :            :      *                          Must be above max(incremental feerate, min relay feerate),
     202                 :            :      *                          or 1sat/vB with default settings.
     203                 :            :      */
     204                 :            :     void MockMempoolMinFee(const CFeeRate& target_feerate);
     205                 :            : 
     206                 :            :     std::vector<CTransactionRef> m_coinbase_txns; // For convenience, coinbase transactions
     207                 :            :     CKey coinbaseKey; // private/public key needed to spend coinbase transactions
     208                 :            : };
     209                 :            : 
     210                 :            : /**
     211                 :            :  * Make a test setup that has disk access to the debug.log file disabled. Can
     212                 :            :  * be used in "hot loops", for example fuzzing or benchmarking.
     213                 :            :  */
     214                 :            : template <class T = const BasicTestingSetup>
     215                 :          1 : std::unique_ptr<T> MakeNoLogFileContext(const ChainType chain_type = ChainType::REGTEST, const std::vector<const char*>& extra_args = {})
     216                 :            : {
     217         [ +  - ]:          1 :     const std::vector<const char*> arguments = Cat(
     218         [ +  - ]:          1 :         {
     219                 :            :             "-nodebuglogfile",
     220                 :            :             "-nodebug",
     221                 :            :         },
     222                 :          1 :         extra_args);
     223                 :            : 
     224         [ -  + ]:          1 :     return std::make_unique<T>(chain_type, arguments);
     225                 :          1 : }
     226                 :            : 
     227                 :            : CBlock getBlock13b8a();
     228                 :            : 
     229                 :            : // define an implicit conversion here so that uint256 may be used directly in BOOST_CHECK_*
     230                 :            : std::ostream& operator<<(std::ostream& os, const uint256& num);
     231                 :            : 
     232                 :            : /**
     233                 :            :  * BOOST_CHECK_EXCEPTION predicates to check the specific validation error.
     234                 :            :  * Use as
     235                 :            :  * BOOST_CHECK_EXCEPTION(code that throws, exception type, HasReason("foo"));
     236                 :            :  */
     237                 :            : class HasReason
     238                 :            : {
     239                 :            : public:
     240                 :            :     explicit HasReason(const std::string& reason) : m_reason(reason) {}
     241                 :            :     bool operator()(const std::exception& e) const
     242                 :            :     {
     243                 :            :         return std::string(e.what()).find(m_reason) != std::string::npos;
     244                 :            :     };
     245                 :            : 
     246                 :            : private:
     247                 :            :     const std::string m_reason;
     248                 :            : };
     249                 :            : 
     250                 :            : #endif // BITCOIN_TEST_UTIL_SETUP_COMMON_H

Generated by: LCOV version 1.14