Bitcoin
Classes | Namespaces | Enumerations | Functions | Variables
random.cpp File Reference
#include <random.h>
#include <crypto/sha512.h>
#include <support/cleanse.h>
#include <logging.h>
#include <sync.h>
#include <util/time.h>
#include <stdlib.h>
#include <chrono>
#include <thread>
#include <support/allocators/secure.h>
#include <fcntl.h>
#include <sys/time.h>
#include <mutex>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/conf.h>

Classes

class  anonymous_namespace{random.cpp}::RNGState
 

Namespaces

 anonymous_namespace{random.cpp}
 

Enumerations

enum  RNGLevel { RNGLevel::FAST, RNGLevel::SLOW, RNGLevel::SLEEP }
 

Functions

static void RandFailure ()
 
static int64_t GetPerformanceCounter () noexcept
 
static void InitHardwareRand ()
 
static void ReportHardwareRand ()
 
static void SeedHardwareFast (CSHA512 &hasher) noexcept
 
static void SeedHardwareSlow (CSHA512 &hasher) noexcept
 
static void Strengthen (const unsigned char(&seed)[32], int microseconds, CSHA512 &hasher) noexcept
 
static void RandAddSeedPerfmon (CSHA512 &hasher)
 
static void GetDevURandom (unsigned char *ent32)
 
void GetOSRand (unsigned char *ent32)
 
void LockingCallbackOpenSSL (int mode, int i, const char *file, int line)
 
RNGState & anonymous_namespace{random.cpp}::GetRNGState () noexcept
 
static void SeedTimestamp (CSHA512 &hasher) noexcept
 
static void SeedFast (CSHA512 &hasher) noexcept
 
static void SeedSlow (CSHA512 &hasher) noexcept
 
static void SeedStrengthen (CSHA512 &hasher, RNGState &rng) noexcept
 
static void SeedSleep (CSHA512 &hasher, RNGState &rng)
 
static void SeedStartup (CSHA512 &hasher, RNGState &rng) noexcept
 
static void ProcRand (unsigned char *out, int num, RNGLevel level)
 
void GetRandBytes (unsigned char *buf, int num) noexcept
 
void GetStrongRandBytes (unsigned char *buf, int num) noexcept
 
void RandAddSeedSleep ()
 
uint64_t GetRand (uint64_t nMax) noexcept
 
int GetRandInt (int nMax) noexcept
 
uint256 GetRandHash () noexcept
 
bool Random_SanityCheck ()
 
void RandomInit ()
 

Variables

bool g_mock_deterministic_tests {false}
 

Enumeration Type Documentation

◆ RNGLevel

enum RNGLevel
strong
Enumerator
FAST 

Automatically called by GetRandBytes.

SLOW 

Automatically called by GetStrongRandBytes.

SLEEP 

Called by RandAddSeedSleep()

Function Documentation

◆ GetDevURandom()

static void GetDevURandom ( unsigned char *  ent32)
static

Fallback: get 32 bytes of system entropy from /dev/urandom. The most compatible way to get cryptographic randomness on UNIX-ish platforms.

◆ GetOSRand()

void GetOSRand ( unsigned char *  ent32)

Get 32 bytes of system entropy.

◆ GetPerformanceCounter()

static int64_t GetPerformanceCounter ( )
inlinestaticnoexcept

◆ GetRand()

uint64_t GetRand ( uint64_t  nMax)
noexcept

◆ GetRandBytes()

void GetRandBytes ( unsigned char *  buf,
int  num 
)
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.
    • Bytes from OpenSSL's RNG (which itself may be seeded from various sources)
    • 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.
  • RandAddSeedSleep() seeds everything that fast seeding includes, but additionally:
    • A high-precision timestamp before and after sleeping 1ms.
    • (On Windows) Once every 10 minutes, performance monitoring data from the OS.

- Once every minute, strengthen the entropy for 10 ms using repeated SHA512. These just exploit the fact the system is idle to improve the quality of the RNG slightly.

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.
  • (On Windows) Performance monitoring data from the OS.
  • (On Windows) Through OpenSSL, the screen contents.
  • 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.

◆ GetRandHash()

uint256 GetRandHash ( )
noexcept

◆ GetRandInt()

int GetRandInt ( int  nMax)
noexcept

◆ GetStrongRandBytes()

void GetStrongRandBytes ( unsigned char *  buf,
int  num 
)
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.

◆ InitHardwareRand()

static void InitHardwareRand ( )
static

◆ LockingCallbackOpenSSL()

void LockingCallbackOpenSSL ( int  mode,
int  i,
const char *  file,
int  line 
)

◆ ProcRand()

static void ProcRand ( unsigned char *  out,
int  num,
RNGLevel  level 
)
static

◆ RandAddSeedPerfmon()

static void RandAddSeedPerfmon ( CSHA512 hasher)
static

◆ RandAddSeedSleep()

void RandAddSeedSleep ( )

Sleep for 1ms, gather entropy from various sources, and feed them to the PRNG state.

Thread-safe.

◆ RandFailure()

static void RandFailure ( )
static

◆ Random_SanityCheck()

bool Random_SanityCheck ( )

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

◆ 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.

◆ ReportHardwareRand()

static void ReportHardwareRand ( )
static

◆ SeedFast()

static void SeedFast ( CSHA512 hasher)
staticnoexcept

◆ SeedHardwareFast()

static void SeedHardwareFast ( CSHA512 hasher)
staticnoexcept

Add 64 bits of entropy gathered from hardware to hasher. Do nothing if not supported.

◆ SeedHardwareSlow()

static void SeedHardwareSlow ( CSHA512 hasher)
staticnoexcept

Add 256 bits of entropy gathered from hardware to hasher. Do nothing if not supported.

◆ SeedSleep()

static void SeedSleep ( CSHA512 hasher,
RNGState &  rng 
)
static

◆ SeedSlow()

static void SeedSlow ( CSHA512 hasher)
staticnoexcept

◆ SeedStartup()

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

◆ SeedStrengthen()

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

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

◆ SeedTimestamp()

static void SeedTimestamp ( CSHA512 hasher)
staticnoexcept

◆ Strengthen()

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

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

Variable Documentation

◆ g_mock_deterministic_tests

bool g_mock_deterministic_tests {false}