LCOV - code coverage report
Current view: top level - src/test/util - setup_common.h (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 100.0 % 10 10
Test Date: 2024-12-04 04:00:22 Functions: 100.0 % 6 6
Branches: 41.7 % 12 5

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

Generated by: LCOV version 2.0-1