Bitcoin Core  24.1.0
P2P Digital Currency
setup_common.h
Go to the documentation of this file.
1 // Copyright (c) 2015-2021 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 <chainparamsbase.h>
9 #include <fs.h>
10 #include <key.h>
11 #include <util/system.h>
12 #include <node/caches.h>
13 #include <node/context.h>
14 #include <pubkey.h>
15 #include <random.h>
16 #include <stdexcept>
17 #include <txmempool.h>
18 #include <util/check.h>
19 #include <util/string.h>
20 #include <util/vector.h>
21 
22 #include <functional>
23 #include <type_traits>
24 #include <vector>
25 
27 extern const std::function<void(const std::string&)> G_TEST_LOG_FUN;
28 
30 extern const std::function<std::vector<const char*>()> G_TEST_COMMAND_LINE_ARGUMENTS;
31 
32 // Enable BOOST_CHECK_EQUAL for enum class types
33 namespace std {
34 template <typename T>
35 std::ostream& operator<<(typename std::enable_if<std::is_enum<T>::value, std::ostream>::type& stream, const T& e)
36 {
37  return stream << static_cast<typename std::underlying_type<T>::type>(e);
38 }
39 } // namespace std
40 
49 
53 extern bool g_mock_deterministic_tests;
54 
55 enum class SeedRand {
56  ZEROS,
57  SEED,
58 };
59 
62 
63 static inline void SeedInsecureRand(SeedRand seed = SeedRand::SEED)
64 {
65  if (seed == SeedRand::ZEROS) {
66  g_insecure_rand_ctx = FastRandomContext(/*fDeterministic=*/true);
67  } else {
69  }
70 }
71 
72 static inline uint32_t InsecureRand32() { return g_insecure_rand_ctx.rand32(); }
73 static inline uint256 InsecureRand256() { return g_insecure_rand_ctx.rand256(); }
74 static inline uint64_t InsecureRandBits(int bits) { return g_insecure_rand_ctx.randbits(bits); }
75 static inline uint64_t InsecureRandRange(uint64_t range) { return g_insecure_rand_ctx.randrange(range); }
76 static inline bool InsecureRandBool() { return g_insecure_rand_ctx.randbool(); }
77 
78 static constexpr CAmount CENT{1000000};
79 
84  node::NodeContext m_node; // keep as first member to be destructed last
85 
86  explicit BasicTestingSetup(const std::string& chainName = CBaseChainParams::MAIN, const std::vector<const char*>& extra_args = {});
88 
91 };
92 
93 
95 
102 
103  explicit ChainTestingSetup(const std::string& chainName = CBaseChainParams::MAIN, const std::vector<const char*>& extra_args = {});
105 };
106 
110  explicit TestingSetup(const std::string& chainName = CBaseChainParams::MAIN, const std::vector<const char*>& extra_args = {});
111 };
112 
114 struct RegTestingSetup : public TestingSetup {
117 };
118 
119 class CBlock;
120 struct CMutableTransaction;
121 class CScript;
122 
127  TestChain100Setup(const std::string& chain_name = CBaseChainParams::REGTEST,
128  const std::vector<const char*>& extra_args = {});
129 
135  CBlock CreateAndProcessBlock(const std::vector<CMutableTransaction>& txns,
136  const CScript& scriptPubKey,
137  Chainstate* chainstate = nullptr);
138 
144  const std::vector<CMutableTransaction>& txns,
145  const CScript& scriptPubKey,
146  Chainstate& chainstate);
147 
149  void mineBlocks(int num_blocks);
150 
163  int input_vout,
164  int input_height,
165  CKey input_signing_key,
166  CScript output_destination,
167  CAmount output_amount = CAmount(1 * COIN),
168  bool submit = true);
169 
181  std::vector<CTransactionRef> PopulateMempool(FastRandomContext& det_rand, size_t num_transactions, bool submit);
182 
183  std::vector<CTransactionRef> m_coinbase_txns; // For convenience, coinbase transactions
184  CKey coinbaseKey; // private/public key needed to spend coinbase transactions
185 };
186 
191 template <class T = const BasicTestingSetup>
192 std::unique_ptr<T> MakeNoLogFileContext(const std::string& chain_name = CBaseChainParams::REGTEST, const std::vector<const char*>& extra_args = {})
193 {
194  const std::vector<const char*> arguments = Cat(
195  {
196  "-nodebuglogfile",
197  "-nodebug",
198  },
199  extra_args);
200 
201  return std::make_unique<T>(chain_name, arguments);
202 }
203 
204 class CTxMemPoolEntry;
205 
207 {
208  // Default values
210  int64_t nTime;
211  unsigned int nHeight;
213  unsigned int sigOpCost;
215 
217  nFee(0), nTime(0), nHeight(1),
218  spendsCoinbase(false), sigOpCost(4) { }
219 
220  CTxMemPoolEntry FromTx(const CMutableTransaction& tx) const;
221  CTxMemPoolEntry FromTx(const CTransactionRef& tx) const;
222 
223  // Change the default value
224  TestMemPoolEntryHelper &Fee(CAmount _fee) { nFee = _fee; return *this; }
225  TestMemPoolEntryHelper &Time(int64_t _time) { nTime = _time; return *this; }
226  TestMemPoolEntryHelper &Height(unsigned int _height) { nHeight = _height; return *this; }
227  TestMemPoolEntryHelper &SpendsCoinbase(bool _flag) { spendsCoinbase = _flag; return *this; }
228  TestMemPoolEntryHelper &SigOpsCost(unsigned int _sigopsCost) { sigOpCost = _sigopsCost; return *this; }
229 };
230 
232 
233 // define an implicit conversion here so that uint256 may be used directly in BOOST_CHECK_*
234 std::ostream& operator<<(std::ostream& os, const uint256& num);
235 
242 {
243 public:
244  explicit HasReason(const std::string& reason) : m_reason(reason) {}
245  bool operator()(const std::exception& e) const
246  {
247  return std::string(e.what()).find(m_reason) != std::string::npos;
248  };
249 
250 private:
251  const std::string m_reason;
252 };
253 
254 #endif // BITCOIN_TEST_UTIL_SETUP_COMMON_H
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:414
std::unique_ptr< T > MakeNoLogFileContext(const std::string &chain_name=CBaseChainParams::REGTEST, const std::vector< const char *> &extra_args={})
Make a test setup that has disk access to the debug.log file disabled.
Definition: setup_common.h:192
static bool InsecureRandBool()
Definition: setup_common.h:76
CTxMemPool::Options MemPoolOptionsForTest(const node::NodeContext &node)
Testing setup that performs all steps up until right before ChainstateManager gets initialized...
Definition: setup_common.h:100
LockPoints lp
Definition: setup_common.h:214
Definition: setup_common.h:206
static const std::string REGTEST
TestMemPoolEntryHelper & Fee(CAmount _fee)
Definition: setup_common.h:224
Definition: block.h:68
void Seed(FastRandomContext &ctx)
Seed the given random ctx or use the seed passed in via an environment var.
ArgsManager m_args
Definition: setup_common.h:90
TestChain100Setup(const std::string &chain_name=CBaseChainParams::REGTEST, const std::vector< const char *> &extra_args={})
node::CacheSizes m_cache_sizes
Definition: setup_common.h:101
std::vector< CTransactionRef > m_coinbase_txns
Definition: setup_common.h:183
FastRandomContext g_insecure_rand_ctx
This global and the helpers that use it are not thread-safe.
uint256 rand256() noexcept
generate a random uint256.
Definition: random.cpp:606
CTxMemPoolEntry FromTx(const CMutableTransaction &tx) const
static uint32_t InsecureRand32()
Definition: setup_common.h:72
ChainTestingSetup(const std::string &chainName=CBaseChainParams::MAIN, const std::vector< const char *> &extra_args={})
Basic testing setup.
Definition: setup_common.h:83
static void SeedInsecureRand(SeedRand seed=SeedRand::SEED)
Definition: setup_common.h:63
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: txmempool.h:88
static const std::string MAIN
Chain name strings.
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
TestMemPoolEntryHelper & SpendsCoinbase(bool _flag)
Definition: setup_common.h:227
uint64_t randbits(int bits) noexcept
Generate a random (bits)-bit integer.
Definition: random.h:195
NodeContext struct containing references to chain state and connection state.
Definition: context.h:43
static uint64_t InsecureRandRange(uint64_t range)
Definition: setup_common.h:75
CBlock CreateAndProcessBlock(const std::vector< CMutableTransaction > &txns, const CScript &scriptPubKey, Chainstate *chainstate=nullptr)
Create a new block with just given transactions, coinbase paying to scriptPubKey, and try to add it t...
Chainstate stores and provides an API to update our local knowledge of the current best chain...
Definition: validation.h:437
TestingSetup(const std::string &chainName=CBaseChainParams::MAIN, const std::vector< const char *> &extra_args={})
std::vector< CTransactionRef > PopulateMempool(FastRandomContext &det_rand, size_t num_transactions, bool submit)
Create transactions spending from m_coinbase_txns.
static secp256k1_context * ctx
Definition: tests.c:34
Fast randomness source.
Definition: random.h:142
BOOST_CHECK_EXCEPTION predicates to check the specific validation error.
Definition: setup_common.h:241
Call the Seed() helper.
void mineBlocks(int num_blocks)
Mine a series of new blocks on the active chain.
BasicTestingSetup(const std::string &chainName=CBaseChainParams::MAIN, const std::vector< const char *> &extra_args={})
static uint64_t InsecureRandBits(int bits)
Definition: setup_common.h:74
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
Definition: setup_common.h:126
bool g_mock_deterministic_tests
Flag to make GetRand in random.h return the same number.
Definition: random.cpp:585
int64_t nTime
Definition: setup_common.h:210
TestMemPoolEntryHelper & Height(unsigned int _height)
Definition: setup_common.h:226
Definition: init.h:25
uint32_t rand32() noexcept
Generate a random 32-bit integer.
Definition: random.h:228
bool spendsCoinbase
Definition: setup_common.h:212
unsigned int nHeight
Definition: setup_common.h:211
256-bit opaque blob.
Definition: uint256.h:119
HasReason(const std::string &reason)
Definition: setup_common.h:244
CMutableTransaction CreateValidMempoolTransaction(CTransactionRef input_transaction, int input_vout, int input_height, CKey input_signing_key, CScript output_destination, CAmount output_amount=CAmount(1 *COIN), bool submit=true)
Create a transaction and submit to the mempool.
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:410
CAmount nFee
Definition: setup_common.h:209
SeedRand
Definition: setup_common.h:55
CBlock CreateBlock(const std::vector< CMutableTransaction > &txns, const CScript &scriptPubKey, Chainstate &chainstate)
Create a new block with just given transactions, coinbase paying to scriptPubKey. ...
unsigned int sigOpCost
Definition: setup_common.h:213
bool operator()(const std::exception &e) const
Definition: setup_common.h:245
TestMemPoolEntryHelper & Time(int64_t _time)
Definition: setup_common.h:225
TestMemPoolEntryHelper & SigOpsCost(unsigned int _sigopsCost)
Definition: setup_common.h:228
std::ostream & operator<<(std::ostream &os, const uint256 &num)
bool randbool() noexcept
Generate a random boolean.
Definition: random.h:234
const std::function< void(const std::string &)> G_TEST_LOG_FUN
This is connected to the logger.
Definition: bench.cpp:21
A mutable version of CTransaction.
Definition: transaction.h:372
const std::function< std::vector< const char * >)> G_TEST_COMMAND_LINE_ARGUMENTS
Retrieve the command line arguments.
Definition: bench.cpp:23
static constexpr CAmount CENT
Definition: setup_common.h:78
Options struct containing options for constructing a CTxMemPool.
An encapsulated private key.
Definition: key.h:26
static uint256 InsecureRand256()
Definition: setup_common.h:73
Identical to TestingSetup, but chain set to regtest.
Definition: setup_common.h:114
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
CBlock getBlock13b8a()
node::NodeContext m_node
Definition: setup_common.h:84
#define T(expected, seed, data)
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
Definition: random.h:213
Testing setup that configures a complete environment.
Definition: setup_common.h:109
Seed with a compile time constant of zeros.
TestMemPoolEntryHelper()
Definition: setup_common.h:216
V Cat(V v1, V &&v2)
Concatenate two vectors, moving elements.
Definition: vector.h:32
static constexpr CAmount COIN
The amount of satoshis in one BTC.
Definition: amount.h:15
const fs::path m_path_root
Definition: setup_common.h:89
const std::string m_reason
Definition: setup_common.h:248