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