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