Bitcoin Core  27.99.0
P2P Digital Currency
random.cpp
Go to the documentation of this file.
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 #include <test/util/random.h>
6 
7 #include <logging.h>
8 #include <random.h>
9 #include <uint256.h>
10 
11 #include <cstdlib>
12 #include <string>
13 
15 
17 static uint256 GetUintFromEnv(const std::string& env_name)
18 {
19  const char* num = std::getenv(env_name.c_str());
20  if (!num) return {};
21  return uint256S(num);
22 }
23 
25 {
26  // Should be enough to get the seed once for the process
27  static uint256 seed{};
28  static const std::string RANDOM_CTX_SEED{"RANDOM_CTX_SEED"};
29  if (seed.IsNull()) seed = GetUintFromEnv(RANDOM_CTX_SEED);
30  if (seed.IsNull()) seed = GetRandHash();
31  LogPrintf("%s: Setting random seed for current tests to %s=%s\n", __func__, RANDOM_CTX_SEED, seed.GetHex());
32  ctx = FastRandomContext(seed);
33 }
Fast randomness source.
Definition: random.h:145
256-bit opaque blob.
Definition: uint256.h:106
#define LogPrintf(...)
Definition: logging.h:244
uint256 GetRandHash() noexcept
Definition: random.cpp:650
void Seed(FastRandomContext &ctx)
Seed the given random ctx or use the seed passed in via an environment var.
Definition: random.cpp:24
static uint256 GetUintFromEnv(const std::string &env_name)
Return the unsigned from the environment var if available, otherwise 0.
Definition: random.cpp:17
FastRandomContext g_insecure_rand_ctx
This global and the helpers that use it are not thread-safe.
Definition: random.cpp:14
uint256 uint256S(const char *str)
Definition: uint256.h:119