Skip to content

Commit

Permalink
test: Only accept a fully valid RANDOM_CTX_SEED
Browse files Browse the repository at this point in the history
This rejects if the seed is corrupt, truncated, too-long, or otherwise
contains non-hex.

For example, "RANDOM_CTX_SEED=z".

Can be tested with:

$ RANDOM_CTX_SEED=z ./src/test/test_bitcoin --log_level=all --run_test=timeoffsets_tests/timeoffsets_warning -- -printtoconsole=1 | grep RANDOM_CTX_SEED
test/util/random.cpp:29 operator(): Assertion `uint256::FromHex(num)' failed.

Co-authored-by: stickies-v <stickies-v@protonmail.com>
  • Loading branch information
MarcoFalke and stickies-v committed Aug 8, 2024
1 parent 1965076 commit 855784d
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions src/test/util/random.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,32 +7,39 @@
#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;

void SeedRandomForTest(SeedRand seedtype)
{
static const std::string RANDOM_CTX_SEED{"RANDOM_CTX_SEED"};
constexpr auto 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)}) {
if (auto num_parsed{uint256::FromHex(num)}) {
return *num_parsed;
} else {
std::cerr << RANDOM_CTX_SEED << " must be a " << uint256::size() * 2 << " char hex string without '0x'-prefix, was set to: '" << num << "'.\n";
std::abort();
}
}
// Otherwise use a (truly) random value.
return GetRandHash();
}();

const uint256& seed{seedtype == SeedRand::SEED ? ctx_seed : uint256::ZERO};
LogPrintf("%s: Setting random seed for current tests to %s=%s\n", __func__, RANDOM_CTX_SEED, seed.GetHex());
LogInfo("Setting random seed for current tests to %s=%s\n", RANDOM_CTX_SEED, seed.GetHex());
MakeRandDeterministicDANGEROUS(seed);
g_insecure_rand_ctx.Reseed(GetRandHash());
}

0 comments on commit 855784d

Please sign in to comment.