Branch data Line data Source code
1 : : // Copyright (c) 2023 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_RANDOM_H
6 : : #define BITCOIN_TEST_UTIL_RANDOM_H
7 : :
8 : : #include <consensus/amount.h>
9 : : #include <random.h>
10 : : #include <uint256.h>
11 : :
12 : : #include <cstdint>
13 : :
14 : : /**
15 : : * This global and the helpers that use it are not thread-safe.
16 : : *
17 : : * If thread-safety is needed, a per-thread instance could be
18 : : * used in the multi-threaded test.
19 : : */
20 : : extern FastRandomContext g_insecure_rand_ctx;
21 : :
22 : : enum class SeedRand {
23 : : ZEROS, //!< Seed with a compile time constant of zeros
24 : : SEED, //!< Use (and report) random seed from environment, or a (truly) random one.
25 : : };
26 : :
27 : : /** Seed the RNG for testing. This affects all randomness, except GetStrongRandBytes(). */
28 : : void SeedRandomForTest(SeedRand seed = SeedRand::SEED);
29 : :
30 : 16463265 : static inline uint32_t InsecureRand32()
31 : : {
32 [ + + ][ + - : 16547625 : return g_insecure_rand_ctx.rand32();
+ - # # ]
[ + + + +
+ - ]
33 : : }
34 : :
35 : 1249760 : static inline uint256 InsecureRand256()
36 : : {
37 : 1249756 : return g_insecure_rand_ctx.rand256();
38 : : }
39 : :
40 : 3349513 : static inline uint64_t InsecureRandBits(int bits)
41 : : {
42 : 3269513 : return g_insecure_rand_ctx.randbits(bits);
43 : : }
44 : :
45 : 5987499 : static inline uint64_t InsecureRandRange(uint64_t range)
46 : : {
47 : 5839079 : return g_insecure_rand_ctx.randrange(range);
48 : : }
49 : :
50 : 557301 : static inline bool InsecureRandBool()
51 : : {
52 [ + + + + : 558878 : return g_insecure_rand_ctx.randbool();
# # # # #
# # # #
# ][ + + +
+ + + + +
+ + + + +
+ ][ + + #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # #
# ][ + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + +
+ ]
53 : : }
54 : :
55 : 174305 : static inline CAmount InsecureRandMoneyAmount()
56 : : {
57 : 174305 : return static_cast<CAmount>(InsecureRandRange(MAX_MONEY + 1));
58 : : }
59 : :
60 : : #endif // BITCOIN_TEST_UTIL_RANDOM_H
|