6 #include <bitcoin-build-config.h> 37 #if defined(HAVE_GETRANDOM) || (defined(HAVE_GETENTROPY_RAND) && defined(__APPLE__)) 38 #include <sys/random.h> 41 #ifdef HAVE_SYSCTL_ARND 42 #include <sys/sysctl.h> 52 static const int NUM_OS_RANDOM_BYTES = 32;
55 [[noreturn]]
void RandFailure()
57 LogError(
"Failed to read randomness, aborting\n");
61 inline int64_t GetPerformanceCounter() noexcept
65 #if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64)) 67 #elif !defined(_MSC_VER) && defined(__i386__) 69 __asm__
volatile (
"rdtsc" :
"=A"(r));
71 #elif !defined(_MSC_VER) && (defined(__x86_64__) || defined(__amd64__)) 72 uint64_t r1 = 0, r2 = 0;
73 __asm__
volatile (
"rdtsc" :
"=a"(r1),
"=d"(r2));
74 return (r2 << 32) | r1;
77 return std::chrono::high_resolution_clock::now().time_since_epoch().count();
82 bool g_rdrand_supported =
false;
83 bool g_rdseed_supported =
false;
84 constexpr uint32_t CPUID_F1_ECX_RDRAND = 0x40000000;
85 constexpr uint32_t CPUID_F7_EBX_RDSEED = 0x00040000;
87 static_assert(CPUID_F1_ECX_RDRAND == bit_RDRND,
"Unexpected value for bit_RDRND");
90 static_assert(CPUID_F7_EBX_RDSEED == bit_RDSEED,
"Unexpected value for bit_RDSEED");
93 void InitHardwareRand()
95 uint32_t eax, ebx, ecx, edx;
96 GetCPUID(1, 0, eax, ebx, ecx, edx);
97 if (ecx & CPUID_F1_ECX_RDRAND) {
98 g_rdrand_supported =
true;
100 GetCPUID(7, 0, eax, ebx, ecx, edx);
101 if (ebx & CPUID_F7_EBX_RDSEED) {
102 g_rdseed_supported =
true;
106 void ReportHardwareRand()
110 if (g_rdseed_supported) {
111 LogPrintf(
"Using RdSeed as an additional entropy source\n");
113 if (g_rdrand_supported) {
114 LogPrintf(
"Using RdRand as an additional entropy source\n");
122 uint64_t GetRdRand() noexcept
130 uint32_t r1 = 0, r2 = 0;
131 for (
int i = 0; i < 10; ++i) {
132 __asm__
volatile (
".byte 0x0f, 0xc7, 0xf0; setc %1" :
"=a"(r1),
"=q"(ok) ::
"cc");
135 for (
int i = 0; i < 10; ++i) {
136 __asm__
volatile (
".byte 0x0f, 0xc7, 0xf0; setc %1" :
"=a"(r2),
"=q"(ok) ::
"cc");
139 return (((uint64_t)r2) << 32) | r1;
140 #elif defined(__x86_64__) || defined(__amd64__) 143 for (
int i = 0; i < 10; ++i) {
144 __asm__
volatile (
".byte 0x48, 0x0f, 0xc7, 0xf0; setc %1" :
"=a"(r1),
"=q"(ok) ::
"cc");
149 #error "RdRand is only supported on x86 and x86_64" 157 uint64_t GetRdSeed() noexcept
165 __asm__
volatile (
".byte 0x0f, 0xc7, 0xf8; setc %1" :
"=a"(r1),
"=q"(ok) ::
"cc");
167 __asm__
volatile (
"pause");
170 __asm__
volatile (
".byte 0x0f, 0xc7, 0xf8; setc %1" :
"=a"(r2),
"=q"(ok) ::
"cc");
172 __asm__
volatile (
"pause");
174 return (((uint64_t)r2) << 32) | r1;
175 #elif defined(__x86_64__) || defined(__amd64__) 179 __asm__
volatile (
".byte 0x48, 0x0f, 0xc7, 0xf8; setc %1" :
"=a"(r1),
"=q"(ok) ::
"cc");
181 __asm__
volatile (
"pause");
185 #error "RdSeed is only supported on x86 and x86_64" 195 void InitHardwareRand() {}
196 void ReportHardwareRand() {}
200 void SeedHardwareFast(
CSHA512& hasher) noexcept {
201 #if defined(__x86_64__) || defined(__amd64__) || defined(__i386__) 202 if (g_rdrand_supported) {
203 uint64_t
out = GetRdRand();
204 hasher.Write((
const unsigned char*)&
out,
sizeof(
out));
211 void SeedHardwareSlow(
CSHA512& hasher) noexcept {
212 #if defined(__x86_64__) || defined(__amd64__) || defined(__i386__) 215 if (g_rdseed_supported) {
216 for (
int i = 0; i < 4; ++i) {
217 uint64_t
out = GetRdSeed();
218 hasher.Write((
const unsigned char*)&
out,
sizeof(
out));
224 if (g_rdrand_supported) {
225 for (
int i = 0; i < 4; ++i) {
227 for (
int j = 0; j < 1024; ++j)
out ^= GetRdRand();
228 hasher.Write((
const unsigned char*)&
out,
sizeof(
out));
236 void Strengthen(
const unsigned char (&seed)[32], SteadyClock::duration dur,
CSHA512& hasher) noexcept
239 inner_hasher.
Write(seed,
sizeof(seed));
242 unsigned char buffer[64];
243 const auto stop{SteadyClock::now() + dur};
245 for (
int i = 0; i < 1000; ++i) {
247 inner_hasher.
Reset();
248 inner_hasher.
Write(buffer,
sizeof(buffer));
251 int64_t perf = GetPerformanceCounter();
252 hasher.Write((
const unsigned char*)&perf,
sizeof(perf));
253 }
while (SteadyClock::now() <
stop);
257 hasher.Write(buffer,
sizeof(buffer));
259 inner_hasher.
Reset();
267 [[maybe_unused]]
void GetDevURandom(
unsigned char *ent32)
269 int f = open(
"/dev/urandom", O_RDONLY);
275 ssize_t n = read(f, ent32 + have, NUM_OS_RANDOM_BYTES - have);
276 if (n <= 0 || n + have > NUM_OS_RANDOM_BYTES) {
281 }
while (have < NUM_OS_RANDOM_BYTES);
287 void GetOSRand(
unsigned char *ent32)
290 HCRYPTPROV hProvider;
291 int ret = CryptAcquireContextW(&hProvider,
nullptr,
nullptr, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
295 ret = CryptGenRandom(hProvider, NUM_OS_RANDOM_BYTES, ent32);
299 CryptReleaseContext(hProvider, 0);
300 #elif defined(HAVE_GETRANDOM) 306 if (getrandom(ent32, NUM_OS_RANDOM_BYTES, 0) != NUM_OS_RANDOM_BYTES) {
309 #elif defined(__OpenBSD__) 316 arc4random_buf(ent32, NUM_OS_RANDOM_BYTES);
317 #elif defined(HAVE_GETENTROPY_RAND) && defined(__APPLE__) 318 if (getentropy(ent32, NUM_OS_RANDOM_BYTES) != 0) {
321 #elif defined(HAVE_SYSCTL_ARND) 325 static int name[2] = {CTL_KERN, KERN_ARND};
328 size_t len = NUM_OS_RANDOM_BYTES - have;
329 if (sysctl(
name, std::size(
name), ent32 + have, &len,
nullptr, 0) != 0) {
333 }
while (have < NUM_OS_RANDOM_BYTES);
338 GetDevURandom(ent32);
352 unsigned char m_state[32]
GUARDED_BY(m_mutex) = {0};
354 bool m_strongly_seeded
GUARDED_BY(m_mutex) =
false;
358 std::optional<ChaCha20> m_deterministic_prng
GUARDED_BY(m_mutex);
360 Mutex m_events_mutex;
369 ~RNGState() =
default;
373 LOCK(m_events_mutex);
375 m_events_hasher.Write((
const unsigned char *)&event_info,
sizeof(event_info));
378 uint32_t perfcounter = (GetPerformanceCounter() & 0xffffffff);
379 m_events_hasher.Write((
const unsigned char*)&perfcounter,
sizeof(perfcounter));
389 LOCK(m_events_mutex);
391 unsigned char events_hash[32];
392 m_events_hasher.Finalize(events_hash);
393 hasher.Write(events_hash, 32);
396 m_events_hasher.Reset();
397 m_events_hasher.Write(events_hash, 32);
417 unsigned char buf[64];
418 static_assert(
sizeof(buf) ==
CSHA512::OUTPUT_SIZE,
"Buffer needs to have hasher's output size");
422 ret = (m_strongly_seeded |= strong_seed);
424 hasher.Write(m_state, 32);
426 hasher.Write((
const unsigned char*)&m_counter,
sizeof(m_counter));
429 hasher.Finalize(buf);
431 memcpy(m_state, buf + 32, 32);
433 if (!always_use_real_rng && m_deterministic_prng.has_value()) [[unlikely]] {
452 RNGState& GetRNGState() noexcept
456 static std::vector<RNGState, secure_allocator<RNGState>> g_rng(1);
465 void SeedTimestamp(
CSHA512& hasher) noexcept
467 int64_t perfcounter = GetPerformanceCounter();
468 hasher.Write((
const unsigned char*)&perfcounter,
sizeof(perfcounter));
471 void SeedFast(
CSHA512& hasher) noexcept
473 unsigned char buffer[32];
476 const unsigned char* ptr = buffer;
477 hasher.Write((
const unsigned char*)&ptr,
sizeof(ptr));
480 SeedHardwareFast(hasher);
483 SeedTimestamp(hasher);
486 void SeedSlow(
CSHA512& hasher, RNGState& rng) noexcept
488 unsigned char buffer[32];
495 hasher.Write(buffer,
sizeof(buffer));
498 rng.SeedEvents(hasher);
504 SeedTimestamp(hasher);
508 void SeedStrengthen(
CSHA512& hasher, RNGState& rng, SteadyClock::duration dur) noexcept
512 unsigned char strengthen_seed[32];
513 rng.MixExtract(strengthen_seed,
sizeof(strengthen_seed),
CSHA512(hasher),
false,
true);
515 Strengthen(strengthen_seed, dur, hasher);
518 void SeedPeriodic(
CSHA512& hasher, RNGState& rng) noexcept
524 SeedTimestamp(hasher);
527 rng.SeedEvents(hasher);
530 auto old_size = hasher.Size();
532 LogDebug(
BCLog::RAND,
"Feeding %i bytes of dynamic environment data into RNG\n", hasher.Size() - old_size);
535 SeedStrengthen(hasher, rng, 10ms);
538 void SeedStartup(
CSHA512& hasher, RNGState& rng) noexcept
541 SeedHardwareSlow(hasher);
544 SeedSlow(hasher, rng);
547 auto old_size = hasher.Size();
552 LogDebug(
BCLog::RAND,
"Feeding %i bytes of environment data into RNG\n", hasher.Size() - old_size);
555 SeedStrengthen(hasher, rng, 100ms);
564 void ProcRand(
unsigned char*
out,
int num,
RNGLevel level,
bool always_use_real_rng) noexcept
567 RNGState& rng = GetRNGState();
577 SeedSlow(hasher, rng);
579 case RNGLevel::PERIODIC:
580 SeedPeriodic(hasher, rng);
585 if (!rng.MixExtract(
out, num, std::move(hasher),
false, always_use_real_rng)) {
588 SeedStartup(startup_hasher, rng);
589 rng.MixExtract(
out, num, std::move(startup_hasher),
true, always_use_real_rng);
599 GetRNGState().MakeDeterministic(seed);
606 ProcRand(bytes.data(), bytes.size(), RNGLevel::FAST,
false);
611 ProcRand(bytes.data(), bytes.size(), RNGLevel::SLOW,
true);
616 ProcRand(
nullptr, 0, RNGLevel::PERIODIC,
false);
619 void RandAddEvent(
const uint32_t event_info) noexcept { GetRNGState().AddEvent(event_info); }
630 if (requires_seed) RandomSeed();
631 rng.Keystream(output);
639 requires_seed =
false;
645 uint64_t start = GetPerformanceCounter();
651 static constexpr
int MAX_TRIES{1024};
652 uint8_t
data[NUM_OS_RANDOM_BYTES];
653 bool overwritten[NUM_OS_RANDOM_BYTES] = {};
658 memset(
data, 0, NUM_OS_RANDOM_BYTES);
660 for (
int x=0; x < NUM_OS_RANDOM_BYTES; ++x) {
661 overwritten[x] |= (
data[x] != 0);
665 for (
int x=0; x < NUM_OS_RANDOM_BYTES; ++x) {
666 if (overwritten[x]) {
667 num_overwritten += 1;
672 }
while (num_overwritten < NUM_OS_RANDOM_BYTES && tries < MAX_TRIES);
673 if (num_overwritten != NUM_OS_RANDOM_BYTES)
return false;
676 std::this_thread::sleep_for(std::chrono::milliseconds(1));
677 uint64_t
stop = GetPerformanceCounter();
678 if (
stop == start)
return false;
682 to_add.
Write((
const unsigned char*)&start,
sizeof(start));
684 GetRNGState().MixExtract(
nullptr, 0, std::move(to_add),
false,
true);
689 static constexpr std::array<std::byte, ChaCha20::KEYLEN>
ZERO_KEY{};
701 ProcRand(
nullptr, 0, RNGLevel::FAST,
true);
703 ReportHardwareRand();
717 return -std::log1p((uniform >> 11) * -0x1.0p-53);
void RandomInit()
Overall design of the RNG and entropy sources.
void RandAddEvent(const uint32_t event_info) noexcept
Gathers entropy from the low bits of the time at which events occur.
Span< std::byte > AsWritableBytes(Span< T > s) noexcept
void MakeRandDeterministicDANGEROUS(const uint256 &seed) noexcept
Internal function to set g_determinstic_rng.
memcpy(result.begin(), stream.data(), stream.size())
void RandAddPeriodic() noexcept
Gather entropy from various expensive sources, and feed them to the PRNG state.
FastRandomContext(bool fDeterministic=false) noexcept
Construct a FastRandomContext with GetRandHash()-based entropy (or zero key if fDeterministic).
void Finalize(unsigned char hash[OUTPUT_SIZE])
void fillrand(Span< std::byte > output) noexcept
Fill a byte Span with random bytes.
void memory_cleanse(void *ptr, size_t len)
Secure overwrite a buffer (possibly containing secret data) with zero-bytes.
void Reseed(const uint256 &seed) noexcept
Reseed with explicit seed (only for testing).
static constexpr size_t OUTPUT_SIZE
static constexpr std::array< std::byte, ChaCha20::KEYLEN > ZERO_KEY
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#define LogDebug(category,...)
std::atomic< bool > g_used_g_prng
CSHA512 & Write(const unsigned char *data, size_t len)
uint256 GetRandHash() noexcept
Generate a random uint256.
Span< const std::byte > MakeByteSpan(V &&v) noexcept
void GetRandBytes(Span< unsigned char > bytes) noexcept
Generate random data via the internal PRNG.
A Span is an object that can refer to a contiguous sequence of objects.
A hasher class for SHA-512.
A hasher class for SHA-256.
void RandAddStaticEnv(CSHA512 &hasher)
Gather non-cryptographic environment data that does not change over time.
void RandomSeed() noexcept
bool Random_SanityCheck()
Check that OS randomness is available and returning the requested number of bytes.
void SetKey(Span< const std::byte > key) noexcept
Set 32-byte key, and seek to nonce 0 and block position 0.
double MakeExponentiallyDistributed(uint64_t uniform) noexcept
Given a uniformly random uint64_t, return an exponentially distributed double with mean 1...
void GetStrongRandBytes(Span< unsigned char > bytes) noexcept
Gather entropy from various sources, feed it into the internal PRNG, and generate random data using i...
void RandAddDynamicEnv(CSHA512 &hasher)
Gather non-cryptographic environment data that changes over time.