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__) 46 #include <openssl/err.h> 47 #include <openssl/rand.h> 51 LogPrintf(
"Failed to read randomness, aborting\n");
59 #if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64)) 61 #elif !defined(_MSC_VER) && defined(__i386__) 63 __asm__
volatile (
"rdtsc" :
"=A"(r));
65 #elif !defined(_MSC_VER) && (defined(__x86_64__) || defined(__amd64__)) 66 uint64_t r1 = 0, r2 = 0;
67 __asm__
volatile (
"rdtsc" :
"=a"(r1),
"=d"(r2));
68 return (r2 << 32) | r1;
71 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;
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);
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;
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;
134 RAND_add(&nCounter,
sizeof(nCounter), 1.5);
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",
nullptr,
nullptr, 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);
205 HCRYPTPROV hProvider;
206 int ret = CryptAcquireContextW(&hProvider,
nullptr,
nullptr, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
214 CryptReleaseContext(hProvider, 0);
215 #elif defined(HAVE_SYS_GETRANDOM) 223 if (rv < 0 && errno == ENOSYS) {
233 #elif defined(HAVE_GETENTROPY) && defined(__OpenBSD__) 243 #elif defined(HAVE_GETENTROPY_RAND) && defined(MAC_OSX) 245 if (&getentropy !=
nullptr) {
252 #elif defined(HAVE_SYSCTL_ARND) 256 static const int name[2] = {CTL_KERN, KERN_ARND};
275 if (RAND_bytes(buf, num) != 1) {
285 std::this_thread::sleep_for(std::chrono::milliseconds(1));
303 hasher.
Write((
const unsigned char*)&len,
sizeof(len));
304 hasher.
Write((
const unsigned char*)data, len);
305 unsigned char buf[64];
321 unsigned char buf[64];
326 hasher.
Write(buf, 32);
330 hasher.
Write(buf, 32);
334 hasher.
Write(buf, 32);
366 uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax;
370 }
while (nRand >= nRange);
371 return (nRand % nMax);
374 std::chrono::microseconds
GetRandMicros(std::chrono::microseconds duration_max) noexcept
376 return std::chrono::microseconds{
GetRand(duration_max.count())};
397 const uint64_t v = 100000000;
399 return r <= v * rate;
422 std::vector<unsigned char> ret(len);
442 static const ssize_t MAX_TRIES = 1024;
452 overwritten[x] |= (data[x] != 0);
457 if (overwritten[x]) {
458 num_overwritten += 1;
467 std::this_thread::sleep_for(std::chrono::milliseconds(1));
469 if (
stop == start)
return false;
472 RAND_add((
const unsigned char*)&start,
sizeof(start), 1);
473 RAND_add((
const unsigned char*)&
stop,
sizeof(
stop), 1);
480 if (!fDeterministic) {
void GetDevURandom(unsigned char *ent32)
Fallback: get 32 bytes of system entropy from /dev/urandom.
static const int NUM_OS_RANDOM_BYTES
void RandomInit()
Initialize the RNG.
void GetOSRand(unsigned char *ent32)
Get 32 bytes of system entropy.
void RandAddSeedSleep()
Add a little bit of randomness to the output of GetStrongRangBytes.
FastRandomContext(bool fDeterministic=false)
static std::mutex cs_rng_state
unsigned char bytebuf[64]
static void WriteLE64(unsigned char *ptr, uint64_t x)
uint64_t randrange(uint64_t range)
Generate a random integer in the range [0..range).
static void WriteLE32(unsigned char *ptr, uint32_t x)
void GetStrongRandBytes(unsigned char *out, int num)
Function to gather random data from multiple sources, failing whenever any of those source fail to pr...
static uint64_t rng_counter
std::chrono::microseconds GetRandMicros(std::chrono::microseconds duration_max) noexcept
static int64_t GetPerformanceCounter()
void Finalize(unsigned char hash[OUTPUT_SIZE])
int64_t GetTime()
Return system time (or mocked time, if set)
static void RandFailure()
void memory_cleanse(void *ptr, size_t len)
bool GetRandBool(double rate)
uint256 rand256()
generate a random uint256.
static unsigned char rng_state[32]
#define LogPrint(category,...)
static bool GetHWRand(unsigned char *ent32)
void Keystream(unsigned char *c, size_t bytes)
outputs the keystream of size <bytes> into
static void AddDataToRng(void *data, size_t len)
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.
A hasher class for SHA-512.
void SetKey(const unsigned char *key, size_t keylen)
set key with flexible keylength; 256bit recommended */
bool g_mock_deterministic_tests
static void RandAddSeedPerfmon()
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)