LCOV - code coverage report
Current view: top level - src/test/util - setup_common.h (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 83.3 % 18 15
Test Date: 2024-11-04 05:10:19 Functions: 66.7 % 6 4
Branches: 41.0 % 78 32

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2015-present 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> // IWYU pragma: export
       9                 :             : #include <kernel/context.h>
      10                 :             : #include <key.h>
      11                 :             : #include <node/caches.h>
      12                 :             : #include <node/context.h> // IWYU pragma: export
      13                 :             : #include <optional>
      14                 :             : #include <ostream>
      15                 :             : #include <primitives/transaction.h>
      16                 :             : #include <pubkey.h>
      17                 :             : #include <stdexcept>
      18                 :             : #include <test/util/random.h>
      19                 :             : #include <util/chaintype.h> // IWYU pragma: export
      20                 :             : #include <util/check.h>
      21                 :             : #include <util/fs.h>
      22                 :             : #include <util/signalinterrupt.h>
      23                 :             : #include <util/string.h>
      24                 :             : #include <util/vector.h>
      25                 :             : 
      26                 :             : #include <functional>
      27                 :             : #include <type_traits>
      28                 :             : #include <vector>
      29                 :             : 
      30                 :             : class arith_uint256;
      31                 :             : class CFeeRate;
      32                 :             : class Chainstate;
      33                 :             : class FastRandomContext;
      34                 :             : class uint160;
      35                 :             : class uint256;
      36                 :             : 
      37                 :             : /** This is connected to the logger. Can be used to redirect logs to any other log */
      38                 :             : extern const std::function<void(const std::string&)> G_TEST_LOG_FUN;
      39                 :             : 
      40                 :             : /** Retrieve the command line arguments. */
      41                 :             : extern const std::function<std::vector<const char*>()> G_TEST_COMMAND_LINE_ARGUMENTS;
      42                 :             : 
      43                 :             : /** Retrieve the unit test name. */
      44                 :             : extern const std::function<std::string()> G_TEST_GET_FULL_NAME;
      45                 :             : 
      46                 :             : static constexpr CAmount CENT{1000000};
      47                 :             : 
      48 [ +  - ][ +  -  :         811 : struct TestOpts {
          +  -  +  -  +  
                      - ]
      49                 :             :     std::vector<const char*> extra_args{};
      50                 :             :     bool coins_db_in_memory{true};
      51                 :             :     bool block_tree_db_in_memory{true};
      52                 :             :     bool setup_net{true};
      53                 :             :     bool setup_validation_interface{true};
      54                 :             :     bool min_validation_cache{false}; // Equivalent of -maxsigcachebytes=0
      55                 :             : };
      56                 :             : 
      57                 :             : /** Basic testing setup.
      58                 :             :  * This just configures logging, data dir and chain parameters.
      59                 :             :  */
      60                 :             : struct BasicTestingSetup {
      61                 :             :     util::SignalInterrupt m_interrupt;
      62                 :             :     node::NodeContext m_node; // keep as first member to be destructed last
      63                 :             : 
      64                 :             :     FastRandomContext m_rng;
      65                 :             :     /** Seed the global RNG state and m_rng for testing and log the seed value. This affects all randomness, except GetStrongRandBytes(). */
      66                 :         601 :     void SeedRandomForTest(SeedRand seed)
      67                 :             :     {
      68                 :         601 :         SeedRandomStateForTest(seed);
      69                 :         601 :         m_rng.Reseed(GetRandHash());
      70                 :         601 :     }
      71                 :             : 
      72                 :             :     explicit BasicTestingSetup(const ChainType chainType = ChainType::MAIN, TestOpts = {});
      73                 :             :     ~BasicTestingSetup();
      74                 :             : 
      75                 :             :     fs::path m_path_root;
      76                 :             :     fs::path m_path_lock;
      77                 :             :     bool m_has_custom_datadir{false};
      78                 :             :     /** @brief Test-specific arguments and settings.
      79                 :             :      *
      80                 :             :      * This member is intended to be the primary source of settings for code
      81                 :             :      * being tested by unit tests. It exists to make tests more self-contained
      82                 :             :      * and reduce reliance on global state.
      83                 :             :      *
      84                 :             :      * Usage guidelines:
      85                 :             :      * 1. Prefer using m_args where possible in test code.
      86                 :             :      * 2. If m_args is not accessible, use m_node.args as a fallback.
      87                 :             :      * 3. Avoid direct references to gArgs in test code.
      88                 :             :      *
      89                 :             :      * Note: Currently, m_node.args points to gArgs for backwards
      90                 :             :      * compatibility. In the future, it will point to m_args to further isolate
      91                 :             :      * test environments.
      92                 :             :      *
      93                 :             :      * @see https://github.com/bitcoin/bitcoin/issues/25055 for additional context.
      94                 :             :      */
      95                 :             :     ArgsManager m_args;
      96                 :             : };
      97                 :             : 
      98                 :             : /** Testing setup that performs all steps up until right before
      99                 :             :  * ChainstateManager gets initialized. Meant for testing ChainstateManager
     100                 :             :  * initialization behaviour.
     101                 :             :  */
     102                 :             : struct ChainTestingSetup : public BasicTestingSetup {
     103                 :             :     node::CacheSizes m_cache_sizes{};
     104                 :             :     bool m_coins_db_in_memory{true};
     105                 :             :     bool m_block_tree_db_in_memory{true};
     106                 :             :     std::function<void()> m_make_chainman{};
     107                 :             : 
     108                 :             :     explicit ChainTestingSetup(const ChainType chainType = ChainType::MAIN, TestOpts = {});
     109                 :             :     ~ChainTestingSetup();
     110                 :             : 
     111                 :             :     // Supplies a chainstate, if one is needed
     112                 :             :     void LoadVerifyActivateChainstate();
     113                 :             : };
     114                 :             : 
     115                 :             : /** Testing setup that configures a complete environment.
     116                 :             :  */
     117                 :         139 : struct TestingSetup : public ChainTestingSetup {
     118                 :             :     explicit TestingSetup(
     119                 :             :         const ChainType chainType = ChainType::MAIN,
     120                 :             :         TestOpts = {});
     121                 :             : };
     122                 :             : 
     123                 :             : /** Identical to TestingSetup, but chain set to regtest */
     124                 :          30 : struct RegTestingSetup : public TestingSetup {
     125                 :          30 :     RegTestingSetup()
     126         [ +  - ]:          60 :         : TestingSetup{ChainType::REGTEST} {}
     127                 :             : };
     128                 :             : 
     129                 :             : class CBlock;
     130                 :             : struct CMutableTransaction;
     131                 :             : class CScript;
     132                 :             : 
     133                 :             : /**
     134                 :             :  * Testing fixture that pre-creates a 100-block REGTEST-mode block chain
     135                 :             :  */
     136                 :             : struct TestChain100Setup : public TestingSetup {
     137                 :             :     TestChain100Setup(
     138                 :             :         const ChainType chain_type = ChainType::REGTEST,
     139                 :             :         TestOpts = {});
     140                 :             : 
     141                 :             :     /**
     142                 :             :      * Create a new block with just given transactions, coinbase paying to
     143                 :             :      * scriptPubKey, and try to add it to the current chain.
     144                 :             :      * If no chainstate is specified, default to the active.
     145                 :             :      */
     146                 :             :     CBlock CreateAndProcessBlock(const std::vector<CMutableTransaction>& txns,
     147                 :             :                                  const CScript& scriptPubKey,
     148                 :             :                                  Chainstate* chainstate = nullptr);
     149                 :             : 
     150                 :             :     /**
     151                 :             :      * Create a new block with just given transactions, coinbase paying to
     152                 :             :      * scriptPubKey.
     153                 :             :      */
     154                 :             :     CBlock CreateBlock(
     155                 :             :         const std::vector<CMutableTransaction>& txns,
     156                 :             :         const CScript& scriptPubKey,
     157                 :             :         Chainstate& chainstate);
     158                 :             : 
     159                 :             :     //! Mine a series of new blocks on the active chain.
     160                 :             :     void mineBlocks(int num_blocks);
     161                 :             : 
     162                 :             :     /**
     163                 :             :     * Create a transaction, optionally setting the fee based on the feerate.
     164                 :             :     * Note: The feerate may not be met exactly depending on whether the signatures can have different sizes.
     165                 :             :     *
     166                 :             :     * @param input_transactions   The transactions to spend
     167                 :             :     * @param inputs               Outpoints with which to construct transaction vin.
     168                 :             :     * @param input_height         The height of the block that included the input transactions.
     169                 :             :     * @param input_signing_keys   The keys to spend the input transactions.
     170                 :             :     * @param outputs              Transaction vout.
     171                 :             :     * @param feerate              The feerate the transaction should pay.
     172                 :             :     * @param fee_output           The index of the output to take the fee from.
     173                 :             :     * @return The transaction and the fee it pays
     174                 :             :     */
     175                 :             :     std::pair<CMutableTransaction, CAmount> CreateValidTransaction(const std::vector<CTransactionRef>& input_transactions,
     176                 :             :                                                                    const std::vector<COutPoint>& inputs,
     177                 :             :                                                                    int input_height,
     178                 :             :                                                                    const std::vector<CKey>& input_signing_keys,
     179                 :             :                                                                    const std::vector<CTxOut>& outputs,
     180                 :             :                                                                    const std::optional<CFeeRate>& feerate,
     181                 :             :                                                                    const std::optional<uint32_t>& fee_output);
     182                 :             :     /**
     183                 :             :      * Create a transaction and, optionally, submit to the mempool.
     184                 :             :      *
     185                 :             :      * @param input_transactions   The transactions to spend
     186                 :             :      * @param inputs               Outpoints with which to construct transaction vin.
     187                 :             :      * @param input_height         The height of the block that included the input transaction(s).
     188                 :             :      * @param input_signing_keys   The keys to spend inputs.
     189                 :             :      * @param outputs              Transaction vout.
     190                 :             :      * @param submit               Whether or not to submit to mempool
     191                 :             :      */
     192                 :             :     CMutableTransaction CreateValidMempoolTransaction(const std::vector<CTransactionRef>& input_transactions,
     193                 :             :                                                       const std::vector<COutPoint>& inputs,
     194                 :             :                                                       int input_height,
     195                 :             :                                                       const std::vector<CKey>& input_signing_keys,
     196                 :             :                                                       const std::vector<CTxOut>& outputs,
     197                 :             :                                                       bool submit = true);
     198                 :             : 
     199                 :             :     /**
     200                 :             :      * Create a 1-in-1-out transaction and, optionally, submit to the mempool.
     201                 :             :      *
     202                 :             :      * @param input_transaction  The transaction to spend
     203                 :             :      * @param input_vout         The vout to spend from the input_transaction
     204                 :             :      * @param input_height       The height of the block that included the input_transaction
     205                 :             :      * @param input_signing_key  The key to spend the input_transaction
     206                 :             :      * @param output_destination Where to send the output
     207                 :             :      * @param output_amount      How much to send
     208                 :             :      * @param submit             Whether or not to submit to mempool
     209                 :             :      */
     210                 :             :     CMutableTransaction CreateValidMempoolTransaction(CTransactionRef input_transaction,
     211                 :             :                                                       uint32_t input_vout,
     212                 :             :                                                       int input_height,
     213                 :             :                                                       CKey input_signing_key,
     214                 :             :                                                       CScript output_destination,
     215                 :             :                                                       CAmount output_amount = CAmount(1 * COIN),
     216                 :             :                                                       bool submit = true);
     217                 :             : 
     218                 :             :     /** Create transactions spending from m_coinbase_txns. These transactions will only spend coins
     219                 :             :      * that exist in the current chain, but may be premature coinbase spends, have missing
     220                 :             :      * signatures, or violate some other consensus rules. They should only be used for testing
     221                 :             :      * mempool consistency. All transactions will have some random number of inputs and outputs
     222                 :             :      * (between 1 and 24). Transactions may or may not be dependent upon each other; if dependencies
     223                 :             :      * exit, every parent will always be somewhere in the list before the child so each transaction
     224                 :             :      * can be submitted in the same order they appear in the list.
     225                 :             :      * @param[in]   submit      When true, submit transactions to the mempool.
     226                 :             :      *                          When false, return them but don't submit them.
     227                 :             :      * @returns A vector of transactions that can be submitted to the mempool.
     228                 :             :      */
     229                 :             :     std::vector<CTransactionRef> PopulateMempool(FastRandomContext& det_rand, size_t num_transactions, bool submit);
     230                 :             : 
     231                 :             :     /** Mock the mempool minimum feerate by adding a transaction and calling TrimToSize(0),
     232                 :             :      * simulating the mempool "reaching capacity" and evicting by descendant feerate.  Note that
     233                 :             :      * this clears the mempool, and the new minimum feerate will depend on the maximum feerate of
     234                 :             :      * transactions removed, so this must be called while the mempool is empty.
     235                 :             :      *
     236                 :             :      * @param target_feerate    The new mempool minimum feerate after this function returns.
     237                 :             :      *                          Must be above max(incremental feerate, min relay feerate),
     238                 :             :      *                          or 1sat/vB with default settings.
     239                 :             :      */
     240                 :             :     void MockMempoolMinFee(const CFeeRate& target_feerate);
     241                 :             : 
     242                 :             :     std::vector<CTransactionRef> m_coinbase_txns; // For convenience, coinbase transactions
     243                 :             :     CKey coinbaseKey; // private/public key needed to spend coinbase transactions
     244                 :             : };
     245                 :             : 
     246                 :             : /**
     247                 :             :  * Make a test setup that has disk access to the debug.log file disabled. Can
     248                 :             :  * be used in "hot loops", for example fuzzing or benchmarking.
     249                 :             :  */
     250                 :             : template <class T = const BasicTestingSetup>
     251                 :             : std::unique_ptr<T> MakeNoLogFileContext(const ChainType chain_type = ChainType::REGTEST, TestOpts opts = {})
     252                 :             : {
     253                 :             :     opts.extra_args = Cat(
     254                 :             :         {
     255                 :             :             "-nodebuglogfile",
     256                 :             :             "-nodebug",
     257                 :             :         },
     258                 :             :         opts.extra_args);
     259                 :             : 
     260                 :             :     return std::make_unique<T>(chain_type, opts);
     261                 :             : }
     262                 :             : 
     263                 :             : CBlock getBlock13b8a();
     264                 :             : 
     265                 :             : // Make types usable in BOOST_CHECK_* @{
     266                 :             : namespace std {
     267                 :             : template <typename T> requires std::is_enum_v<T>
     268                 :          54 : inline std::ostream& operator<<(std::ostream& os, const T& e)
     269                 :             : {
     270         [ -  - ]:          54 :     return os << static_cast<std::underlying_type_t<T>>(e);
     271                 :             : }
     272                 :             : 
     273                 :             : template <typename T>
     274         [ #  # ]:           0 : inline std::ostream& operator<<(std::ostream& os, const std::optional<T>& v)
     275                 :             : {
     276         [ #  # ]:           0 :     return v ? os << *v
     277                 :           0 :              : os << "std::nullopt";
     278                 :             : }
     279                 :             : } // namespace std
     280                 :             : 
     281                 :             : std::ostream& operator<<(std::ostream& os, const arith_uint256& num);
     282                 :             : std::ostream& operator<<(std::ostream& os, const uint160& num);
     283                 :             : std::ostream& operator<<(std::ostream& os, const uint256& num);
     284                 :             : // @}
     285                 :             : 
     286                 :             : /**
     287                 :             :  * BOOST_CHECK_EXCEPTION predicates to check the specific validation error.
     288                 :             :  * Use as
     289                 :             :  * BOOST_CHECK_EXCEPTION(code that throws, exception type, HasReason("foo"));
     290                 :             :  */
     291                 :          40 : class HasReason
     292                 :             : {
     293                 :             : public:
     294   [ +  -  +  -  :          40 :     explicit HasReason(std::string_view reason) : m_reason(reason) {}
          +  -  +  -  +  
             -  +  -  +  
                      - ]
           [ +  -  +  - ]
           [ +  -  +  -  
           +  - ][ +  -  
          -  -  -  -  -  
           -  -  - ][ +  
          -  +  -  +  -  
             +  -  +  - ]
           [ +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
                   +  - ]
     295                 :          40 :     bool operator()(std::string_view s) const { return s.find(m_reason) != std::string_view::npos; }
     296                 :          28 :     bool operator()(const std::exception& e) const { return (*this)(e.what()); }
     297                 :             : 
     298                 :             : private:
     299                 :             :     const std::string m_reason;
     300                 :             : };
     301                 :             : 
     302                 :             : #endif // BITCOIN_TEST_UTIL_SETUP_COMMON_H
        

Generated by: LCOV version 2.0-1