Bitcoin Core  24.99.0
P2P Digital Currency
Classes | Functions | Variables
random.h File Reference
#include <crypto/chacha20.h>
#include <crypto/common.h>
#include <span.h>
#include <uint256.h>
#include <cassert>
#include <chrono>
#include <cstdint>
#include <limits>
Include dependency graph for random.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Classes

class  FastRandomContext
 Fast randomness source. More...
 

Functions

void GetRandBytes (Span< unsigned char > bytes) noexcept
 Overall design of the RNG and entropy sources. More...
 
uint64_t GetRandInternal (uint64_t nMax) noexcept
 Generate a uniform random integer in the range [0..range). More...
 
template<typename T >
GetRand (T nMax=std::numeric_limits< T >::max()) noexcept
 Generate a uniform random integer of type T in the range [0..nMax) nMax defaults to std::numeric_limits<T>::max() Precondition: nMax > 0, T is an integral type, no larger than uint64_t. More...
 
template<typename D >
GetRandomDuration (typename std::common_type< D >::type max) noexcept
 Generate a uniform random duration in the range [0..max). More...
 
std::chrono::microseconds GetExponentialRand (std::chrono::microseconds now, std::chrono::seconds average_interval)
 Return a timestamp in the future sampled from an exponential distribution (https://en.wikipedia.org/wiki/Exponential_distribution). More...
 
uint256 GetRandHash () noexcept
 
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...
 
template<typename I , typename R >
void Shuffle (I first, I last, R &&rng)
 More efficient than using std::shuffle on a FastRandomContext. More...
 
void GetOSRand (unsigned char *ent32)
 Get 32 bytes of system entropy. More...
 
bool Random_SanityCheck ()
 Check that OS randomness is available and returning the requested number of bytes. More...
 
void RandomInit ()
 Initialize global RNG state and log any CPU features that are used. More...
 

Variables

constexpr auto GetRandMicros = GetRandomDuration<std::chrono::microseconds>
 
constexpr auto GetRandMillis = GetRandomDuration<std::chrono::milliseconds>
 
static const int NUM_OS_RANDOM_BYTES = 32
 

Function Documentation

◆ GetExponentialRand()

std::chrono::microseconds GetExponentialRand ( std::chrono::microseconds  now,
std::chrono::seconds  average_interval 
)

Return a timestamp in the future sampled from an exponential distribution (https://en.wikipedia.org/wiki/Exponential_distribution).

This distribution is memoryless and should be used for repeated network events (e.g. sending a certain type of message) to minimize leaking information to observers.

The probability of an event occurring before time x is 1 - e^-(x/a) where a is the average interval between events.

Definition at line 709 of file random.cpp.

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

◆ GetOSRand()

void GetOSRand ( unsigned char *  ent32)

Get 32 bytes of system entropy.

Do not use this in application code: use GetStrongRandBytes instead.

Definition at line 276 of file random.cpp.

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

◆ GetRand()

template<typename T >
T GetRand ( nMax = std::numeric_limits<T>::max())
noexcept

Generate a uniform random integer of type T in the range [0..nMax) nMax defaults to std::numeric_limits<T>::max() Precondition: nMax > 0, T is an integral type, no larger than uint64_t.

Definition at line 79 of file random.h.

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

◆ GetRandBytes()

void GetRandBytes ( Span< unsigned char >  bytes)
noexcept

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:

  • The GetRand*() class of functions, 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 GetStrongRand*() class of function perform '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 (performance monitoring, ...)
    • 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. 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.

Thread-safe.

Definition at line 580 of file random.cpp.

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

◆ GetRandHash()

uint256 GetRandHash ( )
noexcept

Definition at line 592 of file random.cpp.

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

◆ GetRandInternal()

uint64_t GetRandInternal ( uint64_t  nMax)
noexcept

Generate a uniform random integer in the range [0..range).

Precondition: range > 0

Definition at line 587 of file random.cpp.

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

◆ GetRandomDuration()

template<typename D >
D GetRandomDuration ( typename std::common_type< D >::type  max)
noexcept

Generate a uniform random duration in the range [0..max).

Precondition: max.count() > 0

Definition at line 86 of file random.h.

Here is the call 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.

Thread-safe.

Definition at line 581 of file random.cpp.

Here is the call graph for this function:
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 583 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 582 of file random.cpp.

Here is the call graph for this function:
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 632 of file random.cpp.

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

◆ RandomInit()

void RandomInit ( )

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 701 of file random.cpp.

◆ Shuffle()

template<typename I , typename R >
void Shuffle ( first,
last,
R &&  rng 
)

More efficient than using std::shuffle on a FastRandomContext.

This is more efficient as std::shuffle will consume entropy in groups of 64 bits at the time and throw away most.

This also works around a bug in libstdc++ std::shuffle that may cause type::operator=(type&&) to be invoked on itself, which the library's debug mode detects and panics on. This is a known issue, see https://stackoverflow.com/questions/22915325/avoiding-self-assignment-in-stdshuffle

Definition at line 271 of file random.h.

Here is the caller graph for this function:

Variable Documentation

◆ GetRandMicros

constexpr auto GetRandMicros = GetRandomDuration<std::chrono::microseconds>
constexpr

Definition at line 95 of file random.h.

◆ GetRandMillis

constexpr auto GetRandMillis = GetRandomDuration<std::chrono::milliseconds>
constexpr

Definition at line 96 of file random.h.

◆ NUM_OS_RANDOM_BYTES

const int NUM_OS_RANDOM_BYTES = 32
static

Definition at line 288 of file random.h.