Bitcoin Core  22.99.0
P2P Digital Currency
setup_common.h
Go to the documentation of this file.
1 // Copyright (c) 2015-2020 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/context.h>
13 #include <pubkey.h>
14 #include <random.h>
15 #include <stdexcept>
16 #include <txmempool.h>
17 #include <util/check.h>
18 #include <util/string.h>
19 #include <util/vector.h>
20 
21 #include <type_traits>
22 #include <vector>
23 
25 extern const std::function<void(const std::string&)> G_TEST_LOG_FUN;
26 
27 // Enable BOOST_CHECK_EQUAL for enum class types
28 template <typename T>
29 std::ostream& operator<<(typename std::enable_if<std::is_enum<T>::value, std::ostream>::type& stream, const T& e)
30 {
31  return stream << static_cast<typename std::underlying_type<T>::type>(e);
32 }
33 
42 
46 extern bool g_mock_deterministic_tests;
47 
48 enum class SeedRand {
49  ZEROS,
50  SEED,
51 };
52 
55 
56 static inline void SeedInsecureRand(SeedRand seed = SeedRand::SEED)
57 {
58  if (seed == SeedRand::ZEROS) {
59  g_insecure_rand_ctx = FastRandomContext(/* deterministic */ true);
60  } else {
62  }
63 }
64 
65 static inline uint32_t InsecureRand32() { return g_insecure_rand_ctx.rand32(); }
66 static inline uint256 InsecureRand256() { return g_insecure_rand_ctx.rand256(); }
67 static inline uint64_t InsecureRandBits(int bits) { return g_insecure_rand_ctx.randbits(bits); }
68 static inline uint64_t InsecureRandRange(uint64_t range) { return g_insecure_rand_ctx.randrange(range); }
69 static inline bool InsecureRandBool() { return g_insecure_rand_ctx.randbool(); }
70 
71 static constexpr CAmount CENT{1000000};
72 
79 
80  explicit BasicTestingSetup(const std::string& chainName = CBaseChainParams::MAIN, const std::vector<const char*>& extra_args = {});
82 
83  const fs::path m_path_root;
85 };
86 
92 
93  explicit ChainTestingSetup(const std::string& chainName = CBaseChainParams::MAIN, const std::vector<const char*>& extra_args = {});
95 };
96 
100  explicit TestingSetup(const std::string& chainName = CBaseChainParams::MAIN, const std::vector<const char*>& extra_args = {});
101 };
102 
104 struct RegTestingSetup : public TestingSetup {
107 };
108 
109 class CBlock;
110 struct CMutableTransaction;
111 class CScript;
112 
117  TestChain100Setup(const std::vector<const char*>& extra_args = {});
118 
124  CBlock CreateAndProcessBlock(const std::vector<CMutableTransaction>& txns,
125  const CScript& scriptPubKey,
126  CChainState* chainstate = nullptr);
127 
133  const std::vector<CMutableTransaction>& txns,
134  const CScript& scriptPubKey,
135  CChainState& chainstate);
136 
138  void mineBlocks(int num_blocks);
139 
152  int input_vout,
153  int input_height,
154  CKey input_signing_key,
155  CScript output_destination,
156  CAmount output_amount = CAmount(1 * COIN),
157  bool submit = true);
158 
159  std::vector<CTransactionRef> m_coinbase_txns; // For convenience, coinbase transactions
160  CKey coinbaseKey; // private/public key needed to spend coinbase transactions
161 };
162 
167 template <class T = const BasicTestingSetup>
168 std::unique_ptr<T> MakeNoLogFileContext(const std::string& chain_name = CBaseChainParams::REGTEST, const std::vector<const char*>& extra_args = {})
169 {
170  const std::vector<const char*> arguments = Cat(
171  {
172  "-nodebuglogfile",
173  "-nodebug",
174  },
175  extra_args);
176 
177  return std::make_unique<T>(chain_name, arguments);
178 }
179 
180 class CTxMemPoolEntry;
181 
183 {
184  // Default values
186  int64_t nTime;
187  unsigned int nHeight;
189  unsigned int sigOpCost;
191 
193  nFee(0), nTime(0), nHeight(1),
194  spendsCoinbase(false), sigOpCost(4) { }
195 
196  CTxMemPoolEntry FromTx(const CMutableTransaction& tx) const;
197  CTxMemPoolEntry FromTx(const CTransactionRef& tx) const;
198 
199  // Change the default value
200  TestMemPoolEntryHelper &Fee(CAmount _fee) { nFee = _fee; return *this; }
201  TestMemPoolEntryHelper &Time(int64_t _time) { nTime = _time; return *this; }
202  TestMemPoolEntryHelper &Height(unsigned int _height) { nHeight = _height; return *this; }
203  TestMemPoolEntryHelper &SpendsCoinbase(bool _flag) { spendsCoinbase = _flag; return *this; }
204  TestMemPoolEntryHelper &SigOpsCost(unsigned int _sigopsCost) { sigOpCost = _sigopsCost; return *this; }
205 };
206 
208 
209 // define an implicit conversion here so that uint256 may be used directly in BOOST_CHECK_*
210 std::ostream& operator<<(std::ostream& os, const uint256& num);
211 
218 {
219 public:
220  explicit HasReason(const std::string& reason) : m_reason(reason) {}
221  bool operator()(const std::exception& e) const
222  {
223  return std::string(e.what()).find(m_reason) != std::string::npos;
224  };
225 
226 private:
227  const std::string m_reason;
228 };
229 
230 #endif
SeedRand
SeedRand
Definition: setup_common.h:48
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:238
HasReason
BOOST_CHECK_EXCEPTION predicates to check the specific validation error.
Definition: setup_common.h:217
RegTestingSetup
Identical to TestingSetup, but chain set to regtest.
Definition: setup_common.h:104
G_TEST_LOG_FUN
const std::function< void(const std::string &)> G_TEST_LOG_FUN
This is connected to the logger.
Definition: bench.cpp:20
TestMemPoolEntryHelper
Definition: setup_common.h:182
FastRandomContext::rand256
uint256 rand256() noexcept
generate a random uint256.
Definition: random.cpp:615
operator<<
std::ostream & operator<<(typename std::enable_if< std::is_enum< T >::value, std::ostream >::type &stream, const T &e)
Definition: setup_common.h:29
check.h
InsecureRandBool
static bool InsecureRandBool()
Definition: setup_common.h:69
BasicTestingSetup::globalVerifyHandle
ECCVerifyHandle globalVerifyHandle
Definition: setup_common.h:77
TestMemPoolEntryHelper::nHeight
unsigned int nHeight
Definition: setup_common.h:187
SeedInsecureRand
static void SeedInsecureRand(SeedRand seed=SeedRand::SEED)
Definition: setup_common.h:56
fs.h
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:276
TestingSetup::TestingSetup
TestingSetup(const std::string &chainName=CBaseChainParams::MAIN, const std::vector< const char * > &extra_args={})
Definition: setup_common.cpp:172
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:189
FastRandomContext::randbool
bool randbool() noexcept
Generate a random boolean.
Definition: random.h:211
ChainTestingSetup::ChainTestingSetup
ChainTestingSetup(const std::string &chainName=CBaseChainParams::MAIN, const std::vector< const char * > &extra_args={})
Definition: setup_common.cpp:134
chainparamsbase.h
BasicTestingSetup::BasicTestingSetup
BasicTestingSetup(const std::string &chainName=CBaseChainParams::MAIN, const std::vector< const char * > &extra_args={})
Definition: setup_common.cpp:75
InsecureRand256
static uint256 InsecureRand256()
Definition: setup_common.h:66
InsecureRandRange
static uint64_t InsecureRandRange(uint64_t range)
Definition: setup_common.h:68
BasicTestingSetup::~BasicTestingSetup
~BasicTestingSetup()
Definition: setup_common.cpp:125
TestMemPoolEntryHelper::nTime
int64_t nTime
Definition: setup_common.h:186
TestMemPoolEntryHelper::SigOpsCost
TestMemPoolEntryHelper & SigOpsCost(unsigned int _sigopsCost)
Definition: setup_common.h:204
InsecureRand32
static uint32_t InsecureRand32()
Definition: setup_common.h:65
ChainTestingSetup::~ChainTestingSetup
~ChainTestingSetup()
Definition: setup_common.cpp:155
pubkey.h
CTransactionRef
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:386
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:172
txmempool.h
TestMemPoolEntryHelper::spendsCoinbase
bool spendsCoinbase
Definition: setup_common.h:188
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:46
random.h
TestMemPoolEntryHelper::TestMemPoolEntryHelper
TestMemPoolEntryHelper()
Definition: setup_common.h:192
FastRandomContext::rand32
uint32_t rand32() noexcept
Generate a random 32-bit integer.
Definition: random.h:205
CBaseChainParams::REGTEST
static const std::string REGTEST
Definition: chainparamsbase.h:25
BasicTestingSetup::m_args
ArgsManager m_args
Definition: setup_common.h:84
CENT
static constexpr CAmount CENT
Definition: setup_common.h:71
TestMemPoolEntryHelper::nFee
CAmount nFee
Definition: setup_common.h:185
CAmount
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
BasicTestingSetup
Basic testing setup.
Definition: setup_common.h:76
TestMemPoolEntryHelper::SpendsCoinbase
TestMemPoolEntryHelper & SpendsCoinbase(bool _flag)
Definition: setup_common.h:203
TestChain100Setup
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
Definition: setup_common.h:116
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:168
uint256
256-bit opaque blob.
Definition: uint256.h:124
CChainState
CChainState stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:546
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:258
CScript
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:405
CBaseChainParams::MAIN
static const std::string MAIN
Chain name strings.
Definition: chainparamsbase.h:22
TestChain100Setup::TestChain100Setup
TestChain100Setup(const std::vector< const char * > &extra_args={})
Definition: setup_common.cpp:208
system.h
CBlock
Definition: block.h:62
TestMemPoolEntryHelper::lp
LockPoints lp
Definition: setup_common.h:190
key.h
BasicTestingSetup::m_node
NodeContext m_node
Definition: setup_common.h:78
ECCVerifyHandle
Users of this module must hold an ECCVerifyHandle.
Definition: pubkey.h:315
TestMemPoolEntryHelper::Fee
TestMemPoolEntryHelper & Fee(CAmount _fee)
Definition: setup_common.h:200
CKey
An encapsulated private key.
Definition: key.h:26
RegTestingSetup::RegTestingSetup
RegTestingSetup()
Definition: setup_common.h:105
ArgsManager
Definition: system.h:158
CTxMemPoolEntry
Definition: txmempool.h:79
vector.h
TestChain100Setup::m_coinbase_txns
std::vector< CTransactionRef > m_coinbase_txns
Definition: setup_common.h:159
LockPoints
Definition: txmempool.h:40
FastRandomContext::randrange
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
Definition: random.h:190
BasicTestingSetup::m_path_root
const fs::path m_path_root
Definition: setup_common.h:83
TestingSetup
Testing setup that configures a complete environment.
Definition: setup_common.h:99
TestChain100Setup::coinbaseKey
CKey coinbaseKey
Definition: setup_common.h:160
COIN
static const CAmount COIN
Definition: amount.h:14
InsecureRandBits
static uint64_t InsecureRandBits(int bits)
Definition: setup_common.h:67
HasReason::m_reason
const std::string m_reason
Definition: setup_common.h:224
TestMemPoolEntryHelper::FromTx
CTxMemPoolEntry FromTx(const CMutableTransaction &tx) const
Definition: setup_common.cpp:325
HasReason::HasReason
HasReason(const std::string &reason)
Definition: setup_common.h:220
CMutableTransaction
A mutable version of CTransaction.
Definition: transaction.h:344
NodeContext
NodeContext struct containing references to chain state and connection state.
Definition: context.h:39
getBlock13b8a
CBlock getBlock13b8a()
Definition: setup_common.cpp:340
T
#define T(expected, seed, data)
HasReason::operator()
bool operator()(const std::exception &e) const
Definition: setup_common.h:221
TestChain100Setup::mineBlocks
void mineBlocks(int num_blocks)
Mine a series of new blocks on the active chain.
Definition: setup_common.cpp:227
g_mock_deterministic_tests
bool g_mock_deterministic_tests
Flag to make GetRand in random.h return the same number.
Definition: random.cpp:589
TestMemPoolEntryHelper::Height
TestMemPoolEntryHelper & Height(unsigned int _height)
Definition: setup_common.h:202
FastRandomContext
Fast randomness source.
Definition: random.h:119
ChainTestingSetup
Testing setup that performs all steps up until right before ChainstateManager gets initialized.
Definition: setup_common.h:91
ctx
static secp256k1_context * ctx
Definition: tests.c:42
TestMemPoolEntryHelper::Time
TestMemPoolEntryHelper & Time(int64_t _time)
Definition: setup_common.h:201
Seed
void Seed(FastRandomContext &ctx)
Seed the given random ctx or use the seed passed in via an environment var.
Definition: setup_common.cpp:58