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

Generated by: LCOV version 1.14