Bitcoin Core  24.1.0
P2P Digital Currency
random.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2021 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include <random.h>
7 
8 #include <compat/cpuid.h>
9 #include <crypto/sha256.h>
10 #include <crypto/sha512.h>
11 #include <support/cleanse.h>
12 #ifdef WIN32
13 #include <compat/compat.h>
14 #include <wincrypt.h>
15 #endif
16 #include <logging.h>
17 #include <randomenv.h>
19 #include <span.h>
20 #include <sync.h> // for Mutex
21 #include <util/time.h> // for GetTimeMicros()
22 
23 #include <cmath>
24 #include <stdlib.h>
25 #include <thread>
26 
27 #ifndef WIN32
28 #include <fcntl.h>
29 #include <sys/time.h>
30 #endif
31 
32 #ifdef HAVE_SYS_GETRANDOM
33 #include <sys/syscall.h>
34 #include <linux/random.h>
35 #endif
36 #if defined(HAVE_GETENTROPY_RAND) && defined(MAC_OSX)
37 #include <unistd.h>
38 #include <sys/random.h>
39 #endif
40 #ifdef HAVE_SYSCTL_ARND
41 #include <sys/sysctl.h>
42 #endif
43 
44 [[noreturn]] static void RandFailure()
45 {
46  LogPrintf("Failed to read randomness, aborting\n");
47  std::abort();
48 }
49 
50 static inline int64_t GetPerformanceCounter() noexcept
51 {
52  // Read the hardware time stamp counter when available.
53  // See https://en.wikipedia.org/wiki/Time_Stamp_Counter for more information.
54 #if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64))
55  return __rdtsc();
56 #elif !defined(_MSC_VER) && defined(__i386__)
57  uint64_t r = 0;
58  __asm__ volatile ("rdtsc" : "=A"(r)); // Constrain the r variable to the eax:edx pair.
59  return r;
60 #elif !defined(_MSC_VER) && (defined(__x86_64__) || defined(__amd64__))
61  uint64_t r1 = 0, r2 = 0;
62  __asm__ volatile ("rdtsc" : "=a"(r1), "=d"(r2)); // Constrain r1 to rax and r2 to rdx.
63  return (r2 << 32) | r1;
64 #else
65  // Fall back to using C++11 clock (usually microsecond or nanosecond precision)
66  return std::chrono::high_resolution_clock::now().time_since_epoch().count();
67 #endif
68 }
69 
70 #ifdef HAVE_GETCPUID
71 static bool g_rdrand_supported = false;
72 static bool g_rdseed_supported = false;
73 static constexpr uint32_t CPUID_F1_ECX_RDRAND = 0x40000000;
74 static constexpr uint32_t CPUID_F7_EBX_RDSEED = 0x00040000;
75 #ifdef bit_RDRND
76 static_assert(CPUID_F1_ECX_RDRAND == bit_RDRND, "Unexpected value for bit_RDRND");
77 #endif
78 #ifdef bit_RDSEED
79 static_assert(CPUID_F7_EBX_RDSEED == bit_RDSEED, "Unexpected value for bit_RDSEED");
80 #endif
81 
82 static void InitHardwareRand()
83 {
84  uint32_t eax, ebx, ecx, edx;
85  GetCPUID(1, 0, eax, ebx, ecx, edx);
86  if (ecx & CPUID_F1_ECX_RDRAND) {
87  g_rdrand_supported = true;
88  }
89  GetCPUID(7, 0, eax, ebx, ecx, edx);
90  if (ebx & CPUID_F7_EBX_RDSEED) {
91  g_rdseed_supported = true;
92  }
93 }
94 
95 static void ReportHardwareRand()
96 {
97  // This must be done in a separate function, as InitHardwareRand() may be indirectly called
98  // from global constructors, before logging is initialized.
99  if (g_rdseed_supported) {
100  LogPrintf("Using RdSeed as an additional entropy source\n");
101  }
102  if (g_rdrand_supported) {
103  LogPrintf("Using RdRand as an additional entropy source\n");
104  }
105 }
106 
111 static uint64_t GetRdRand() noexcept
112 {
113  // RdRand may very rarely fail. Invoke it up to 10 times in a loop to reduce this risk.
114 #ifdef __i386__
115  uint8_t ok;
116  // Initialize to 0 to silence a compiler warning that r1 or r2 may be used
117  // uninitialized. Even if rdrand fails (!ok) it will set the output to 0,
118  // but there is no way that the compiler could know that.
119  uint32_t r1 = 0, r2 = 0;
120  for (int i = 0; i < 10; ++i) {
121  __asm__ volatile (".byte 0x0f, 0xc7, 0xf0; setc %1" : "=a"(r1), "=q"(ok) :: "cc"); // rdrand %eax
122  if (ok) break;
123  }
124  for (int i = 0; i < 10; ++i) {
125  __asm__ volatile (".byte 0x0f, 0xc7, 0xf0; setc %1" : "=a"(r2), "=q"(ok) :: "cc"); // rdrand %eax
126  if (ok) break;
127  }
128  return (((uint64_t)r2) << 32) | r1;
129 #elif defined(__x86_64__) || defined(__amd64__)
130  uint8_t ok;
131  uint64_t r1 = 0; // See above why we initialize to 0.
132  for (int i = 0; i < 10; ++i) {
133  __asm__ volatile (".byte 0x48, 0x0f, 0xc7, 0xf0; setc %1" : "=a"(r1), "=q"(ok) :: "cc"); // rdrand %rax
134  if (ok) break;
135  }
136  return r1;
137 #else
138 #error "RdRand is only supported on x86 and x86_64"
139 #endif
140 }
141 
146 static uint64_t GetRdSeed() noexcept
147 {
148  // RdSeed may fail when the HW RNG is overloaded. Loop indefinitely until enough entropy is gathered,
149  // but pause after every failure.
150 #ifdef __i386__
151  uint8_t ok;
152  uint32_t r1, r2;
153  do {
154  __asm__ volatile (".byte 0x0f, 0xc7, 0xf8; setc %1" : "=a"(r1), "=q"(ok) :: "cc"); // rdseed %eax
155  if (ok) break;
156  __asm__ volatile ("pause");
157  } while(true);
158  do {
159  __asm__ volatile (".byte 0x0f, 0xc7, 0xf8; setc %1" : "=a"(r2), "=q"(ok) :: "cc"); // rdseed %eax
160  if (ok) break;
161  __asm__ volatile ("pause");
162  } while(true);
163  return (((uint64_t)r2) << 32) | r1;
164 #elif defined(__x86_64__) || defined(__amd64__)
165  uint8_t ok;
166  uint64_t r1;
167  do {
168  __asm__ volatile (".byte 0x48, 0x0f, 0xc7, 0xf8; setc %1" : "=a"(r1), "=q"(ok) :: "cc"); // rdseed %rax
169  if (ok) break;
170  __asm__ volatile ("pause");
171  } while(true);
172  return r1;
173 #else
174 #error "RdSeed is only supported on x86 and x86_64"
175 #endif
176 }
177 
178 #else
179 /* Access to other hardware random number generators could be added here later,
180  * assuming it is sufficiently fast (in the order of a few hundred CPU cycles).
181  * Slower sources should probably be invoked separately, and/or only from
182  * RandAddPeriodic (which is called once a minute).
183  */
184 static void InitHardwareRand() {}
185 static void ReportHardwareRand() {}
186 #endif
187 
189 static void SeedHardwareFast(CSHA512& hasher) noexcept {
190 #if defined(__x86_64__) || defined(__amd64__) || defined(__i386__)
191  if (g_rdrand_supported) {
192  uint64_t out = GetRdRand();
193  hasher.Write((const unsigned char*)&out, sizeof(out));
194  return;
195  }
196 #endif
197 }
198 
200 static void SeedHardwareSlow(CSHA512& hasher) noexcept {
201 #if defined(__x86_64__) || defined(__amd64__) || defined(__i386__)
202  // When we want 256 bits of entropy, prefer RdSeed over RdRand, as it's
203  // guaranteed to produce independent randomness on every call.
204  if (g_rdseed_supported) {
205  for (int i = 0; i < 4; ++i) {
206  uint64_t out = GetRdSeed();
207  hasher.Write((const unsigned char*)&out, sizeof(out));
208  }
209  return;
210  }
211  // When falling back to RdRand, XOR the result of 1024 results.
212  // This guarantees a reseeding occurs between each.
213  if (g_rdrand_supported) {
214  for (int i = 0; i < 4; ++i) {
215  uint64_t out = 0;
216  for (int j = 0; j < 1024; ++j) out ^= GetRdRand();
217  hasher.Write((const unsigned char*)&out, sizeof(out));
218  }
219  return;
220  }
221 #endif
222 }
223 
225 static void Strengthen(const unsigned char (&seed)[32], int microseconds, CSHA512& hasher) noexcept
226 {
227  CSHA512 inner_hasher;
228  inner_hasher.Write(seed, sizeof(seed));
229 
230  // Hash loop
231  unsigned char buffer[64];
232  int64_t stop = GetTimeMicros() + microseconds;
233  do {
234  for (int i = 0; i < 1000; ++i) {
235  inner_hasher.Finalize(buffer);
236  inner_hasher.Reset();
237  inner_hasher.Write(buffer, sizeof(buffer));
238  }
239  // Benchmark operation and feed it into outer hasher.
240  int64_t perf = GetPerformanceCounter();
241  hasher.Write((const unsigned char*)&perf, sizeof(perf));
242  } while (GetTimeMicros() < stop);
243 
244  // Produce output from inner state and feed it to outer hasher.
245  inner_hasher.Finalize(buffer);
246  hasher.Write(buffer, sizeof(buffer));
247  // Try to clean up.
248  inner_hasher.Reset();
249  memory_cleanse(buffer, sizeof(buffer));
250 }
251 
252 #ifndef WIN32
253 
256 static void GetDevURandom(unsigned char *ent32)
257 {
258  int f = open("/dev/urandom", O_RDONLY);
259  if (f == -1) {
260  RandFailure();
261  }
262  int have = 0;
263  do {
264  ssize_t n = read(f, ent32 + have, NUM_OS_RANDOM_BYTES - have);
265  if (n <= 0 || n + have > NUM_OS_RANDOM_BYTES) {
266  close(f);
267  RandFailure();
268  }
269  have += n;
270  } while (have < NUM_OS_RANDOM_BYTES);
271  close(f);
272 }
273 #endif
274 
276 void GetOSRand(unsigned char *ent32)
277 {
278 #if defined(WIN32)
279  HCRYPTPROV hProvider;
280  int ret = CryptAcquireContextW(&hProvider, nullptr, nullptr, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
281  if (!ret) {
282  RandFailure();
283  }
284  ret = CryptGenRandom(hProvider, NUM_OS_RANDOM_BYTES, ent32);
285  if (!ret) {
286  RandFailure();
287  }
288  CryptReleaseContext(hProvider, 0);
289 #elif defined(HAVE_SYS_GETRANDOM)
290  /* Linux. From the getrandom(2) man page:
291  * "If the urandom source has been initialized, reads of up to 256 bytes
292  * will always return as many bytes as requested and will not be
293  * interrupted by signals."
294  */
295  int rv = syscall(SYS_getrandom, ent32, NUM_OS_RANDOM_BYTES, 0);
296  if (rv != NUM_OS_RANDOM_BYTES) {
297  if (rv < 0 && errno == ENOSYS) {
298  /* Fallback for kernel <3.17: the return value will be -1 and errno
299  * ENOSYS if the syscall is not available, in that case fall back
300  * to /dev/urandom.
301  */
302  GetDevURandom(ent32);
303  } else {
304  RandFailure();
305  }
306  }
307 #elif defined(__OpenBSD__)
308  /* OpenBSD. From the arc4random(3) man page:
309  "Use of these functions is encouraged for almost all random number
310  consumption because the other interfaces are deficient in either
311  quality, portability, standardization, or availability."
312  The function call is always successful.
313  */
314  arc4random_buf(ent32, NUM_OS_RANDOM_BYTES);
315  // Silence a compiler warning about unused function.
316  (void)GetDevURandom;
317 #elif defined(HAVE_GETENTROPY_RAND) && defined(MAC_OSX)
318  /* getentropy() is available on macOS 10.12 and later.
319  */
320  if (getentropy(ent32, NUM_OS_RANDOM_BYTES) != 0) {
321  RandFailure();
322  }
323  // Silence a compiler warning about unused function.
324  (void)GetDevURandom;
325 #elif defined(HAVE_SYSCTL_ARND)
326  /* FreeBSD, NetBSD and similar. It is possible for the call to return less
327  * bytes than requested, so need to read in a loop.
328  */
329  static int name[2] = {CTL_KERN, KERN_ARND};
330  int have = 0;
331  do {
332  size_t len = NUM_OS_RANDOM_BYTES - have;
333  if (sysctl(name, std::size(name), ent32 + have, &len, nullptr, 0) != 0) {
334  RandFailure();
335  }
336  have += len;
337  } while (have < NUM_OS_RANDOM_BYTES);
338  // Silence a compiler warning about unused function.
339  (void)GetDevURandom;
340 #else
341  /* Fall back to /dev/urandom if there is no specific method implemented to
342  * get system entropy for this OS.
343  */
344  GetDevURandom(ent32);
345 #endif
346 }
347 
348 namespace {
349 
350 class RNGState {
351  Mutex m_mutex;
352  /* The RNG state consists of 256 bits of entropy, taken from the output of
353  * one operation's SHA512 output, and fed as input to the next one.
354  * Carrying 256 bits of entropy should be sufficient to guarantee
355  * unpredictability as long as any entropy source was ever unpredictable
356  * to an attacker. To protect against situations where an attacker might
357  * observe the RNG's state, fresh entropy is always mixed when
358  * GetStrongRandBytes is called.
359  */
360  unsigned char m_state[32] GUARDED_BY(m_mutex) = {0};
361  uint64_t m_counter GUARDED_BY(m_mutex) = 0;
362  bool m_strongly_seeded GUARDED_BY(m_mutex) = false;
363 
364  Mutex m_events_mutex;
365  CSHA256 m_events_hasher GUARDED_BY(m_events_mutex);
366 
367 public:
368  RNGState() noexcept
369  {
371  }
372 
373  ~RNGState() = default;
374 
375  void AddEvent(uint32_t event_info) noexcept EXCLUSIVE_LOCKS_REQUIRED(!m_events_mutex)
376  {
377  LOCK(m_events_mutex);
378 
379  m_events_hasher.Write((const unsigned char *)&event_info, sizeof(event_info));
380  // Get the low four bytes of the performance counter. This translates to roughly the
381  // subsecond part.
382  uint32_t perfcounter = (GetPerformanceCounter() & 0xffffffff);
383  m_events_hasher.Write((const unsigned char*)&perfcounter, sizeof(perfcounter));
384  }
385 
389  void SeedEvents(CSHA512& hasher) noexcept EXCLUSIVE_LOCKS_REQUIRED(!m_events_mutex)
390  {
391  // We use only SHA256 for the events hashing to get the ASM speedups we have for SHA256,
392  // since we want it to be fast as network peers may be able to trigger it repeatedly.
393  LOCK(m_events_mutex);
394 
395  unsigned char events_hash[32];
396  m_events_hasher.Finalize(events_hash);
397  hasher.Write(events_hash, 32);
398 
399  // Re-initialize the hasher with the finalized state to use later.
400  m_events_hasher.Reset();
401  m_events_hasher.Write(events_hash, 32);
402  }
403 
408  bool MixExtract(unsigned char* out, size_t num, CSHA512&& hasher, bool strong_seed) noexcept EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
409  {
410  assert(num <= 32);
411  unsigned char buf[64];
412  static_assert(sizeof(buf) == CSHA512::OUTPUT_SIZE, "Buffer needs to have hasher's output size");
413  bool ret;
414  {
415  LOCK(m_mutex);
416  ret = (m_strongly_seeded |= strong_seed);
417  // Write the current state of the RNG into the hasher
418  hasher.Write(m_state, 32);
419  // Write a new counter number into the state
420  hasher.Write((const unsigned char*)&m_counter, sizeof(m_counter));
421  ++m_counter;
422  // Finalize the hasher
423  hasher.Finalize(buf);
424  // Store the last 32 bytes of the hash output as new RNG state.
425  memcpy(m_state, buf + 32, 32);
426  }
427  // If desired, copy (up to) the first 32 bytes of the hash output as output.
428  if (num) {
429  assert(out != nullptr);
430  memcpy(out, buf, num);
431  }
432  // Best effort cleanup of internal state
433  hasher.Reset();
434  memory_cleanse(buf, 64);
435  return ret;
436  }
437 };
438 
439 RNGState& GetRNGState() noexcept
440 {
441  // This C++11 idiom relies on the guarantee that static variable are initialized
442  // on first call, even when multiple parallel calls are permitted.
443  static std::vector<RNGState, secure_allocator<RNGState>> g_rng(1);
444  return g_rng[0];
445 }
446 }
447 
448 /* A note on the use of noexcept in the seeding functions below:
449  *
450  * None of the RNG code should ever throw any exception.
451  */
452 
453 static void SeedTimestamp(CSHA512& hasher) noexcept
454 {
455  int64_t perfcounter = GetPerformanceCounter();
456  hasher.Write((const unsigned char*)&perfcounter, sizeof(perfcounter));
457 }
458 
459 static void SeedFast(CSHA512& hasher) noexcept
460 {
461  unsigned char buffer[32];
462 
463  // Stack pointer to indirectly commit to thread/callstack
464  const unsigned char* ptr = buffer;
465  hasher.Write((const unsigned char*)&ptr, sizeof(ptr));
466 
467  // Hardware randomness is very fast when available; use it always.
468  SeedHardwareFast(hasher);
469 
470  // High-precision timestamp
471  SeedTimestamp(hasher);
472 }
473 
474 static void SeedSlow(CSHA512& hasher, RNGState& rng) noexcept
475 {
476  unsigned char buffer[32];
477 
478  // Everything that the 'fast' seeder includes
479  SeedFast(hasher);
480 
481  // OS randomness
482  GetOSRand(buffer);
483  hasher.Write(buffer, sizeof(buffer));
484 
485  // Add the events hasher into the mix
486  rng.SeedEvents(hasher);
487 
488  // High-precision timestamp.
489  //
490  // Note that we also commit to a timestamp in the Fast seeder, so we indirectly commit to a
491  // benchmark of all the entropy gathering sources in this function).
492  SeedTimestamp(hasher);
493 }
494 
496 static void SeedStrengthen(CSHA512& hasher, RNGState& rng, int microseconds) noexcept
497 {
498  // Generate 32 bytes of entropy from the RNG, and a copy of the entropy already in hasher.
499  unsigned char strengthen_seed[32];
500  rng.MixExtract(strengthen_seed, sizeof(strengthen_seed), CSHA512(hasher), false);
501  // Strengthen the seed, and feed it into hasher.
502  Strengthen(strengthen_seed, microseconds, hasher);
503 }
504 
505 static void SeedPeriodic(CSHA512& hasher, RNGState& rng) noexcept
506 {
507  // Everything that the 'fast' seeder includes
508  SeedFast(hasher);
509 
510  // High-precision timestamp
511  SeedTimestamp(hasher);
512 
513  // Add the events hasher into the mix
514  rng.SeedEvents(hasher);
515 
516  // Dynamic environment data (performance monitoring, ...)
517  auto old_size = hasher.Size();
518  RandAddDynamicEnv(hasher);
519  LogPrint(BCLog::RAND, "Feeding %i bytes of dynamic environment data into RNG\n", hasher.Size() - old_size);
520 
521  // Strengthen for 10 ms
522  SeedStrengthen(hasher, rng, 10000);
523 }
524 
525 static void SeedStartup(CSHA512& hasher, RNGState& rng) noexcept
526 {
527  // Gather 256 bits of hardware randomness, if available
528  SeedHardwareSlow(hasher);
529 
530  // Everything that the 'slow' seeder includes.
531  SeedSlow(hasher, rng);
532 
533  // Dynamic environment data (performance monitoring, ...)
534  auto old_size = hasher.Size();
535  RandAddDynamicEnv(hasher);
536 
537  // Static environment data
538  RandAddStaticEnv(hasher);
539  LogPrint(BCLog::RAND, "Feeding %i bytes of environment data into RNG\n", hasher.Size() - old_size);
540 
541  // Strengthen for 100 ms
542  SeedStrengthen(hasher, rng, 100000);
543 }
544 
545 enum class RNGLevel {
546  FAST,
547  SLOW,
548  PERIODIC,
549 };
550 
551 static void ProcRand(unsigned char* out, int num, RNGLevel level) noexcept
552 {
553  // Make sure the RNG is initialized first (as all Seed* function possibly need hwrand to be available).
554  RNGState& rng = GetRNGState();
555 
556  assert(num <= 32);
557 
558  CSHA512 hasher;
559  switch (level) {
560  case RNGLevel::FAST:
561  SeedFast(hasher);
562  break;
563  case RNGLevel::SLOW:
564  SeedSlow(hasher, rng);
565  break;
566  case RNGLevel::PERIODIC:
567  SeedPeriodic(hasher, rng);
568  break;
569  }
570 
571  // Combine with and update state
572  if (!rng.MixExtract(out, num, std::move(hasher), false)) {
573  // On the first invocation, also seed with SeedStartup().
574  CSHA512 startup_hasher;
575  SeedStartup(startup_hasher, rng);
576  rng.MixExtract(out, num, std::move(startup_hasher), true);
577  }
578 }
579 
580 void GetRandBytes(Span<unsigned char> bytes) noexcept { ProcRand(bytes.data(), bytes.size(), RNGLevel::FAST); }
581 void GetStrongRandBytes(Span<unsigned char> bytes) noexcept { ProcRand(bytes.data(), bytes.size(), RNGLevel::SLOW); }
582 void RandAddPeriodic() noexcept { ProcRand(nullptr, 0, RNGLevel::PERIODIC); }
583 void RandAddEvent(const uint32_t event_info) noexcept { GetRNGState().AddEvent(event_info); }
584 
586 
587 uint64_t GetRandInternal(uint64_t nMax) noexcept
588 {
590 }
591 
593 {
594  uint256 hash;
595  GetRandBytes(hash);
596  return hash;
597 }
598 
600 {
601  uint256 seed = GetRandHash();
602  rng.SetKey(seed.begin(), 32);
603  requires_seed = false;
604 }
605 
607 {
608  if (bytebuf_size < 32) {
609  FillByteBuffer();
610  }
611  uint256 ret;
612  memcpy(ret.begin(), bytebuf + 64 - bytebuf_size, 32);
613  bytebuf_size -= 32;
614  return ret;
615 }
616 
617 std::vector<unsigned char> FastRandomContext::randbytes(size_t len)
618 {
619  if (requires_seed) RandomSeed();
620  std::vector<unsigned char> ret(len);
621  if (len > 0) {
622  rng.Keystream(ret.data(), len);
623  }
624  return ret;
625 }
626 
627 FastRandomContext::FastRandomContext(const uint256& seed) noexcept : requires_seed(false), bytebuf_size(0), bitbuf_size(0)
628 {
629  rng.SetKey(seed.begin(), 32);
630 }
631 
633 {
634  uint64_t start = GetPerformanceCounter();
635 
636  /* This does not measure the quality of randomness, but it does test that
637  * GetOSRand() overwrites all 32 bytes of the output given a maximum
638  * number of tries.
639  */
640  static const ssize_t MAX_TRIES = 1024;
641  uint8_t data[NUM_OS_RANDOM_BYTES];
642  bool overwritten[NUM_OS_RANDOM_BYTES] = {}; /* Tracks which bytes have been overwritten at least once */
643  int num_overwritten;
644  int tries = 0;
645  /* Loop until all bytes have been overwritten at least once, or max number tries reached */
646  do {
647  memset(data, 0, NUM_OS_RANDOM_BYTES);
648  GetOSRand(data);
649  for (int x=0; x < NUM_OS_RANDOM_BYTES; ++x) {
650  overwritten[x] |= (data[x] != 0);
651  }
652 
653  num_overwritten = 0;
654  for (int x=0; x < NUM_OS_RANDOM_BYTES; ++x) {
655  if (overwritten[x]) {
656  num_overwritten += 1;
657  }
658  }
659 
660  tries += 1;
661  } while (num_overwritten < NUM_OS_RANDOM_BYTES && tries < MAX_TRIES);
662  if (num_overwritten != NUM_OS_RANDOM_BYTES) return false; /* If this failed, bailed out after too many tries */
663 
664  // Check that GetPerformanceCounter increases at least during a GetOSRand() call + 1ms sleep.
665  std::this_thread::sleep_for(std::chrono::milliseconds(1));
666  uint64_t stop = GetPerformanceCounter();
667  if (stop == start) return false;
668 
669  // We called GetPerformanceCounter. Use it as entropy.
670  CSHA512 to_add;
671  to_add.Write((const unsigned char*)&start, sizeof(start));
672  to_add.Write((const unsigned char*)&stop, sizeof(stop));
673  GetRNGState().MixExtract(nullptr, 0, std::move(to_add), false);
674 
675  return true;
676 }
677 
678 FastRandomContext::FastRandomContext(bool fDeterministic) noexcept : requires_seed(!fDeterministic), bytebuf_size(0), bitbuf_size(0)
679 {
680  if (!fDeterministic) {
681  return;
682  }
683  uint256 seed;
684  rng.SetKey(seed.begin(), 32);
685 }
686 
688 {
689  requires_seed = from.requires_seed;
690  rng = from.rng;
691  std::copy(std::begin(from.bytebuf), std::end(from.bytebuf), std::begin(bytebuf));
692  bytebuf_size = from.bytebuf_size;
693  bitbuf = from.bitbuf;
694  bitbuf_size = from.bitbuf_size;
695  from.requires_seed = true;
696  from.bytebuf_size = 0;
697  from.bitbuf_size = 0;
698  return *this;
699 }
700 
702 {
703  // Invoke RNG code to trigger initialization (if not already performed)
704  ProcRand(nullptr, 0, RNGLevel::FAST);
705 
707 }
708 
709 std::chrono::microseconds GetExponentialRand(std::chrono::microseconds now, std::chrono::seconds average_interval)
710 {
711  double unscaled = -std::log1p(GetRand(uint64_t{1} << 48) * -0.0000000000000035527136788 /* -1/2^48 */);
712  return now + std::chrono::duration_cast<std::chrono::microseconds>(unscaled * average_interval + 0.5us);
713 }
static const int NUM_OS_RANDOM_BYTES
Definition: random.h:288
void RandomInit()
Initialize global RNG state and log any CPU features that are used.
Definition: random.cpp:701
void GetOSRand(unsigned char *ent32)
Get 32 bytes of system entropy.
Definition: random.cpp:276
void RandAddEvent(const uint32_t event_info) noexcept
Gathers entropy from the low bits of the time at which events occur.
Definition: random.cpp:583
int ret
uint64_t GetRandInternal(uint64_t nMax) noexcept
Generate a uniform random integer in the range [0..range).
Definition: random.cpp:587
#define LogPrint(category,...)
Definition: logging.h:243
assert(!tx.IsCoinBase())
unsigned char bytebuf[64]
Definition: random.h:148
FastRandomContext & operator=(const FastRandomContext &)=delete
uint256 GetRandHash() noexcept
Definition: random.cpp:592
static void SeedHardwareSlow(CSHA512 &hasher) noexcept
Add 256 bits of entropy gathered from hardware to hasher.
Definition: random.cpp:200
static void ProcRand(unsigned char *out, int num, RNGLevel level) noexcept
Definition: random.cpp:551
static void GetDevURandom(unsigned char *ent32)
Fallback: get 32 bytes of system entropy from /dev/urandom.
Definition: random.cpp:256
uint256 rand256() noexcept
generate a random uint256.
Definition: random.cpp:606
void RandAddPeriodic() noexcept
Gather entropy from various expensive sources, and feed them to the PRNG state.
Definition: random.cpp:582
FastRandomContext(bool fDeterministic=false) noexcept
Definition: random.cpp:678
static void Strengthen(const unsigned char(&seed)[32], int microseconds, CSHA512 &hasher) noexcept
Use repeated SHA512 to strengthen the randomness in seed32, and feed into hasher. ...
Definition: random.cpp:225
static void SeedStrengthen(CSHA512 &hasher, RNGState &rng, int microseconds) noexcept
Extract entropy from rng, strengthen it, and feed it into hasher.
Definition: random.cpp:496
unsigned char * begin()
Definition: uint256.h:61
void FillByteBuffer()
Definition: random.h:156
Called by RandAddPeriodic()
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: sha512.cpp:185
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...
Definition: random.h:79
RNGLevel
Definition: random.cpp:545
static void SeedFast(CSHA512 &hasher) noexcept
Definition: random.cpp:459
static void RandFailure()
Definition: random.cpp:44
void memory_cleanse(void *ptr, size_t len)
Secure overwrite a buffer (possibly containing secret data) with zero-bytes.
Definition: cleanse.cpp:14
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).
Definition: random.cpp:709
#define LOCK(cs)
Definition: sync.h:261
const char * name
Definition: rest.cpp:46
Fast randomness source.
Definition: random.h:142
CSHA512 & Reset()
Definition: sha512.cpp:202
static void SeedStartup(CSHA512 &hasher, RNGState &rng) noexcept
Definition: random.cpp:525
void RandomSeed()
Definition: random.cpp:599
Automatically called by GetStrongRandBytes.
static constexpr size_t OUTPUT_SIZE
Definition: sha512.h:20
static RPCHelpMan stop()
Definition: server.cpp:162
static void SeedPeriodic(CSHA512 &hasher, RNGState &rng) noexcept
Definition: random.cpp:505
int64_t GetTimeMicros()
Returns the system time (not mockable)
Definition: time.cpp:112
bool requires_seed
Definition: random.h:145
256-bit opaque blob.
Definition: uint256.h:119
Automatically called by GetRandBytes.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
static void ReportHardwareRand()
Definition: random.cpp:185
static void SeedSlow(CSHA512 &hasher, RNGState &rng) noexcept
Definition: random.cpp:474
void Keystream(unsigned char *c, size_t bytes)
outputs the keystream of size <bytes> into
Definition: chacha20.cpp:76
CSHA512 & Write(const unsigned char *data, size_t len)
Definition: sha512.cpp:159
#define GUARDED_BY(x)
Definition: threadsafety.h:38
void GetRandBytes(Span< unsigned char > bytes) noexcept
Overall design of the RNG and entropy sources.
Definition: random.cpp:580
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:96
A hasher class for SHA-512.
Definition: sha512.h:12
ChaCha20 rng
Definition: random.h:146
void SetKey(const unsigned char *key, size_t keylen)
set key with flexible keylength; 256bit recommended */
Definition: chacha20.cpp:26
bool g_mock_deterministic_tests
Flag to make GetRand in random.h return the same number.
Definition: random.cpp:585
static void SeedHardwareFast(CSHA512 &hasher) noexcept
Add 64 bits of entropy gathered from hardware to hasher.
Definition: random.cpp:189
A hasher class for SHA-256.
Definition: sha256.h:13
#define LogPrintf(...)
Definition: logging.h:234
void RandAddStaticEnv(CSHA512 &hasher)
Gather non-cryptographic environment data that does not change over time.
Definition: randomenv.cpp:306
bool Random_SanityCheck()
Check that OS randomness is available and returning the requested number of bytes.
Definition: random.cpp:632
static void InitHardwareRand()
Definition: random.cpp:184
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
Definition: random.h:213
std::vector< unsigned char > randbytes(size_t len)
Generate random bytes.
Definition: random.cpp:617
void GetStrongRandBytes(Span< unsigned char > bytes) noexcept
Gather entropy from various sources, feed it into the internal PRNG, and generate random data using i...
Definition: random.cpp:581
static int64_t GetPerformanceCounter() noexcept
Definition: random.cpp:50
static void SeedTimestamp(CSHA512 &hasher) noexcept
Definition: random.cpp:453
void RandAddDynamicEnv(CSHA512 &hasher)
Gather non-cryptographic environment data that changes over time.
Definition: randomenv.cpp:225