Bitcoin Core
27.99.0
P2P Digital Currency
src
test
util
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
14
FastRandomContext
g_insecure_rand_ctx
;
15
16
extern
void
MakeRandDeterministicDANGEROUS
(
const
uint256
& seed) noexcept;
17
18
void
SeedRandomForTest
(
SeedRand
seedtype)
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());
36
MakeRandDeterministicDANGEROUS
(seed);
37
g_insecure_rand_ctx
.
Reseed
(
GetRandHash
());
38
}
FastRandomContext
Fast randomness source.
Definition:
random.h:377
FastRandomContext::Reseed
void Reseed(const uint256 &seed) noexcept
Reseed with explicit seed (only for testing).
Definition:
random.cpp:707
uint256
256-bit opaque blob.
Definition:
uint256.h:127
uint256::ZERO
static const uint256 ZERO
Definition:
uint256.h:133
LogPrintf
#define LogPrintf(...)
Definition:
logging.h:274
MakeRandDeterministicDANGEROUS
void MakeRandDeterministicDANGEROUS(const uint256 &seed) noexcept
Internal function to set g_determinstic_rng.
Definition:
random.cpp:670
GetRandHash
uint256 GetRandHash() noexcept
Generate a random uint256.
Definition:
random.h:454
logging.h
g_insecure_rand_ctx
FastRandomContext g_insecure_rand_ctx
This global and the helpers that use it are not thread-safe.
Definition:
random.cpp:14
SeedRandomForTest
void SeedRandomForTest(SeedRand seedtype)
Seed the RNG for testing.
Definition:
random.cpp:18
random.h
SeedRand
SeedRand
Definition:
random.h:22
SeedRand::SEED
@ SEED
Use (and report) random seed from environment, or a (truly) random one.
uint256.h
uint256S
uint256 uint256S(std::string_view str)
Definition:
uint256.h:140
Generated on Sat Jul 27 2024 02:44:41 for Bitcoin Core by
1.9.1