Skip to content

Commit

Permalink
random: use uint256::FromHex for RANDOM_CTX_SEED
Browse files Browse the repository at this point in the history
Removes dependency on unsafe and deprecated uint256S.

This makes parsing more strict, by requiring RANDOM_CTX_SEED
to be a 64 char hex string, whereas previously any string would
be accepted, with non-hex characters silently ignored and strings
longer than 64 characters silently trimmed.

Additionally, and unrelatedly, make RANDOM_CTX_SEED inline constexpr
  • Loading branch information
stickies-v committed Aug 7, 2024
1 parent 31a3cd2 commit d045fc7
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions src/test/util/random.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,27 @@
#include <logging.h>
#include <random.h>
#include <uint256.h>
#include <util/check.h>

#include <cstdlib>
#include <string>

FastRandomContext g_insecure_rand_ctx;

inline constexpr const char* RANDOM_CTX_SEED{"RANDOM_CTX_SEED"};

extern void MakeRandDeterministicDANGEROUS(const uint256& seed) noexcept;

void SeedRandomForTest(SeedRand seedtype)
{
static const std::string RANDOM_CTX_SEED{"RANDOM_CTX_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.
const char* num = std::getenv(RANDOM_CTX_SEED.c_str());
if (num) return uint256S(num);
if (const char* num{std::getenv(RANDOM_CTX_SEED)}) {
return *Assert(uint256::FromHex(num)); // RANDOM_CTX_SEED must be a 64 char hex string
}
// Otherwise use a (truly) random value.
return GetRandHash();
}();
Expand Down

0 comments on commit d045fc7

Please sign in to comment.