Bitcoin Core 28.99.0
P2P Digital Currency
Functions | Variables
random.cpp File Reference
#include <bitcoin-build-config.h>
#include <random.h>
#include <compat/compat.h>
#include <compat/cpuid.h>
#include <crypto/chacha20.h>
#include <crypto/sha256.h>
#include <crypto/sha512.h>
#include <logging.h>
#include <randomenv.h>
#include <span.h>
#include <support/allocators/secure.h>
#include <support/cleanse.h>
#include <sync.h>
#include <util/time.h>
#include <array>
#include <cmath>
#include <cstdlib>
#include <optional>
#include <thread>
#include <fcntl.h>
#include <sys/time.h>
Include dependency graph for random.cpp:

Go to the source code of this file.

Functions

void MakeRandDeterministicDANGEROUS (const uint256 &seed) noexcept
 Internal function to set g_determinstic_rng. More...
 
void GetRandBytes (Span< unsigned char > bytes) noexcept
 Generate random data via the internal PRNG. More...
 
void GetStrongRandBytes (Span< unsigned char > bytes) noexcept
 Gather entropy from various sources, feed it into the internal PRNG, and generate random data using it. More...
 
void RandAddPeriodic () noexcept
 Gather entropy from various expensive sources, and feed them to the PRNG state. More...
 
void RandAddEvent (const uint32_t event_info) noexcept
 Gathers entropy from the low bits of the time at which events occur. More...
 
bool Random_SanityCheck ()
 Check that OS randomness is available and returning the requested number of bytes. More...
 
void RandomInit ()
 Overall design of the RNG and entropy sources. More...
 
double MakeExponentiallyDistributed (uint64_t uniform) noexcept
 Given a uniformly random uint64_t, return an exponentially distributed double with mean 1. More...
 

Variables

std::atomic< bool > g_used_g_prng {false}
 
static constexpr std::array< std::byte, ChaCha20::KEYLENZERO_KEY {}
 

Function Documentation

◆ GetRandBytes()

void GetRandBytes ( Span< unsigned char >  bytes)
noexcept

Generate random data via the internal PRNG.

These functions are designed to be fast (sub microsecond), but do not necessarily meaningfully add entropy to the PRNG state.

In test mode (see SeedRandomForTest in src/test/util/random.h), the normal PRNG state is bypassed, and a deterministic, seeded, PRNG is used instead.

Thread-safe.

Definition at line 676 of file random.cpp.

Here is the caller graph for this function:

◆ GetStrongRandBytes()

void GetStrongRandBytes ( Span< unsigned char >  bytes)
noexcept

Gather entropy from various sources, feed it into the internal PRNG, and generate random data using it.

This function will cause failure whenever the OS RNG fails.

The normal PRNG is never bypassed here, even in test mode.

Thread-safe.

Definition at line 682 of file random.cpp.

Here is the caller graph for this function:

◆ MakeExponentiallyDistributed()

double MakeExponentiallyDistributed ( uint64_t  uniform)
noexcept

Given a uniformly random uint64_t, return an exponentially distributed double with mean 1.

Definition at line 779 of file random.cpp.

Here is the caller graph for this function:

◆ MakeRandDeterministicDANGEROUS()

void MakeRandDeterministicDANGEROUS ( const uint256 seed)
noexcept

Internal function to set g_determinstic_rng.

Only accessed from tests.

Definition at line 670 of file random.cpp.

Here is the caller graph for this function:

◆ RandAddEvent()

void RandAddEvent ( const uint32_t  event_info)
noexcept

Gathers entropy from the low bits of the time at which events occur.

Should be called with a uint32_t describing the event at the time an event occurs.

Thread-safe.

Definition at line 692 of file random.cpp.

Here is the caller graph for this function:

◆ RandAddPeriodic()

void RandAddPeriodic ( )
noexcept

Gather entropy from various expensive sources, and feed them to the PRNG state.

Thread-safe.

Definition at line 687 of file random.cpp.

Here is the caller graph for this function:

◆ Random_SanityCheck()

bool Random_SanityCheck ( )

Check that OS randomness is available and returning the requested number of bytes.

Definition at line 716 of file random.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ RandomInit()

void RandomInit ( )

Overall design of the RNG and entropy sources.

We maintain a single global 256-bit RNG state for all high-quality randomness. The following (classes of) functions interact with that state by mixing in new entropy, and optionally extracting random output from it:

  • GetRandBytes, GetRandHash, GetRandDur, as well as construction of FastRandomContext objects, perform 'fast' seeding, consisting of mixing in:
    • A stack pointer (indirectly committing to calling thread and call stack)
    • A high-precision timestamp (rdtsc when available, c++ high_resolution_clock otherwise)
    • 64 bits from the hardware RNG (rdrand) when available. These entropy sources are very fast, and only designed to protect against situations where a VM state restore/copy results in multiple systems with the same randomness. FastRandomContext on the other hand does not protect against this once created, but is even faster (and acceptable to use inside tight loops).
  • The GetStrongRandBytes() function performs 'slow' seeding, including everything that fast seeding includes, but additionally:
    • OS entropy (/dev/urandom, getrandom(), ...). The application will terminate if this entropy source fails.
    • Another high-precision timestamp (indirectly committing to a benchmark of all the previous sources). These entropy sources are slower, but designed to make sure the RNG state contains fresh data that is unpredictable to attackers.
  • RandAddPeriodic() seeds everything that fast seeding includes, but additionally:
    • A high-precision timestamp
    • Dynamic environment data (clocks, resource usage, ...)
    • Strengthen the entropy for 10 ms using repeated SHA512. This is run once every minute.
  • On first use of the RNG (regardless of what function is called first), all entropy sources used in the 'slow' seeder are included, but also:
    • 256 bits from the hardware RNG (rdseed or rdrand) when available.
    • Dynamic environment data (performance monitoring, ...)
    • Static environment data
    • Strengthen the entropy for 100 ms using repeated SHA512.

When mixing in new entropy, H = SHA512(entropy || old_rng_state) is computed, and (up to) the first 32 bytes of H are produced as output, while the last 32 bytes become the new RNG state.

During tests, the RNG can be put into a special deterministic mode, in which the output of all RNG functions, with the exception of GetStrongRandBytes(), is replaced with the output of a deterministic RNG. This deterministic RNG does not gather entropy, and is unaffected by RandAddPeriodic() or RandAddEvent(). It produces pseudorandom data that only depends on the seed it was initialized with, possibly until it is reinitialized. Initialize global RNG state and log any CPU features that are used.

Calling this function is optional. RNG state will be initialized when first needed if it is not called.

Definition at line 771 of file random.cpp.

Here is the caller graph for this function:

Variable Documentation

◆ g_used_g_prng

std::atomic<bool> g_used_g_prng {false}

Definition at line 674 of file random.cpp.

◆ ZERO_KEY

constexpr std::array<std::byte, ChaCha20::KEYLEN> ZERO_KEY {}
staticconstexpr

Definition at line 762 of file random.cpp.