27 #ifdef HAVE_SYS_GETRANDOM 28 #include <sys/syscall.h> 29 #include <linux/random.h> 31 #if defined(HAVE_GETENTROPY) || (defined(HAVE_GETENTROPY_RAND) && defined(MAC_OSX)) 34 #if defined(HAVE_GETENTROPY_RAND) && defined(MAC_OSX) 35 #include <sys/random.h> 37 #ifdef HAVE_SYSCTL_ARND 38 #include <sys/sysctl.h> 43 #if defined(__x86_64__) || defined(__amd64__) || defined(__i386__) 47 #include <openssl/err.h> 48 #include <openssl/rand.h> 50 [[noreturn]]
static void RandFailure()
52 LogPrintf(
"Failed to read randomness, aborting\n");
56 static inline int64_t GetPerformanceCounter()
60 #if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64)) 62 #elif !defined(_MSC_VER) && defined(__i386__) 64 __asm__
volatile (
"rdtsc" :
"=A"(r));
66 #elif !defined(_MSC_VER) && (defined(__x86_64__) || defined(__amd64__)) 67 uint64_t r1 = 0, r2 = 0;
68 __asm__
volatile (
"rdtsc" :
"=a"(r1),
"=d"(r2));
69 return (r2 << 32) | r1;
72 return std::chrono::high_resolution_clock::now().time_since_epoch().count();
77 #if defined(__x86_64__) || defined(__amd64__) || defined(__i386__) 78 static std::atomic<bool> hwrand_initialized{
false};
79 static bool rdrand_supported =
false;
80 static constexpr uint32_t CPUID_F1_ECX_RDRAND = 0x40000000;
81 static void RDRandInit()
83 uint32_t eax, ebx, ecx, edx;
84 if (__get_cpuid(1, &eax, &ebx, &ecx, &edx) && (ecx & CPUID_F1_ECX_RDRAND)) {
85 LogPrintf(
"Using RdRand as an additional entropy source\n");
86 rdrand_supported =
true;
88 hwrand_initialized.store(
true);
91 static void RDRandInit() {}
94 static bool GetHWRand(
unsigned char* ent32) {
95 #if defined(__x86_64__) || defined(__amd64__) || defined(__i386__) 96 assert(hwrand_initialized.load(std::memory_order_relaxed));
97 if (rdrand_supported) {
101 for (
int iter = 0; iter < 4; ++iter) {
103 __asm__
volatile (
".byte 0x0f, 0xc7, 0xf0;" 104 ".byte 0x0f, 0xc7, 0xf2;" 106 "=a"(r1),
"=d"(r2),
"=q"(ok) ::
"cc");
107 if (!ok)
return false;
108 WriteLE32(ent32 + 8 * iter, r1);
109 WriteLE32(ent32 + 8 * iter + 4, r2);
112 uint64_t r1, r2, r3, r4;
113 __asm__
volatile (
".byte 0x48, 0x0f, 0xc7, 0xf0, " 114 "0x48, 0x0f, 0xc7, 0xf3, " 115 "0x48, 0x0f, 0xc7, 0xf1, " 116 "0x48, 0x0f, 0xc7, 0xf2; " 118 "=a"(r1),
"=b"(r2),
"=c"(r3),
"=d"(r4),
"=q"(ok) ::
"cc");
119 if (!ok)
return false;
120 WriteLE64(ent32, r1);
121 WriteLE64(ent32 + 8, r2);
122 WriteLE64(ent32 + 16, r3);
123 WriteLE64(ent32 + 24, r4);
134 int64_t nCounter = GetPerformanceCounter();
135 RAND_add(&nCounter,
sizeof(nCounter), 1.5);
139 static void RandAddSeedPerfmon()
148 static int64_t nLastPerfmon;
149 if (
GetTime() < nLastPerfmon + 10 * 60)
153 std::vector<unsigned char> vData(250000, 0);
155 unsigned long nSize = 0;
156 const size_t nMaxSize = 10000000;
158 nSize = vData.size();
159 ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA,
"Global",
nullptr,
nullptr, vData.data(), &nSize);
160 if (ret != ERROR_MORE_DATA || vData.size() >= nMaxSize)
162 vData.resize(std::max((vData.size() * 3) / 2, nMaxSize));
164 RegCloseKey(HKEY_PERFORMANCE_DATA);
165 if (ret == ERROR_SUCCESS) {
166 RAND_add(vData.data(), nSize, nSize / 100.0);
170 static bool warned =
false;
172 LogPrintf(
"%s: Warning: RegQueryValueExA(HKEY_PERFORMANCE_DATA) failed with code %i\n", __func__, ret);
185 int f = open(
"/dev/urandom", O_RDONLY);
191 ssize_t n = read(f, ent32 + have, NUM_OS_RANDOM_BYTES - have);
192 if (n <= 0 || n + have > NUM_OS_RANDOM_BYTES) {
197 }
while (have < NUM_OS_RANDOM_BYTES);
206 HCRYPTPROV hProvider;
207 int ret = CryptAcquireContextW(&hProvider,
nullptr,
nullptr, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
211 ret = CryptGenRandom(hProvider, NUM_OS_RANDOM_BYTES, ent32);
215 CryptReleaseContext(hProvider, 0);
216 #elif defined(HAVE_SYS_GETRANDOM) 222 int rv = syscall(SYS_getrandom, ent32, NUM_OS_RANDOM_BYTES, 0);
223 if (rv != NUM_OS_RANDOM_BYTES) {
224 if (rv < 0 && errno == ENOSYS) {
234 #elif defined(HAVE_GETENTROPY) && defined(__OpenBSD__) 241 if (getentropy(ent32, NUM_OS_RANDOM_BYTES) != 0) {
244 #elif defined(HAVE_GETENTROPY_RAND) && defined(MAC_OSX) 246 if (&getentropy !=
nullptr) {
247 if (getentropy(ent32, NUM_OS_RANDOM_BYTES) != 0) {
253 #elif defined(HAVE_SYSCTL_ARND) 257 static const int name[2] = {CTL_KERN, KERN_ARND};
260 size_t len = NUM_OS_RANDOM_BYTES - have;
261 if (sysctl(name,
ARRAYLEN(name), ent32 + have, &len,
nullptr, 0) != 0) {
265 }
while (have < NUM_OS_RANDOM_BYTES);
276 if (RAND_bytes(buf, num) != 1) {
281 static void AddDataToRng(
void* data,
size_t len);
285 int64_t nPerfCounter1 = GetPerformanceCounter();
286 std::this_thread::sleep_for(std::chrono::milliseconds(1));
287 int64_t nPerfCounter2 = GetPerformanceCounter();
290 AddDataToRng(&nPerfCounter1,
sizeof(nPerfCounter1));
291 AddDataToRng(&nPerfCounter2,
sizeof(nPerfCounter2));
298 static std::mutex cs_rng_state;
299 static unsigned char rng_state[32] = {0};
300 static uint64_t rng_counter = 0;
302 static void AddDataToRng(
void* data,
size_t len) {
304 hasher.
Write((
const unsigned char*)&len,
sizeof(len));
305 hasher.
Write((
const unsigned char*)data, len);
306 unsigned char buf[64];
308 std::unique_lock<std::mutex> lock(cs_rng_state);
309 hasher.
Write(rng_state,
sizeof(rng_state));
310 hasher.
Write((
const unsigned char*)&rng_counter,
sizeof(rng_counter));
313 memcpy(rng_state, buf + 32, 32);
322 unsigned char buf[64];
325 RandAddSeedPerfmon();
327 hasher.
Write(buf, 32);
331 hasher.
Write(buf, 32);
334 if (GetHWRand(buf)) {
335 hasher.
Write(buf, 32);
340 std::unique_lock<std::mutex> lock(cs_rng_state);
341 hasher.
Write(rng_state,
sizeof(rng_state));
342 hasher.
Write((
const unsigned char*)&rng_counter,
sizeof(rng_counter));
345 memcpy(rng_state, buf + 32, 32);
360 uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax;
364 }
while (nRand >= nRange);
365 return (nRand % nMax);
400 std::vector<unsigned char> ret(len);
414 uint64_t start = GetPerformanceCounter();
420 static const ssize_t MAX_TRIES = 1024;
421 uint8_t data[NUM_OS_RANDOM_BYTES];
422 bool overwritten[NUM_OS_RANDOM_BYTES] = {};
427 memset(data, 0, NUM_OS_RANDOM_BYTES);
429 for (
int x=0; x < NUM_OS_RANDOM_BYTES; ++x) {
430 overwritten[x] |= (data[x] != 0);
434 for (
int x=0; x < NUM_OS_RANDOM_BYTES; ++x) {
435 if (overwritten[x]) {
436 num_overwritten += 1;
441 }
while (num_overwritten < NUM_OS_RANDOM_BYTES && tries < MAX_TRIES);
442 if (num_overwritten != NUM_OS_RANDOM_BYTES)
return false;
445 std::this_thread::sleep_for(std::chrono::milliseconds(1));
446 uint64_t
stop = GetPerformanceCounter();
447 if (stop == start)
return false;
450 RAND_add((
const unsigned char*)&start,
sizeof(start), 1);
451 RAND_add((
const unsigned char*)&stop,
sizeof(stop), 1);
458 if (!fDeterministic) {
void GetDevURandom(unsigned char *ent32)
Fallback: get 32 bytes of system entropy from /dev/urandom.
void RandomInit()
Initialize the RNG.
void GetOSRand(unsigned char *ent32)
Get 32 bytes of system entropy.
void Output(unsigned char *output, size_t bytes)
void RandAddSeedSleep()
Add a little bit of randomness to the output of GetStrongRangBytes.
FastRandomContext(bool fDeterministic=false)
unsigned char bytebuf[64]
void GetStrongRandBytes(unsigned char *out, int num)
Function to gather random data from multiple sources, failing whenever any of those source fail to pr...
void Finalize(unsigned char hash[OUTPUT_SIZE])
void memory_cleanse(void *ptr, size_t len)
uint256 rand256()
generate a random uint256.
#define LogPrint(category,...)
void * memcpy(void *a, const void *b, size_t c)
CSHA512 & Write(const unsigned char *data, size_t len)
void GetRandBytes(unsigned char *buf, int num)
Functions to gather random data via the OpenSSL PRNG.
int64_t GetTime()
GetTimeMicros() and GetTimeMillis() both return the system time, but in different units...
A hasher class for SHA-512.
void SetKey(const unsigned char *key, size_t keylen)
bool Random_SanityCheck()
Check that OS randomness is available and returning the requested number of bytes.
std::vector< unsigned char > randbytes(size_t len)
Generate random bytes.
UniValue stop(const JSONRPCRequest &jsonRequest)
uint64_t GetRand(uint64_t nMax)