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 static constexpr CAmount CENT{1000000};
42 43 /** Register common test args. Shared across binaries that rely on the test framework. */
44 void SetupCommonTestArgs(ArgsManager& argsman);
45 46 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 void SeedRandomForTest(SeedRand seed)
65 {
66 SeedRandomStateForTest(seed);
67 m_rng.Reseed(GetRandHash());
68 }
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 // Supplies a chainstate, if one is needed
110 void LoadVerifyActivateChainstate();
111 };
112 113 /** Testing setup that configures a complete environment.
114 */
115 struct TestingSetup : public ChainTestingSetup {
116 explicit TestingSetup(
117 ChainType chainType = ChainType::MAIN,
118 TestOpts = {});
119 };
120 121 /** Identical to TestingSetup, but chain set to regtest */
122 struct RegTestingSetup : public TestingSetup {
123 RegTestingSetup()
124 : TestingSetup{ChainType::REGTEST} {}
125 };
126 127 /** Identical to TestingSetup, but chain set to testnet4 */
128 struct Testnet4Setup : public TestingSetup {
129 Testnet4Setup()
130 : TestingSetup{ChainType::TESTNET4} {}
131 };
132 133 class CBlock;
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 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 */
148 CBlock CreateAndProcessBlock(const std::vector<CMutableTransaction>& txns,
149 const CScript& scriptPubKey);
150 151 /**
152 * Create a new block with just given transactions, coinbase paying to
153 * scriptPubKey.
154 */
155 CBlock CreateBlock(
156 const std::vector<CMutableTransaction>& txns,
157 const CScript& scriptPubKey);
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 FakeNodeClock m_clock{std::chrono::seconds{1598887952}}; // 2020-08-31, arbitrary
232 std::vector<CTransactionRef> m_coinbase_txns; // For convenience, coinbase transactions
233 CKey coinbaseKey; // private/public key needed to spend coinbase transactions
234 };
235 236 /**
237 * Make a test setup that has disk access to the debug.log file disabled. Can
238 * be used in "hot loops", for example fuzzing or benchmarking.
239 */
240 template <class T = const BasicTestingSetup>
241 std::unique_ptr<T> MakeNoLogFileContext(const ChainType chain_type = ChainType::REGTEST, TestOpts opts = {})
242 {
243 opts.extra_args = Cat(
244 {
245 "-nodebuglogfile",
246 "-nodebug",
247 },
248 opts.extra_args);
249 250 return std::make_unique<T>(chain_type, opts);
251 }
252 253 class SocketTestingSetup : public BasicTestingSetup
254 {
255 public:
256 explicit SocketTestingSetup();
257 ~SocketTestingSetup();
258 259 /**
260 * Connect to the socket with a mock client and send pre-loaded data.
261 * Returns the I/O pipes from the mock client so we can read response data sent to it.
262 * Template parameter selects the socket type: DynSock by default.
263 */
264 template <typename T = DynSock>
265 std::shared_ptr<typename T::Pipes> ConnectClient(std::span<const std::byte> data)
266 {
267 auto connected_socket_pipes(std::make_shared<typename T::Pipes>());
268 connected_socket_pipes->recv.PushBytes(data.data(), data.size());
269 m_accepted_sockets.Push(std::make_unique<T>(connected_socket_pipes));
270 return connected_socket_pipes;
271 }
272 273 private:
274 //! Save the original value of CreateSock here and restore it when the test ends.
275 decltype(CreateSock) m_create_sock_orig;
276 277 //! Queue of connected sockets returned by listening socket (represents network interface)
278 DynSock::Queue m_accepted_sockets;
279 };
280 281 CBlock getBlock13b8a();
282 283 #endif // BITCOIN_TEST_UTIL_SETUP_COMMON_H
284