31 #ifdef HAVE_SYS_GETRANDOM
32 #include <sys/syscall.h>
33 #include <linux/random.h>
35 #if defined(HAVE_GETENTROPY_RAND) && defined(MAC_OSX)
37 #include <sys/random.h>
39 #ifdef HAVE_SYSCTL_ARND
40 #include <sys/sysctl.h>
45 LogPrintf(
"Failed to read randomness, aborting\n");
53 #if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64))
55 #elif !defined(_MSC_VER) && defined(__i386__)
57 __asm__
volatile (
"rdtsc" :
"=A"(r));
59 #elif !defined(_MSC_VER) && (defined(__x86_64__) || defined(__amd64__))
60 uint64_t r1 = 0, r2 = 0;
61 __asm__
volatile (
"rdtsc" :
"=a"(r1),
"=d"(r2));
62 return (r2 << 32) | r1;
65 return std::chrono::high_resolution_clock::now().time_since_epoch().count();
70 static bool g_rdrand_supported =
false;
71 static bool g_rdseed_supported =
false;
72 static constexpr uint32_t CPUID_F1_ECX_RDRAND = 0x40000000;
73 static constexpr uint32_t CPUID_F7_EBX_RDSEED = 0x00040000;
75 static_assert(CPUID_F1_ECX_RDRAND == bit_RDRND,
"Unexpected value for bit_RDRND");
78 static_assert(CPUID_F7_EBX_RDSEED == bit_RDSEED,
"Unexpected value for bit_RDSEED");
83 uint32_t eax, ebx, ecx, edx;
84 GetCPUID(1, 0, eax, ebx, ecx, edx);
85 if (ecx & CPUID_F1_ECX_RDRAND) {
86 g_rdrand_supported =
true;
88 GetCPUID(7, 0, eax, ebx, ecx, edx);
89 if (ebx & CPUID_F7_EBX_RDSEED) {
90 g_rdseed_supported =
true;
98 if (g_rdseed_supported) {
99 LogPrintf(
"Using RdSeed as an additional entropy source\n");
101 if (g_rdrand_supported) {
102 LogPrintf(
"Using RdRand as an additional entropy source\n");
110 static uint64_t GetRdRand() noexcept
118 uint32_t r1 = 0, r2 = 0;
119 for (
int i = 0; i < 10; ++i) {
120 __asm__
volatile (
".byte 0x0f, 0xc7, 0xf0; setc %1" :
"=a"(r1),
"=q"(ok) ::
"cc");
123 for (
int i = 0; i < 10; ++i) {
124 __asm__
volatile (
".byte 0x0f, 0xc7, 0xf0; setc %1" :
"=a"(r2),
"=q"(ok) ::
"cc");
127 return (((uint64_t)r2) << 32) | r1;
128 #elif defined(__x86_64__) || defined(__amd64__)
131 for (
int i = 0; i < 10; ++i) {
132 __asm__
volatile (
".byte 0x48, 0x0f, 0xc7, 0xf0; setc %1" :
"=a"(r1),
"=q"(ok) ::
"cc");
137 #error "RdRand is only supported on x86 and x86_64"
145 static uint64_t GetRdSeed() noexcept
153 __asm__
volatile (
".byte 0x0f, 0xc7, 0xf8; setc %1" :
"=a"(r1),
"=q"(ok) ::
"cc");
155 __asm__
volatile (
"pause");
158 __asm__
volatile (
".byte 0x0f, 0xc7, 0xf8; setc %1" :
"=a"(r2),
"=q"(ok) ::
"cc");
160 __asm__
volatile (
"pause");
162 return (((uint64_t)r2) << 32) | r1;
163 #elif defined(__x86_64__) || defined(__amd64__)
167 __asm__
volatile (
".byte 0x48, 0x0f, 0xc7, 0xf8; setc %1" :
"=a"(r1),
"=q"(ok) ::
"cc");
169 __asm__
volatile (
"pause");
173 #error "RdSeed is only supported on x86 and x86_64"
189 #if defined(__x86_64__) || defined(__amd64__) || defined(__i386__)
190 if (g_rdrand_supported) {
191 uint64_t out = GetRdRand();
192 hasher.Write((
const unsigned char*)&out,
sizeof(out));
200 #if defined(__x86_64__) || defined(__amd64__) || defined(__i386__)
203 if (g_rdseed_supported) {
204 for (
int i = 0; i < 4; ++i) {
205 uint64_t out = GetRdSeed();
206 hasher.Write((
const unsigned char*)&out,
sizeof(out));
212 if (g_rdrand_supported) {
213 for (
int i = 0; i < 4; ++i) {
215 for (
int j = 0; j < 1024; ++j) out ^= GetRdRand();
216 hasher.Write((
const unsigned char*)&out,
sizeof(out));
224 static void Strengthen(
const unsigned char (&seed)[32], SteadyClock::duration dur,
CSHA512& hasher) noexcept
227 inner_hasher.
Write(seed,
sizeof(seed));
230 unsigned char buffer[64];
231 const auto stop{SteadyClock::now() + dur};
233 for (
int i = 0; i < 1000; ++i) {
235 inner_hasher.
Reset();
236 inner_hasher.
Write(buffer,
sizeof(buffer));
240 hasher.Write((
const unsigned char*)&perf,
sizeof(perf));
241 }
while (SteadyClock::now() <
stop);
245 hasher.Write(buffer,
sizeof(buffer));
247 inner_hasher.
Reset();
257 int f = open(
"/dev/urandom", O_RDONLY);
278 HCRYPTPROV hProvider;
279 int ret = CryptAcquireContextW(&hProvider,
nullptr,
nullptr, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
287 CryptReleaseContext(hProvider, 0);
288 #elif defined(HAVE_SYS_GETRANDOM)
296 if (rv < 0 && errno == ENOSYS) {
306 #elif defined(__OpenBSD__)
316 #elif defined(HAVE_GETENTROPY_RAND) && defined(MAC_OSX)
324 #elif defined(HAVE_SYSCTL_ARND)
328 static int name[2] = {CTL_KERN, KERN_ARND};
332 if (sysctl(
name, std::size(
name), ent32 + have, &len,
nullptr, 0) != 0) {
359 unsigned char m_state[32]
GUARDED_BY(m_mutex) = {0};
361 bool m_strongly_seeded
GUARDED_BY(m_mutex) =
false;
363 Mutex m_events_mutex;
372 ~RNGState() =
default;
376 LOCK(m_events_mutex);
378 m_events_hasher.Write((
const unsigned char *)&event_info,
sizeof(event_info));
382 m_events_hasher.Write((
const unsigned char*)&perfcounter,
sizeof(perfcounter));
392 LOCK(m_events_mutex);
394 unsigned char events_hash[32];
395 m_events_hasher.Finalize(events_hash);
396 hasher.Write(events_hash, 32);
399 m_events_hasher.Reset();
400 m_events_hasher.Write(events_hash, 32);
410 unsigned char buf[64];
411 static_assert(
sizeof(buf) ==
CSHA512::OUTPUT_SIZE,
"Buffer needs to have hasher's output size");
415 ret = (m_strongly_seeded |= strong_seed);
417 hasher.Write(m_state, 32);
419 hasher.Write((
const unsigned char*)&m_counter,
sizeof(m_counter));
422 hasher.Finalize(buf);
424 memcpy(m_state, buf + 32, 32);
429 memcpy(out, buf, num);
438 RNGState& GetRNGState() noexcept
442 static std::vector<RNGState, secure_allocator<RNGState>> g_rng(1);
455 hasher.Write((
const unsigned char*)&perfcounter,
sizeof(perfcounter));
460 unsigned char buffer[32];
463 const unsigned char* ptr = buffer;
464 hasher.Write((
const unsigned char*)&ptr,
sizeof(ptr));
475 unsigned char buffer[32];
482 hasher.Write(buffer,
sizeof(buffer));
485 rng.SeedEvents(hasher);
498 unsigned char strengthen_seed[32];
499 rng.MixExtract(strengthen_seed,
sizeof(strengthen_seed),
CSHA512(hasher),
false);
513 rng.SeedEvents(hasher);
516 auto old_size = hasher.Size();
518 LogPrint(
BCLog::RAND,
"Feeding %i bytes of dynamic environment data into RNG\n", hasher.Size() - old_size);
533 auto old_size = hasher.Size();
538 LogPrint(
BCLog::RAND,
"Feeding %i bytes of environment data into RNG\n", hasher.Size() - old_size);
553 RNGState& rng = GetRNGState();
571 if (!rng.MixExtract(out, num, std::move(hasher),
false)) {
575 rng.MixExtract(out, num, std::move(startup_hasher),
true);
582 void RandAddEvent(
const uint32_t event_info) noexcept { GetRNGState().AddEvent(event_info); }
616 std::vector<unsigned char>
ret(len);
625 rng.SetKey32(seed.begin());
636 static constexpr
int MAX_TRIES{1024};
646 overwritten[x] |= (data[x] != 0);
651 if (overwritten[x]) {
652 num_overwritten += 1;
661 std::this_thread::sleep_for(std::chrono::milliseconds(1));
663 if (
stop == start)
return false;
667 to_add.
Write((
const unsigned char*)&start,
sizeof(start));
669 GetRNGState().MixExtract(
nullptr, 0, std::move(to_add),
false);
676 if (!fDeterministic) {
680 rng.SetKey32(seed.
begin());
687 bitbuf = from.bitbuf;
688 bitbuf_size = from.bitbuf_size;
689 from.requires_seed =
true;
690 from.bitbuf_size = 0;
702 std::chrono::microseconds
GetExponentialRand(std::chrono::microseconds now, std::chrono::seconds average_interval)
704 double unscaled = -std::log1p(
GetRand(uint64_t{1} << 48) * -0.0000000000000035527136788 );
705 return now + std::chrono::duration_cast<std::chrono::microseconds>(unscaled * average_interval + 0.5us);
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 SetKey32(const unsigned char *key32)
set 32-byte key.
void Keystream(unsigned char *c, size_t bytes)
outputs the keystream of size <bytes> into
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).
A Span is an object that can refer to a contiguous sequence of objects.
constexpr unsigned char * begin()
void memory_cleanse(void *ptr, size_t len)
Secure overwrite a buffer (possibly containing secret data) with zero-bytes.
#define LogPrint(category,...)
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....
static void ReportHardwareRand()
static void SeedStrengthen(CSHA512 &hasher, RNGState &rng, SteadyClock::duration dur) noexcept
Extract entropy from rng, strengthen it, and feed it into hasher.
void GetRandBytes(Span< unsigned char > bytes) noexcept
Overall design of the RNG and entropy sources.
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.
uint64_t GetRandInternal(uint64_t nMax) noexcept
Generate a uniform random integer in the range [0..range).
void GetStrongRandBytes(Span< unsigned char > bytes) 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
void RandAddEvent(const uint32_t event_info) noexcept
Gathers entropy from the low bits of the time at which events occur.
static void RandFailure()
static void Strengthen(const unsigned char(&seed)[32], SteadyClock::duration dur, CSHA512 &hasher) noexcept
Use repeated SHA512 to strengthen the randomness in seed32, and feed into hasher.
@ 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.
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
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_limi...
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.
#define EXCLUSIVE_LOCKS_REQUIRED(...)