34 #if defined(HAVE_GETRANDOM) || (defined(HAVE_GETENTROPY_RAND) && defined(MAC_OSX)) 35 #include <sys/random.h> 38 #ifdef HAVE_SYSCTL_ARND 39 #include <sys/sysctl.h> 44 LogPrintf(
"Failed to read randomness, aborting\n");
52 #if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64)) 54 #elif !defined(_MSC_VER) && defined(__i386__) 56 __asm__
volatile (
"rdtsc" :
"=A"(r));
58 #elif !defined(_MSC_VER) && (defined(__x86_64__) || defined(__amd64__)) 59 uint64_t r1 = 0, r2 = 0;
60 __asm__
volatile (
"rdtsc" :
"=a"(r1),
"=d"(r2));
61 return (r2 << 32) | r1;
64 return std::chrono::high_resolution_clock::now().time_since_epoch().count();
69 static bool g_rdrand_supported =
false;
70 static bool g_rdseed_supported =
false;
71 static constexpr uint32_t CPUID_F1_ECX_RDRAND = 0x40000000;
72 static constexpr uint32_t CPUID_F7_EBX_RDSEED = 0x00040000;
74 static_assert(CPUID_F1_ECX_RDRAND == bit_RDRND,
"Unexpected value for bit_RDRND");
77 static_assert(CPUID_F7_EBX_RDSEED == bit_RDSEED,
"Unexpected value for bit_RDSEED");
82 uint32_t eax, ebx, ecx, edx;
83 GetCPUID(1, 0, eax, ebx, ecx, edx);
84 if (ecx & CPUID_F1_ECX_RDRAND) {
85 g_rdrand_supported =
true;
87 GetCPUID(7, 0, eax, ebx, ecx, edx);
88 if (ebx & CPUID_F7_EBX_RDSEED) {
89 g_rdseed_supported =
true;
97 if (g_rdseed_supported) {
98 LogPrintf(
"Using RdSeed as an additional entropy source\n");
100 if (g_rdrand_supported) {
101 LogPrintf(
"Using RdRand as an additional entropy source\n");
109 static uint64_t GetRdRand() noexcept
117 uint32_t r1 = 0, r2 = 0;
118 for (
int i = 0; i < 10; ++i) {
119 __asm__
volatile (
".byte 0x0f, 0xc7, 0xf0; setc %1" :
"=a"(r1),
"=q"(ok) ::
"cc");
122 for (
int i = 0; i < 10; ++i) {
123 __asm__
volatile (
".byte 0x0f, 0xc7, 0xf0; setc %1" :
"=a"(r2),
"=q"(ok) ::
"cc");
126 return (((uint64_t)r2) << 32) | r1;
127 #elif defined(__x86_64__) || defined(__amd64__) 130 for (
int i = 0; i < 10; ++i) {
131 __asm__
volatile (
".byte 0x48, 0x0f, 0xc7, 0xf0; setc %1" :
"=a"(r1),
"=q"(ok) ::
"cc");
136 #error "RdRand is only supported on x86 and x86_64" 144 static uint64_t GetRdSeed() noexcept
152 __asm__
volatile (
".byte 0x0f, 0xc7, 0xf8; setc %1" :
"=a"(r1),
"=q"(ok) ::
"cc");
154 __asm__
volatile (
"pause");
157 __asm__
volatile (
".byte 0x0f, 0xc7, 0xf8; setc %1" :
"=a"(r2),
"=q"(ok) ::
"cc");
159 __asm__
volatile (
"pause");
161 return (((uint64_t)r2) << 32) | r1;
162 #elif defined(__x86_64__) || defined(__amd64__) 166 __asm__
volatile (
".byte 0x48, 0x0f, 0xc7, 0xf8; setc %1" :
"=a"(r1),
"=q"(ok) ::
"cc");
168 __asm__
volatile (
"pause");
172 #error "RdSeed is only supported on x86 and x86_64" 188 #if defined(__x86_64__) || defined(__amd64__) || defined(__i386__) 189 if (g_rdrand_supported) {
190 uint64_t
out = GetRdRand();
191 hasher.Write((
const unsigned char*)&
out,
sizeof(
out));
199 #if defined(__x86_64__) || defined(__amd64__) || defined(__i386__) 202 if (g_rdseed_supported) {
203 for (
int i = 0; i < 4; ++i) {
204 uint64_t
out = GetRdSeed();
205 hasher.Write((
const unsigned char*)&
out,
sizeof(
out));
211 if (g_rdrand_supported) {
212 for (
int i = 0; i < 4; ++i) {
214 for (
int j = 0; j < 1024; ++j)
out ^= GetRdRand();
215 hasher.Write((
const unsigned char*)&
out,
sizeof(
out));
223 static void Strengthen(
const unsigned char (&seed)[32], SteadyClock::duration dur,
CSHA512& hasher) noexcept
226 inner_hasher.
Write(seed,
sizeof(seed));
229 unsigned char buffer[64];
230 const auto stop{SteadyClock::now() + dur};
232 for (
int i = 0; i < 1000; ++i) {
234 inner_hasher.
Reset();
235 inner_hasher.
Write(buffer,
sizeof(buffer));
239 hasher.Write((
const unsigned char*)&perf,
sizeof(perf));
240 }
while (SteadyClock::now() <
stop);
244 hasher.Write(buffer,
sizeof(buffer));
246 inner_hasher.
Reset();
256 int f = open(
"/dev/urandom", O_RDONLY);
277 HCRYPTPROV hProvider;
278 int ret = CryptAcquireContextW(&hProvider,
nullptr,
nullptr, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
286 CryptReleaseContext(hProvider, 0);
287 #elif defined(HAVE_GETRANDOM) 296 #elif defined(__OpenBSD__) 304 #elif defined(HAVE_GETENTROPY_RAND) && defined(MAC_OSX) 308 #elif defined(HAVE_SYSCTL_ARND) 312 static int name[2] = {CTL_KERN, KERN_ARND};
316 if (sysctl(
name, std::size(
name), ent32 + have, &len,
nullptr, 0) != 0) {
341 unsigned char m_state[32]
GUARDED_BY(m_mutex) = {0};
343 bool m_strongly_seeded
GUARDED_BY(m_mutex) =
false;
345 Mutex m_events_mutex;
354 ~RNGState() =
default;
358 LOCK(m_events_mutex);
360 m_events_hasher.Write((
const unsigned char *)&event_info,
sizeof(event_info));
364 m_events_hasher.Write((
const unsigned char*)&perfcounter,
sizeof(perfcounter));
374 LOCK(m_events_mutex);
376 unsigned char events_hash[32];
377 m_events_hasher.Finalize(events_hash);
378 hasher.Write(events_hash, 32);
381 m_events_hasher.Reset();
382 m_events_hasher.Write(events_hash, 32);
392 unsigned char buf[64];
393 static_assert(
sizeof(buf) ==
CSHA512::OUTPUT_SIZE,
"Buffer needs to have hasher's output size");
397 ret = (m_strongly_seeded |= strong_seed);
399 hasher.Write(m_state, 32);
401 hasher.Write((
const unsigned char*)&m_counter,
sizeof(m_counter));
404 hasher.Finalize(buf);
406 memcpy(m_state, buf + 32, 32);
411 memcpy(
out, buf, num);
420 RNGState& GetRNGState() noexcept
424 static std::vector<RNGState, secure_allocator<RNGState>> g_rng(1);
437 hasher.Write((
const unsigned char*)&perfcounter,
sizeof(perfcounter));
442 unsigned char buffer[32];
445 const unsigned char* ptr = buffer;
446 hasher.Write((
const unsigned char*)&ptr,
sizeof(ptr));
457 unsigned char buffer[32];
464 hasher.Write(buffer,
sizeof(buffer));
467 rng.SeedEvents(hasher);
480 unsigned char strengthen_seed[32];
481 rng.MixExtract(strengthen_seed,
sizeof(strengthen_seed),
CSHA512(hasher),
false);
495 rng.SeedEvents(hasher);
498 auto old_size = hasher.Size();
500 LogPrint(
BCLog::RAND,
"Feeding %i bytes of dynamic environment data into RNG\n", hasher.Size() - old_size);
515 auto old_size = hasher.Size();
520 LogPrint(
BCLog::RAND,
"Feeding %i bytes of environment data into RNG\n", hasher.Size() - old_size);
535 RNGState& rng = GetRNGState();
553 if (!rng.MixExtract(
out, num, std::move(hasher),
false)) {
557 rng.MixExtract(
out, num, std::move(startup_hasher),
true);
564 void RandAddEvent(
const uint32_t event_info) noexcept { GetRNGState().AddEvent(event_info); }
595 template <
typename B>
598 std::vector<B>
ret(len);
621 static constexpr
int MAX_TRIES{1024};
631 overwritten[x] |= (data[x] != 0);
636 if (overwritten[x]) {
637 num_overwritten += 1;
646 std::this_thread::sleep_for(std::chrono::milliseconds(1));
648 if (
stop == start)
return false;
652 to_add.
Write((
const unsigned char*)&start,
sizeof(start));
654 GetRNGState().MixExtract(
nullptr, 0, std::move(to_add),
false);
659 static constexpr std::array<std::byte, ChaCha20::KEYLEN>
ZERO_KEY{};
672 bitbuf = from.bitbuf;
673 bitbuf_size = from.bitbuf_size;
674 from.requires_seed =
true;
675 from.bitbuf_size = 0;
687 std::chrono::microseconds
GetExponentialRand(std::chrono::microseconds now, std::chrono::seconds average_interval)
689 double unscaled = -std::log1p(
GetRand(uint64_t{1} << 48) * -0.0000000000000035527136788 );
690 return now + std::chrono::duration_cast<std::chrono::microseconds>(unscaled * average_interval + 0.5us);
static const int NUM_OS_RANDOM_BYTES
void RandomInit()
Initialize global RNG state and log any CPU features that are used.
void GetOSRand(unsigned char *ent32)
Get 32 bytes of system entropy.
void RandAddEvent(const uint32_t event_info) noexcept
Gathers entropy from the low bits of the time at which events occur.
uint64_t GetRandInternal(uint64_t nMax) noexcept
Generate a uniform random integer in the range [0..range).
#define LogPrint(category,...)
FastRandomContext & operator=(const FastRandomContext &)=delete
uint256 GetRandHash() noexcept
Span< std::byte > MakeWritableByteSpan(V &&v) noexcept
static void SeedHardwareSlow(CSHA512 &hasher) noexcept
Add 256 bits of entropy gathered from hardware to hasher.
static void ProcRand(unsigned char *out, int num, RNGLevel level) noexcept
static void GetDevURandom(unsigned char *ent32)
Fallback: get 32 bytes of system entropy from /dev/urandom.
static void SeedStrengthen(CSHA512 &hasher, RNGState &rng, SteadyClock::duration dur) noexcept
Extract entropy from rng, strengthen it, and feed it into hasher.
uint256 rand256() noexcept
generate a random uint256.
void RandAddPeriodic() noexcept
Gather entropy from various expensive sources, and feed them to the PRNG state.
FastRandomContext(bool fDeterministic=false) noexcept
Called by RandAddPeriodic()
void Keystream(Span< std::byte > out) noexcept
outputs the keystream to out.
void Finalize(unsigned char hash[OUTPUT_SIZE])
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...
static void SeedFast(CSHA512 &hasher) noexcept
static void RandFailure()
void memory_cleanse(void *ptr, size_t len)
Secure overwrite a buffer (possibly containing secret data) with zero-bytes.
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. ...
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).
void fillrand(Span< std::byte > output)
Fill a byte Span with random bytes.
static void SeedStartup(CSHA512 &hasher, RNGState &rng) noexcept
Automatically called by GetStrongRandBytes.
static constexpr size_t OUTPUT_SIZE
static constexpr std::array< std::byte, ChaCha20::KEYLEN > ZERO_KEY
std::vector< B > randbytes(size_t len)
Generate random bytes.
static void SeedPeriodic(CSHA512 &hasher, RNGState &rng) noexcept
Automatically called by GetRandBytes.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
static void ReportHardwareRand()
static void SeedSlow(CSHA512 &hasher, RNGState &rng) noexcept
CSHA512 & Write(const unsigned char *data, size_t len)
Span< const std::byte > MakeByteSpan(V &&v) noexcept
void GetRandBytes(Span< unsigned char > bytes) noexcept
Overall design of the RNG and entropy sources.
A Span is an object that can refer to a contiguous sequence of objects.
A hasher class for SHA-512.
bool g_mock_deterministic_tests
Flag to make GetRand in random.h return the same number.
static void SeedHardwareFast(CSHA512 &hasher) noexcept
Add 64 bits of entropy gathered from hardware to hasher.
A hasher class for SHA-256.
void RandAddStaticEnv(CSHA512 &hasher)
Gather non-cryptographic environment data that does not change over time.
bool Random_SanityCheck()
Check that OS randomness is available and returning the requested number of bytes.
static void InitHardwareRand()
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
void SetKey(Span< const std::byte > key) noexcept
Set 32-byte key, and seek to nonce 0 and block position 0.
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 int64_t GetPerformanceCounter() noexcept
static void SeedTimestamp(CSHA512 &hasher) noexcept
void RandAddDynamicEnv(CSHA512 &hasher)
Gather non-cryptographic environment data that changes over time.