diff options
Diffstat (limited to 'src/test/util/random.cpp')
-rw-r--r-- | src/test/util/random.cpp | 43 |
1 files changed, 26 insertions, 17 deletions
diff --git a/src/test/util/random.cpp b/src/test/util/random.cpp index 4c87ab8df8..32d785e45d 100644 --- a/src/test/util/random.cpp +++ b/src/test/util/random.cpp @@ -7,27 +7,36 @@ #include <logging.h> #include <random.h> #include <uint256.h> +#include <util/check.h> #include <cstdlib> -#include <string> +#include <iostream> -FastRandomContext g_insecure_rand_ctx; +extern void MakeRandDeterministicDANGEROUS(const uint256& seed) noexcept; -/** Return the unsigned from the environment var if available, otherwise 0 */ -static uint256 GetUintFromEnv(const std::string& env_name) +void SeedRandomStateForTest(SeedRand seedtype) { - const char* num = std::getenv(env_name.c_str()); - if (!num) return {}; - return uint256S(num); -} + constexpr auto RANDOM_CTX_SEED{"RANDOM_CTX_SEED"}; -void Seed(FastRandomContext& ctx) -{ - // Should be enough to get the seed once for the process - static uint256 seed{}; - static const std::string RANDOM_CTX_SEED{"RANDOM_CTX_SEED"}; - if (seed.IsNull()) seed = GetUintFromEnv(RANDOM_CTX_SEED); - if (seed.IsNull()) seed = GetRandHash(); - LogPrintf("%s: Setting random seed for current tests to %s=%s\n", __func__, RANDOM_CTX_SEED, seed.GetHex()); - ctx = FastRandomContext(seed); + // Do this once, on the first call, regardless of seedtype, because once + // MakeRandDeterministicDANGEROUS is called, the output of GetRandHash is + // no longer truly random. It should be enough to get the seed once for the + // process. + static const uint256 ctx_seed = []() { + // If RANDOM_CTX_SEED is set, use that as seed. + if (const char* num{std::getenv(RANDOM_CTX_SEED)}) { + if (auto num_parsed{uint256::FromUserHex(num)}) { + return *num_parsed; + } else { + std::cerr << RANDOM_CTX_SEED << " must consist of up to " << uint256::size() * 2 << " hex digits (\"0x\" prefix allowed), it was set to: '" << num << "'.\n"; + std::abort(); + } + } + // Otherwise use a (truly) random value. + return GetRandHash(); + }(); + + const uint256& seed{seedtype == SeedRand::FIXED_SEED ? ctx_seed : uint256::ZERO}; + LogInfo("Setting random seed for current tests to %s=%s\n", RANDOM_CTX_SEED, seed.GetHex()); + MakeRandDeterministicDANGEROUS(seed); } |