Bitcoin Core  23.99.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 
99 
100  explicit ChainTestingSetup(const std::string& chainName = CBaseChainParams::MAIN, const std::vector<const char*>& extra_args = {});
102 };
103 
107  explicit TestingSetup(const std::string& chainName = CBaseChainParams::MAIN, const std::vector<const char*>& extra_args = {});
108 };
109 
111 struct RegTestingSetup : public TestingSetup {
114 };
115 
116 class CBlock;
117 struct CMutableTransaction;
118 class CScript;
119 
124  TestChain100Setup(const std::string& chain_name = CBaseChainParams::REGTEST,
125  const std::vector<const char*>& extra_args = {});
126 
132  CBlock CreateAndProcessBlock(const std::vector<CMutableTransaction>& txns,
133  const CScript& scriptPubKey,
134  CChainState* chainstate = nullptr);
135 
141  const std::vector<CMutableTransaction>& txns,
142  const CScript& scriptPubKey,
143  CChainState& chainstate);
144 
146  void mineBlocks(int num_blocks);
147 
160  int input_vout,
161  int input_height,
162  CKey input_signing_key,
163  CScript output_destination,
164  CAmount output_amount = CAmount(1 * COIN),
165  bool submit = true);
166 
178  std::vector<CTransactionRef> PopulateMempool(FastRandomContext& det_rand, size_t num_transactions, bool submit);
179 
180  std::vector<CTransactionRef> m_coinbase_txns; // For convenience, coinbase transactions
181  CKey coinbaseKey; // private/public key needed to spend coinbase transactions
182 };
183 
188 template <class T = const BasicTestingSetup>
189 std::unique_ptr<T> MakeNoLogFileContext(const std::string& chain_name = CBaseChainParams::REGTEST, const std::vector<const char*>& extra_args = {})
190 {
191  const std::vector<const char*> arguments = Cat(
192  {
193  "-nodebuglogfile",
194  "-nodebug",
195  },
196  extra_args);
197 
198  return std::make_unique<T>(chain_name, arguments);
199 }
200 
201 class CTxMemPoolEntry;
202 
204 {
205  // Default values
207  int64_t nTime;
208  unsigned int nHeight;
210  unsigned int sigOpCost;
212 
214  nFee(0), nTime(0), nHeight(1),
215  spendsCoinbase(false), sigOpCost(4) { }
216 
217  CTxMemPoolEntry FromTx(const CMutableTransaction& tx) const;
218  CTxMemPoolEntry FromTx(const CTransactionRef& tx) const;
219 
220  // Change the default value
221  TestMemPoolEntryHelper &Fee(CAmount _fee) { nFee = _fee; return *this; }
222  TestMemPoolEntryHelper &Time(int64_t _time) { nTime = _time; return *this; }
223  TestMemPoolEntryHelper &Height(unsigned int _height) { nHeight = _height; return *this; }
224  TestMemPoolEntryHelper &SpendsCoinbase(bool _flag) { spendsCoinbase = _flag; return *this; }
225  TestMemPoolEntryHelper &SigOpsCost(unsigned int _sigopsCost) { sigOpCost = _sigopsCost; return *this; }
226 };
227 
229 
230 // define an implicit conversion here so that uint256 may be used directly in BOOST_CHECK_*
231 std::ostream& operator<<(std::ostream& os, const uint256& num);
232 
239 {
240 public:
241  explicit HasReason(const std::string& reason) : m_reason(reason) {}
242  bool operator()(const std::exception& e) const
243  {
244  return std::string(e.what()).find(m_reason) != std::string::npos;
245  };
246 
247 private:
248  const std::string m_reason;
249 };
250 
251 #endif // BITCOIN_TEST_UTIL_SETUP_COMMON_H
SeedRand
SeedRand
Definition: setup_common.h:55
TestChain100Setup::CreateBlock
CBlock CreateBlock(const std::vector< CMutableTransaction > &txns, const CScript &scriptPubKey, CChainState &chainstate)
Create a new block with just given transactions, coinbase paying to scriptPubKey.
Definition: setup_common.cpp:275
operator<<
std::ostream & operator<<(std::ostream &os, const uint256 &num)
Definition: setup_common.cpp:85
HasReason
BOOST_CHECK_EXCEPTION predicates to check the specific validation error.
Definition: setup_common.h:238
RegTestingSetup
Identical to TestingSetup, but chain set to regtest.
Definition: setup_common.h:111
G_TEST_LOG_FUN
const std::function< void(const std::string &)> G_TEST_LOG_FUN
This is connected to the logger.
Definition: bench.cpp:21
BasicTestingSetup::m_node
node::NodeContext m_node
Definition: setup_common.h:84
TestMemPoolEntryHelper
Definition: setup_common.h:203
FastRandomContext::rand256
uint256 rand256() noexcept
generate a random uint256.
Definition: random.cpp:606
check.h
InsecureRandBool
static bool InsecureRandBool()
Definition: setup_common.h:76
TestMemPoolEntryHelper::nHeight
unsigned int nHeight
Definition: setup_common.h:208
SeedInsecureRand
static void SeedInsecureRand(SeedRand seed=SeedRand::SEED)
Definition: setup_common.h:63
fs.h
node::CacheSizes
Definition: caches.h:14
TestChain100Setup::CreateValidMempoolTransaction
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.
Definition: setup_common.cpp:310
TestingSetup::TestingSetup
TestingSetup(const std::string &chainName=CBaseChainParams::MAIN, const std::vector< const char * > &extra_args={})
Definition: setup_common.cpp:197
Cat
V Cat(V v1, V &&v2)
Concatenate two vectors, moving elements.
Definition: vector.h:31
string.h
TestMemPoolEntryHelper::sigOpCost
unsigned int sigOpCost
Definition: setup_common.h:210
FastRandomContext::randbool
bool randbool() noexcept
Generate a random boolean.
Definition: random.h:233
ChainTestingSetup::ChainTestingSetup
ChainTestingSetup(const std::string &chainName=CBaseChainParams::MAIN, const std::vector< const char * > &extra_args={})
Definition: setup_common.cpp:152
chainparamsbase.h
BasicTestingSetup::BasicTestingSetup
BasicTestingSetup(const std::string &chainName=CBaseChainParams::MAIN, const std::vector< const char * > &extra_args={})
Definition: setup_common.cpp:91
InsecureRand256
static uint256 InsecureRand256()
Definition: setup_common.h:73
node::NodeContext
NodeContext struct containing references to chain state and connection state.
Definition: context.h:43
InsecureRandRange
static uint64_t InsecureRandRange(uint64_t range)
Definition: setup_common.h:75
G_TEST_COMMAND_LINE_ARGUMENTS
const std::function< std::vector< const char * >)> G_TEST_COMMAND_LINE_ARGUMENTS
Retrieve the command line arguments.
Definition: bench.cpp:23
BasicTestingSetup::~BasicTestingSetup
~BasicTestingSetup()
Definition: setup_common.cpp:144
TestMemPoolEntryHelper::nTime
int64_t nTime
Definition: setup_common.h:207
TestMemPoolEntryHelper::SigOpsCost
TestMemPoolEntryHelper & SigOpsCost(unsigned int _sigopsCost)
Definition: setup_common.h:225
InsecureRand32
static uint32_t InsecureRand32()
Definition: setup_common.h:72
ChainTestingSetup::~ChainTestingSetup
~ChainTestingSetup()
Definition: setup_common.cpp:181
pubkey.h
CTransactionRef
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:406
context.h
SeedRand::SEED
@ SEED
Call the Seed() helper.
FastRandomContext::randbits
uint64_t randbits(int bits) noexcept
Generate a random (bits)-bit integer.
Definition: random.h:194
txmempool.h
ChainTestingSetup::m_cache_sizes
node::CacheSizes m_cache_sizes
Definition: setup_common.h:98
TestMemPoolEntryHelper::spendsCoinbase
bool spendsCoinbase
Definition: setup_common.h:209
SeedRand::ZEROS
@ ZEROS
Seed with a compile time constant of zeros.
g_insecure_rand_ctx
FastRandomContext g_insecure_rand_ctx
This global and the helpers that use it are not thread-safe.
Definition: setup_common.cpp:62
TestMemPoolEntryHelper::TestMemPoolEntryHelper
TestMemPoolEntryHelper()
Definition: setup_common.h:213
fs::path
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:29
FastRandomContext::rand32
uint32_t rand32() noexcept
Generate a random 32-bit integer.
Definition: random.h:227
CBaseChainParams::REGTEST
static const std::string REGTEST
Definition: chainparamsbase.h:25
BasicTestingSetup::m_args
ArgsManager m_args
Definition: setup_common.h:90
CENT
static constexpr CAmount CENT
Definition: setup_common.h:78
TestMemPoolEntryHelper::nFee
CAmount nFee
Definition: setup_common.h:206
CAmount
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
BasicTestingSetup
Basic testing setup.
Definition: setup_common.h:83
std::operator<<
std::ostream & operator<<(typename std::enable_if< std::is_enum< T >::value, std::ostream >::type &stream, const T &e)
Definition: setup_common.h:35
TestMemPoolEntryHelper::SpendsCoinbase
TestMemPoolEntryHelper & SpendsCoinbase(bool _flag)
Definition: setup_common.h:224
TestChain100Setup
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
Definition: setup_common.h:123
MakeNoLogFileContext
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:189
uint256
256-bit opaque blob.
Definition: uint256.h:126
TestChain100Setup::TestChain100Setup
TestChain100Setup(const std::string &chain_name=CBaseChainParams::REGTEST, const std::vector< const char * > &extra_args={})
Definition: setup_common.cpp:245
CChainState
CChainState stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:436
TestChain100Setup::CreateAndProcessBlock
CBlock CreateAndProcessBlock(const std::vector< CMutableTransaction > &txns, const CScript &scriptPubKey, CChainState *chainstate=nullptr)
Create a new block with just given transactions, coinbase paying to scriptPubKey, and try to add it t...
Definition: setup_common.cpp:293
CScript
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:410
CBaseChainParams::MAIN
static const std::string MAIN
Chain name strings.
Definition: chainparamsbase.h:22
TestChain100Setup::PopulateMempool
std::vector< CTransactionRef > PopulateMempool(FastRandomContext &det_rand, size_t num_transactions, bool submit)
Create transactions spending from m_coinbase_txns.
Definition: setup_common.cpp:359
system.h
CBlock
Definition: block.h:62
TestMemPoolEntryHelper::lp
LockPoints lp
Definition: setup_common.h:211
key.h
TestMemPoolEntryHelper::Fee
TestMemPoolEntryHelper & Fee(CAmount _fee)
Definition: setup_common.h:221
CKey
An encapsulated private key.
Definition: key.h:26
RegTestingSetup::RegTestingSetup
RegTestingSetup()
Definition: setup_common.h:112
ArgsManager
Definition: system.h:167
CTxMemPoolEntry
Definition: txmempool.h:85
vector.h
TestChain100Setup::m_coinbase_txns
std::vector< CTransactionRef > m_coinbase_txns
Definition: setup_common.h:180
std
Definition: setup_common.h:33
LockPoints
Definition: txmempool.h:41
FastRandomContext::randrange
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
Definition: random.h:212
BasicTestingSetup::m_path_root
const fs::path m_path_root
Definition: setup_common.h:89
TestingSetup
Testing setup that configures a complete environment.
Definition: setup_common.h:106
TestChain100Setup::coinbaseKey
CKey coinbaseKey
Definition: setup_common.h:181
InsecureRandBits
static uint64_t InsecureRandBits(int bits)
Definition: setup_common.h:74
caches.h
HasReason::m_reason
const std::string m_reason
Definition: setup_common.h:245
TestMemPoolEntryHelper::FromTx
CTxMemPoolEntry FromTx(const CMutableTransaction &tx) const
Definition: setup_common.cpp:405
HasReason::HasReason
HasReason(const std::string &reason)
Definition: setup_common.h:241
COIN
static constexpr CAmount COIN
The amount of satoshis in one BTC.
Definition: amount.h:15
CMutableTransaction
A mutable version of CTransaction.
Definition: transaction.h:364
getBlock13b8a
CBlock getBlock13b8a()
Definition: setup_common.cpp:420
HasReason::operator()
bool operator()(const std::exception &e) const
Definition: setup_common.h:242
TestChain100Setup::mineBlocks
void mineBlocks(int num_blocks)
Mine a series of new blocks on the active chain.
Definition: setup_common.cpp:264
g_mock_deterministic_tests
bool g_mock_deterministic_tests
Flag to make GetRand in random.h return the same number.
Definition: random.cpp:585
TestMemPoolEntryHelper::Height
TestMemPoolEntryHelper & Height(unsigned int _height)
Definition: setup_common.h:223
FastRandomContext
Fast randomness source.
Definition: random.h:141
ChainTestingSetup
Testing setup that performs all steps up until right before ChainstateManager gets initialized.
Definition: setup_common.h:97
ctx
static secp256k1_context * ctx
Definition: tests.c:34
TestMemPoolEntryHelper::Time
TestMemPoolEntryHelper & Time(int64_t _time)
Definition: setup_common.h:222
Seed
void Seed(FastRandomContext &ctx)
Seed the given random ctx or use the seed passed in via an environment var.
Definition: setup_common.cpp:74