30#ifdef HAVE_SYS_GETRANDOM
31#include <sys/syscall.h>
32#include <linux/random.h>
34#if defined(HAVE_GETENTROPY) || (defined(HAVE_GETENTROPY_RAND) && defined(MAC_OSX))
37#if defined(HAVE_GETENTROPY_RAND) && defined(MAC_OSX)
38#include <sys/random.h>
40#ifdef HAVE_SYSCTL_ARND
41#include <sys/sysctl.h>
46 LogPrintf(
"Failed to read randomness, aborting\n");
54#if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64))
56#elif !defined(_MSC_VER) && defined(__i386__)
58 __asm__
volatile (
"rdtsc" :
"=A"(r));
60#elif !defined(_MSC_VER) && (defined(__x86_64__) || defined(__amd64__))
61 uint64_t r1 = 0, r2 = 0;
62 __asm__
volatile (
"rdtsc" :
"=a"(r1),
"=d"(r2));
63 return (r2 << 32) | r1;
66 return std::chrono::high_resolution_clock::now().time_since_epoch().count();
71static bool g_rdrand_supported =
false;
72static bool g_rdseed_supported =
false;
73static constexpr uint32_t CPUID_F1_ECX_RDRAND = 0x40000000;
74static constexpr uint32_t CPUID_F7_EBX_RDSEED = 0x00040000;
76static_assert(CPUID_F1_ECX_RDRAND == bit_RDRND,
"Unexpected value for bit_RDRND");
79static_assert(CPUID_F7_EBX_RDSEED == bit_RDSEED,
"Unexpected value for bit_RDSEED");
84 uint32_t eax, ebx, ecx, edx;
85 GetCPUID(1, 0, eax, ebx, ecx, edx);
86 if (ecx & CPUID_F1_ECX_RDRAND) {
87 g_rdrand_supported =
true;
89 GetCPUID(7, 0, eax, ebx, ecx, edx);
90 if (ebx & CPUID_F7_EBX_RDSEED) {
91 g_rdseed_supported =
true;
99 if (g_rdseed_supported) {
100 LogPrintf(
"Using RdSeed as additional entropy source\n");
102 if (g_rdrand_supported) {
103 LogPrintf(
"Using RdRand as an additional entropy source\n");
111static uint64_t GetRdRand() noexcept
119 uint32_t r1 = 0, r2 = 0;
120 for (
int i = 0; i < 10; ++i) {
121 __asm__
volatile (
".byte 0x0f, 0xc7, 0xf0; setc %1" :
"=a"(r1),
"=q"(ok) ::
"cc");
124 for (
int i = 0; i < 10; ++i) {
125 __asm__
volatile (
".byte 0x0f, 0xc7, 0xf0; setc %1" :
"=a"(r2),
"=q"(ok) ::
"cc");
128 return (((uint64_t)r2) << 32) | r1;
129#elif defined(__x86_64__) || defined(__amd64__)
132 for (
int i = 0; i < 10; ++i) {
133 __asm__
volatile (
".byte 0x48, 0x0f, 0xc7, 0xf0; setc %1" :
"=a"(r1),
"=q"(ok) ::
"cc");
138#error "RdRand is only supported on x86 and x86_64"
146static uint64_t GetRdSeed() noexcept
154 __asm__
volatile (
".byte 0x0f, 0xc7, 0xf8; setc %1" :
"=a"(r1),
"=q"(ok) ::
"cc");
156 __asm__
volatile (
"pause");
159 __asm__
volatile (
".byte 0x0f, 0xc7, 0xf8; setc %1" :
"=a"(r2),
"=q"(ok) ::
"cc");
161 __asm__
volatile (
"pause");
163 return (((uint64_t)r2) << 32) | r1;
164#elif defined(__x86_64__) || defined(__amd64__)
168 __asm__
volatile (
".byte 0x48, 0x0f, 0xc7, 0xf8; setc %1" :
"=a"(r1),
"=q"(ok) ::
"cc");
170 __asm__
volatile (
"pause");
174#error "RdSeed is only supported on x86 and x86_64"
190#if defined(__x86_64__) || defined(__amd64__) || defined(__i386__)
191 if (g_rdrand_supported) {
192 uint64_t out = GetRdRand();
193 hasher.Write((
const unsigned char*)&out,
sizeof(out));
201#if defined(__x86_64__) || defined(__amd64__) || defined(__i386__)
204 if (g_rdseed_supported) {
205 for (
int i = 0; i < 4; ++i) {
206 uint64_t out = GetRdSeed();
207 hasher.Write((
const unsigned char*)&out,
sizeof(out));
213 if (g_rdrand_supported) {
214 for (
int i = 0; i < 4; ++i) {
216 for (
int j = 0; j < 1024; ++j) out ^= GetRdRand();
217 hasher.Write((
const unsigned char*)&out,
sizeof(out));
225static void Strengthen(
const unsigned char (&seed)[32],
int microseconds,
CSHA512& hasher)
noexcept
228 inner_hasher.
Write(seed,
sizeof(seed));
231 unsigned char buffer[64];
234 for (
int i = 0; i < 1000; ++i) {
236 inner_hasher.
Reset();
237 inner_hasher.
Write(buffer,
sizeof(buffer));
241 hasher.Write((
const unsigned char*)&perf,
sizeof(perf));
246 hasher.Write(buffer,
sizeof(buffer));
248 inner_hasher.
Reset();
258 int f = open(
"/dev/urandom", O_RDONLY);
279 HCRYPTPROV hProvider;
280 int ret = CryptAcquireContextW(&hProvider,
nullptr,
nullptr, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
288 CryptReleaseContext(hProvider, 0);
289#elif defined(HAVE_SYS_GETRANDOM)
297 if (rv < 0 && errno == ENOSYS) {
307#elif defined(HAVE_GETENTROPY) && defined(__OpenBSD__)
319#elif defined(HAVE_GETENTROPY_RAND) && defined(MAC_OSX)
327#elif defined(HAVE_SYSCTL_ARND)
331 static int name[2] = {CTL_KERN, KERN_ARND};
335 if (sysctl(
name, std::size(
name), ent32 + have, &len,
nullptr, 0) != 0) {
362 unsigned char m_state[32]
GUARDED_BY(m_mutex) = {0};
364 bool m_strongly_seeded
GUARDED_BY(m_mutex) =
false;
366 Mutex m_events_mutex;
379 void AddEvent(uint32_t event_info)
noexcept
381 LOCK(m_events_mutex);
383 m_events_hasher.Write((
const unsigned char *)&event_info,
sizeof(event_info));
387 m_events_hasher.Write((
const unsigned char*)&perfcounter,
sizeof(perfcounter));
393 void SeedEvents(
CSHA512& hasher)
noexcept
397 LOCK(m_events_mutex);
399 unsigned char events_hash[32];
400 m_events_hasher.Finalize(events_hash);
401 hasher.Write(events_hash, 32);
404 m_events_hasher.Reset();
405 m_events_hasher.Write(events_hash, 32);
412 bool MixExtract(
unsigned char* out,
size_t num,
CSHA512&& hasher,
bool strong_seed)
noexcept
415 unsigned char buf[64];
416 static_assert(
sizeof(buf) ==
CSHA512::OUTPUT_SIZE,
"Buffer needs to have hasher's output size");
420 ret = (m_strongly_seeded |= strong_seed);
422 hasher.Write(m_state, 32);
424 hasher.Write((
const unsigned char*)&m_counter,
sizeof(m_counter));
427 hasher.Finalize(buf);
429 memcpy(m_state, buf + 32, 32);
434 memcpy(out, buf, num);
443RNGState& GetRNGState() noexcept
447 static std::vector<RNGState, secure_allocator<RNGState>> g_rng(1);
460 hasher.Write((
const unsigned char*)&perfcounter,
sizeof(perfcounter));
465 unsigned char buffer[32];
468 const unsigned char* ptr = buffer;
469 hasher.Write((
const unsigned char*)&ptr,
sizeof(ptr));
480 unsigned char buffer[32];
487 hasher.Write(buffer,
sizeof(buffer));
490 rng.SeedEvents(hasher);
503 unsigned char strengthen_seed[32];
504 rng.MixExtract(strengthen_seed,
sizeof(strengthen_seed),
CSHA512(hasher),
false);
506 Strengthen(strengthen_seed, microseconds, hasher);
518 rng.SeedEvents(hasher);
521 auto old_size = hasher.Size();
523 LogPrint(
BCLog::RAND,
"Feeding %i bytes of dynamic environment data into RNG\n", hasher.Size() - old_size);
538 auto old_size = hasher.Size();
543 LogPrint(
BCLog::RAND,
"Feeding %i bytes of environment data into RNG\n", hasher.Size() - old_size);
558 RNGState& rng = GetRNGState();
576 if (!rng.MixExtract(out, num, std::move(hasher),
false)) {
580 rng.MixExtract(out, num, std::move(startup_hasher),
true);
587void RandAddEvent(
const uint32_t event_info)
noexcept { GetRNGState().AddEvent(event_info); }
629 std::vector<unsigned char> ret(len);
638 rng.SetKey(seed.begin(), 32);
649 static const ssize_t MAX_TRIES = 1024;
659 overwritten[x] |= (data[x] != 0);
664 if (overwritten[x]) {
665 num_overwritten += 1;
674 std::this_thread::sleep_for(std::chrono::milliseconds(1));
676 if (
stop == start)
return false;
680 to_add.
Write((
const unsigned char*)&start,
sizeof(start));
682 GetRNGState().MixExtract(
nullptr, 0, std::move(to_add),
false);
689 if (!fDeterministic) {
693 rng.SetKey(seed.
begin(), 32);
700 std::copy(std::begin(from.bytebuf), std::end(from.bytebuf), std::begin(bytebuf));
701 bytebuf_size = from.bytebuf_size;
702 bitbuf = from.bitbuf;
703 bitbuf_size = from.bitbuf_size;
704 from.requires_seed =
true;
705 from.bytebuf_size = 0;
706 from.bitbuf_size = 0;
A hasher class for SHA-256.
A hasher class for SHA-512.
static constexpr size_t OUTPUT_SIZE
void Finalize(unsigned char hash[OUTPUT_SIZE])
CSHA512 & Write(const unsigned char *data, size_t len)
void Keystream(unsigned char *c, size_t bytes)
outputs the keystream of size <bytes> into
void SetKey(const unsigned char *key, size_t keylen)
set key with flexible keylength; 256bit recommended */
unsigned char bytebuf[64]
FastRandomContext(bool fDeterministic=false) noexcept
uint256 rand256() noexcept
generate a random uint256.
std::vector< unsigned char > randbytes(size_t len)
Generate random bytes.
FastRandomContext & operator=(const FastRandomContext &)=delete
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
void memory_cleanse(void *ptr, size_t len)
Secure overwrite a buffer (possibly containing secret data) with zero-bytes.
#define LogPrint(category,...)
static void Strengthen(const unsigned char(&seed)[32], int microseconds, CSHA512 &hasher) noexcept
Use repeated SHA512 to strengthen the randomness in seed32, and feed into hasher.
static void ReportHardwareRand()
static void SeedStrengthen(CSHA512 &hasher, RNGState &rng, int microseconds) noexcept
Extract entropy from rng, strengthen it, and feed it into hasher.
static void SeedStartup(CSHA512 &hasher, RNGState &rng) noexcept
void RandAddPeriodic() noexcept
Gather entropy from various expensive sources, and feed them to the PRNG state.
static void GetDevURandom(unsigned char *ent32)
Fallback: get 32 bytes of system entropy from /dev/urandom.
bool g_mock_deterministic_tests
Flag to make GetRand in random.h return the same number.
static void SeedFast(CSHA512 &hasher) noexcept
static void InitHardwareRand()
static void SeedHardwareFast(CSHA512 &hasher) noexcept
Add 64 bits of entropy gathered from hardware to hasher.
void GetRandBytes(unsigned char *buf, int num) noexcept
Overall design of the RNG and entropy sources.
void GetStrongRandBytes(unsigned char *buf, int num) noexcept
Gather entropy from various sources, feed it into the internal PRNG, and generate random data using i...
static void SeedTimestamp(CSHA512 &hasher) noexcept
bool Random_SanityCheck()
Check that OS randomness is available and returning the requested number of bytes.
uint256 GetRandHash() noexcept
static void ProcRand(unsigned char *out, int num, RNGLevel level) noexcept
void RandomInit()
Initialize global RNG state and log any CPU features that are used.
static void SeedPeriodic(CSHA512 &hasher, RNGState &rng) noexcept
uint64_t GetRand(uint64_t nMax) noexcept
Generate a uniform random integer in the range [0..range).
void RandAddEvent(const uint32_t event_info) noexcept
Gathers entropy from the low bits of the time at which events occur.
static void RandFailure()
@ SLOW
Automatically called by GetStrongRandBytes.
@ PERIODIC
Called by RandAddPeriodic()
@ FAST
Automatically called by GetRandBytes.
void GetOSRand(unsigned char *ent32)
Get 32 bytes of system entropy.
int GetRandInt(int nMax) noexcept
static void SeedHardwareSlow(CSHA512 &hasher) noexcept
Add 256 bits of entropy gathered from hardware to hasher.
static int64_t GetPerformanceCounter() noexcept
static void SeedSlow(CSHA512 &hasher, RNGState &rng) noexcept
static const int NUM_OS_RANDOM_BYTES
void RandAddStaticEnv(CSHA512 &hasher)
Gather non-cryptographic environment data that does not change over time.
void RandAddDynamicEnv(CSHA512 &hasher)
Gather non-cryptographic environment data that changes over time.
int64_t GetTimeMicros()
Returns the system time (not mockable)