26 #ifdef HAVE_SYS_GETRANDOM
27 #include <sys/syscall.h>
28 #include <linux/random.h>
30 #if defined(HAVE_GETENTROPY) || (defined(HAVE_GETENTROPY_RAND) && defined(MAC_OSX))
33 #if defined(HAVE_GETENTROPY_RAND) && defined(MAC_OSX)
34 #include <sys/random.h>
36 #ifdef HAVE_SYSCTL_ARND
37 #include <sys/sysctl.h>
42 #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();
76 #if defined(__x86_64__) || defined(__amd64__) || defined(__i386__)
77 static std::atomic<bool> hwrand_initialized{
false};
78 static bool rdrand_supported =
false;
79 static constexpr uint32_t CPUID_F1_ECX_RDRAND = 0x40000000;
80 static void RDRandInit()
82 uint32_t eax, ebx, ecx, edx;
83 if (__get_cpuid(1, &eax, &ebx, &ecx, &edx) && (ecx & CPUID_F1_ECX_RDRAND)) {
84 LogPrintf(
"Using RdRand as an additional entropy source\n");
85 rdrand_supported =
true;
87 hwrand_initialized.store(
true);
90 static void RDRandInit() {}
93 static bool GetHWRand(
unsigned char* ent32) {
94 #if defined(__x86_64__) || defined(__amd64__) || defined(__i386__)
95 assert(hwrand_initialized.load(std::memory_order_relaxed));
96 if (rdrand_supported) {
100 for (
int iter = 0; iter < 4; ++iter) {
102 __asm__
volatile (
".byte 0x0f, 0xc7, 0xf0;"
103 ".byte 0x0f, 0xc7, 0xf2;"
105 "=a"(r1),
"=d"(r2),
"=q"(ok) ::
"cc");
106 if (!ok)
return false;
107 WriteLE32(ent32 + 8 * iter, r1);
108 WriteLE32(ent32 + 8 * iter + 4, r2);
111 uint64_t r1, r2, r3, r4;
112 __asm__
volatile (
".byte 0x48, 0x0f, 0xc7, 0xf0, "
113 "0x48, 0x0f, 0xc7, 0xf3, "
114 "0x48, 0x0f, 0xc7, 0xf1, "
115 "0x48, 0x0f, 0xc7, 0xf2; "
117 "=a"(r1),
"=b"(r2),
"=c"(r3),
"=d"(r4),
"=q"(ok) ::
"cc");
118 if (!ok)
return false;
119 WriteLE64(ent32, r1);
120 WriteLE64(ent32 + 8, r2);
121 WriteLE64(ent32 + 16, r3);
122 WriteLE64(ent32 + 24, r4);
133 int64_t nCounter = GetPerformanceCounter();
134 RAND_add(&nCounter,
sizeof(nCounter), 1.5);
138 static void RandAddSeedPerfmon()
147 static int64_t nLastPerfmon;
148 if (
GetTime() < nLastPerfmon + 10 * 60)
152 std::vector<unsigned char> vData(250000, 0);
154 unsigned long nSize = 0;
155 const size_t nMaxSize = 10000000;
157 nSize = vData.size();
158 ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA,
"Global", NULL, NULL, vData.data(), &nSize);
159 if (ret != ERROR_MORE_DATA || vData.size() >= nMaxSize)
161 vData.resize(std::max((vData.size() * 3) / 2, nMaxSize));
163 RegCloseKey(HKEY_PERFORMANCE_DATA);
164 if (ret == ERROR_SUCCESS) {
165 RAND_add(vData.data(), nSize, nSize / 100.0);
169 static bool warned =
false;
171 LogPrintf(
"%s: Warning: RegQueryValueExA(HKEY_PERFORMANCE_DATA) failed with code %i\n", __func__, ret);
184 int f = open(
"/dev/urandom", O_RDONLY);
190 ssize_t n = read(f, ent32 + have, NUM_OS_RANDOM_BYTES - have);
191 if (n <= 0 || n + have > NUM_OS_RANDOM_BYTES) {
196 }
while (have < NUM_OS_RANDOM_BYTES);
205 HCRYPTPROV hProvider;
206 int ret = CryptAcquireContextW(&hProvider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
210 ret = CryptGenRandom(hProvider, NUM_OS_RANDOM_BYTES, ent32);
214 CryptReleaseContext(hProvider, 0);
215 #elif defined(HAVE_SYS_GETRANDOM)
221 int rv = syscall(SYS_getrandom, ent32, NUM_OS_RANDOM_BYTES, 0);
222 if (rv != NUM_OS_RANDOM_BYTES) {
223 if (rv < 0 && errno == ENOSYS) {
233 #elif defined(HAVE_GETENTROPY) && defined(__OpenBSD__)
240 if (getentropy(ent32, NUM_OS_RANDOM_BYTES) != 0) {
243 #elif defined(HAVE_GETENTROPY_RAND) && defined(MAC_OSX)
245 if (&getentropy != NULL) {
246 if (getentropy(ent32, NUM_OS_RANDOM_BYTES) != 0) {
252 #elif defined(HAVE_SYSCTL_ARND)
256 static const int name[2] = {CTL_KERN, KERN_ARND};
259 size_t len = NUM_OS_RANDOM_BYTES - have;
264 }
while (have < NUM_OS_RANDOM_BYTES);
275 if (RAND_bytes(buf, num) != 1) {
280 static void AddDataToRng(
void* data,
size_t len);
284 int64_t nPerfCounter1 = GetPerformanceCounter();
285 std::this_thread::sleep_for(std::chrono::milliseconds(1));
286 int64_t nPerfCounter2 = GetPerformanceCounter();
289 AddDataToRng(&nPerfCounter1,
sizeof(nPerfCounter1));
290 AddDataToRng(&nPerfCounter2,
sizeof(nPerfCounter2));
296 static std::mutex cs_rng_state;
297 static unsigned char rng_state[32] = {0};
298 static uint64_t rng_counter = 0;
300 static void AddDataToRng(
void* data,
size_t len) {
302 hasher.
Write((
const unsigned char*)&len,
sizeof(len));
303 hasher.
Write((
const unsigned char*)data, len);
304 unsigned char buf[64];
306 std::unique_lock<std::mutex> lock(cs_rng_state);
307 hasher.
Write(rng_state,
sizeof(rng_state));
308 hasher.
Write((
const unsigned char*)&rng_counter,
sizeof(rng_counter));
311 memcpy(rng_state, buf + 32, 32);
320 unsigned char buf[64];
323 RandAddSeedPerfmon();
325 hasher.
Write(buf, 32);
329 hasher.
Write(buf, 32);
332 if (GetHWRand(buf)) {
333 hasher.
Write(buf, 32);
338 std::unique_lock<std::mutex> lock(cs_rng_state);
339 hasher.
Write(rng_state,
sizeof(rng_state));
340 hasher.
Write((
const unsigned char*)&rng_counter,
sizeof(rng_counter));
343 memcpy(rng_state, buf + 32, 32);
358 uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax;
362 }
while (nRand >= nRange);
363 return (nRand % nMax);
399 std::vector<unsigned char> ret(len);
413 uint64_t start = GetPerformanceCounter();
419 static const ssize_t MAX_TRIES = 1024;
420 uint8_t data[NUM_OS_RANDOM_BYTES];
421 bool overwritten[NUM_OS_RANDOM_BYTES] = {};
426 memset(data, 0, NUM_OS_RANDOM_BYTES);
428 for (
int x=0; x < NUM_OS_RANDOM_BYTES; ++x) {
429 overwritten[x] |= (data[x] != 0);
433 for (
int x=0; x < NUM_OS_RANDOM_BYTES; ++x) {
434 if (overwritten[x]) {
435 num_overwritten += 1;
440 }
while (num_overwritten < NUM_OS_RANDOM_BYTES && tries < MAX_TRIES);
441 if (num_overwritten != NUM_OS_RANDOM_BYTES)
return false;
444 std::this_thread::sleep_for(std::chrono::milliseconds(1));
445 uint64_t
stop = GetPerformanceCounter();
446 if (
stop == start)
return false;
449 RAND_add((
const unsigned char*)&start,
sizeof(start), 1);
450 RAND_add((
const unsigned char*)&
stop,
sizeof(
stop), 1);
457 if (!fDeterministic) {
468 std::copy(std::begin(from.bytebuf), std::end(from.bytebuf), std::begin(bytebuf));
469 bytebuf_size = from.bytebuf_size;
470 bitbuf = from.bitbuf;
471 bitbuf_size = from.bitbuf_size;
472 from.requires_seed =
true;
473 from.bytebuf_size = 0;
474 from.bitbuf_size = 0;