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