Bitcoin Core 28.0.0
P2P Digital Currency
Loading...
Searching...
No Matches
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
16extern void MakeRandDeterministicDANGEROUS(const uint256& seed) noexcept;
17
19{
20 static const std::string RANDOM_CTX_SEED{"RANDOM_CTX_SEED"};
21
22 // Do this once, on the first call, regardless of seedtype, because once
23 // MakeRandDeterministicDANGEROUS is called, the output of GetRandHash is
24 // no longer truly random. It should be enough to get the seed once for the
25 // process.
26 static const uint256 ctx_seed = []() {
27 // If RANDOM_CTX_SEED is set, use that as seed.
28 const char* num = std::getenv(RANDOM_CTX_SEED.c_str());
29 if (num) return uint256S(num);
30 // Otherwise use a (truly) random value.
31 return GetRandHash();
32 }();
33
34 const uint256& seed{seedtype == SeedRand::SEED ? ctx_seed : uint256::ZERO};
35 LogPrintf("%s: Setting random seed for current tests to %s=%s\n", __func__, RANDOM_CTX_SEED, seed.GetHex());
38}
Fast randomness source.
Definition random.h:377
void Reseed(const uint256 &seed) noexcept
Reseed with explicit seed (only for testing).
Definition random.cpp:707
256-bit opaque blob.
Definition uint256.h:178
static const uint256 ZERO
Definition uint256.h:185
#define LogPrintf(...)
Definition logging.h:274
uint256 GetRandHash() noexcept
Generate a random uint256.
Definition random.h:454
void MakeRandDeterministicDANGEROUS(const uint256 &seed) noexcept
Internal function to set g_determinstic_rng.
Definition random.cpp:670
FastRandomContext g_insecure_rand_ctx
This global and the helpers that use it are not thread-safe.
Definition random.cpp:14
void SeedRandomForTest(SeedRand seedtype)
Seed the RNG for testing.
Definition random.cpp:18
SeedRand
Definition random.h:22
@ SEED
Use (and report) random seed from environment, or a (truly) random one.
uint256 uint256S(std::string_view str)
Definition uint256.h:192