Bitcoin ABC 0.30.5
P2P Digital Currency
Enumerations | Functions | Variables
random.cpp File Reference
#include <random.h>
#include <compat/cpuid.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 <cmath>
#include <cstdlib>
#include <memory>
#include <thread>
#include <fcntl.h>
#include <sys/time.h>
Include dependency graph for random.cpp:

Go to the source code of this file.

Enumerations

enum class  RNGLevel { FAST , SLOW , PERIODIC }
 

Functions

static void RandFailure ()
 
static int64_t GetPerformanceCounter () noexcept
 
static void InitHardwareRand ()
 Access to other hardware random number generators could be added here later, assuming it is sufficiently fast (in the order of a few hundred CPU cycles). More...
 
static void ReportHardwareRand ()
 
static void SeedHardwareFast (CSHA512 &hasher) noexcept
 Add 64 bits of entropy gathered from hardware to hasher. More...
 
static void SeedHardwareSlow (CSHA512 &hasher) noexcept
 Add 256 bits of entropy gathered from hardware to hasher. More...
 
static void Strengthen (const uint8_t(&seed)[32], int microseconds, CSHA512 &hasher) noexcept
 Use repeated SHA512 to strengthen the randomness in seed32, and feed into hasher. More...
 
static void GetDevURandom (uint8_t *ent32)
 Fallback: get 32 bytes of system entropy from /dev/urandom. More...
 
void GetOSRand (uint8_t *ent32)
 Get 32 bytes of system entropy. More...
 
static void SeedTimestamp (CSHA512 &hasher) noexcept
 A note on the use of noexcept in the seeding functions below: More...
 
static void SeedFast (CSHA512 &hasher) noexcept
 
static void SeedSlow (CSHA512 &hasher, RNGState &rng) noexcept
 
static void SeedStrengthen (CSHA512 &hasher, RNGState &rng, int microseconds) noexcept
 Extract entropy from rng, strengthen it, and feed it into hasher. More...
 
static void SeedPeriodic (CSHA512 &hasher, RNGState &rng) noexcept
 
static void SeedStartup (CSHA512 &hasher, RNGState &rng) noexcept
 
static void ProcRand (uint8_t *out, int num, RNGLevel level) noexcept
 
void GetRandBytes (Span< uint8_t > bytes) noexcept
 Overall design of the RNG and entropy sources. More...
 
void GetStrongRandBytes (Span< uint8_t > 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...
 
uint64_t GetRandInternal (uint64_t nMax) noexcept
 Generate a uniform random integer in the range [0..range). More...
 
uint256 GetRandHash () noexcept
 
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...
 
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...
 

Variables

bool g_mock_deterministic_tests {false}
 

Enumeration Type Documentation

◆ RNGLevel

enum class RNGLevel
strong
Enumerator
FAST 

Automatically called by GetRandBytes.

SLOW 

Automatically called by GetStrongRandBytes.

PERIODIC 

Called by RandAddPeriodic()

Definition at line 604 of file random.cpp.

Function Documentation

◆ GetDevURandom()

static void GetDevURandom ( uint8_t *  ent32)
static

Fallback: get 32 bytes of system entropy from /dev/urandom.

The most compatible way to get cryptographic randomness on UNIX-ish platforms.

Definition at line 300 of file random.cpp.

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

◆ 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 occuring before time x is 1 - e^-(x/a) where a is the average interval between events.

Definition at line 794 of file random.cpp.

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

◆ GetOSRand()

void GetOSRand ( uint8_t *  ent32)

Get 32 bytes of system entropy.

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

Fall back to /dev/urandom if there is no specific method implemented to get system entropy for this OS.

Definition at line 319 of file random.cpp.

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

◆ GetPerformanceCounter()

static int64_t GetPerformanceCounter ( )
inlinestaticnoexcept

Definition at line 53 of file random.cpp.

Here is the caller graph for this function:

◆ GetRandBytes()

void GetRandBytes ( Span< uint8_t >  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 639 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 659 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 655 of file random.cpp.

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

◆ GetStrongRandBytes()

void GetStrongRandBytes ( Span< uint8_t >  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 642 of file random.cpp.

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

◆ InitHardwareRand()

static void InitHardwareRand ( )
static

Access to other hardware random number generators could be added here later, assuming it is sufficiently fast (in the order of a few hundred CPU cycles).

Slower sources should probably be invoked separately, and/or only from RandAddPeriodic (which is called once a minute).

Definition at line 216 of file random.cpp.

◆ ProcRand()

static void ProcRand ( uint8_t *  out,
int  num,
RNGLevel  level 
)
staticnoexcept

Definition at line 610 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 649 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 645 of file random.cpp.

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

◆ RandFailure()

static void RandFailure ( )
static

Definition at line 48 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.

This does not measure the quality of randomness, but it does test that GetOSRand() overwrites all 32 bytes of the output given a maximum number of tries.

Loop until all bytes have been overwritten at least once, or max number tries reached.

Definition at line 706 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 786 of file random.cpp.

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

◆ ReportHardwareRand()

static void ReportHardwareRand ( )
static

Definition at line 217 of file random.cpp.

Here is the caller graph for this function:

◆ SeedFast()

static void SeedFast ( CSHA512 hasher)
staticnoexcept

Definition at line 516 of file random.cpp.

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

◆ SeedHardwareFast()

static void SeedHardwareFast ( CSHA512 hasher)
staticnoexcept

Add 64 bits of entropy gathered from hardware to hasher.

Do nothing if not supported.

Definition at line 224 of file random.cpp.

Here is the caller graph for this function:

◆ SeedHardwareSlow()

static void SeedHardwareSlow ( CSHA512 hasher)
staticnoexcept

Add 256 bits of entropy gathered from hardware to hasher.

Do nothing if not supported.

Definition at line 238 of file random.cpp.

Here is the caller graph for this function:

◆ SeedPeriodic()

static void SeedPeriodic ( CSHA512 hasher,
RNGState &  rng 
)
staticnoexcept

Definition at line 563 of file random.cpp.

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

◆ SeedSlow()

static void SeedSlow ( CSHA512 hasher,
RNGState &  rng 
)
staticnoexcept

Definition at line 530 of file random.cpp.

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

◆ SeedStartup()

static void SeedStartup ( CSHA512 hasher,
RNGState &  rng 
)
staticnoexcept

Definition at line 584 of file random.cpp.

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

◆ SeedStrengthen()

static void SeedStrengthen ( CSHA512 hasher,
RNGState &  rng,
int  microseconds 
)
staticnoexcept

Extract entropy from rng, strengthen it, and feed it into hasher.

Definition at line 552 of file random.cpp.

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

◆ SeedTimestamp()

static void SeedTimestamp ( CSHA512 hasher)
staticnoexcept

A note on the use of noexcept in the seeding functions below:

None of the RNG code should ever throw any exception.

Definition at line 511 of file random.cpp.

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

◆ Strengthen()

static void Strengthen ( const uint8_t(&)  seed[32],
int  microseconds,
CSHA512 hasher 
)
staticnoexcept

Use repeated SHA512 to strengthen the randomness in seed32, and feed into hasher.

Definition at line 268 of file random.cpp.

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

Variable Documentation

◆ g_mock_deterministic_tests

bool g_mock_deterministic_tests {false}

Definition at line 653 of file random.cpp.