Bitcoin Core  0.19.99
P2P Digital Currency
random.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2019 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 #ifndef BITCOIN_RANDOM_H
7 #define BITCOIN_RANDOM_H
8 
9 #include <crypto/chacha20.h>
10 #include <crypto/common.h>
11 #include <uint256.h>
12 
13 #include <chrono> // For std::chrono::microseconds
14 #include <cstdint>
15 #include <limits>
16 
69 void GetRandBytes(unsigned char* buf, int num) noexcept;
70 uint64_t GetRand(uint64_t nMax) noexcept;
71 std::chrono::microseconds GetRandMicros(std::chrono::microseconds duration_max) noexcept;
72 int GetRandInt(int nMax) noexcept;
73 uint256 GetRandHash() noexcept;
74 
83 void GetStrongRandBytes(unsigned char* buf, int num) noexcept;
84 
90 void RandAddPeriodic() noexcept;
91 
98 void RandAddEvent(const uint32_t event_info) noexcept;
99 
107 private:
110 
111  unsigned char bytebuf[64];
113 
114  uint64_t bitbuf;
116 
117  void RandomSeed();
118 
120  {
121  if (requires_seed) {
122  RandomSeed();
123  }
124  rng.Keystream(bytebuf, sizeof(bytebuf));
125  bytebuf_size = sizeof(bytebuf);
126  }
127 
129  {
130  bitbuf = rand64();
131  bitbuf_size = 64;
132  }
133 
134 public:
135  explicit FastRandomContext(bool fDeterministic = false) noexcept;
136 
138  explicit FastRandomContext(const uint256& seed) noexcept;
139 
140  // Do not permit copying a FastRandomContext (move it, or create a new one to get reseeded).
141  FastRandomContext(const FastRandomContext&) = delete;
142  FastRandomContext(FastRandomContext&&) = delete;
143  FastRandomContext& operator=(const FastRandomContext&) = delete;
144 
146  FastRandomContext& operator=(FastRandomContext&& from) noexcept;
147 
149  uint64_t rand64() noexcept
150  {
151  if (bytebuf_size < 8) FillByteBuffer();
152  uint64_t ret = ReadLE64(bytebuf + 64 - bytebuf_size);
153  bytebuf_size -= 8;
154  return ret;
155  }
156 
158  uint64_t randbits(int bits) noexcept {
159  if (bits == 0) {
160  return 0;
161  } else if (bits > 32) {
162  return rand64() >> (64 - bits);
163  } else {
164  if (bitbuf_size < bits) FillBitBuffer();
165  uint64_t ret = bitbuf & (~(uint64_t)0 >> (64 - bits));
166  bitbuf >>= bits;
167  bitbuf_size -= bits;
168  return ret;
169  }
170  }
171 
173  uint64_t randrange(uint64_t range) noexcept
174  {
175  assert(range);
176  --range;
177  int bits = CountBits(range);
178  while (true) {
179  uint64_t ret = randbits(bits);
180  if (ret <= range) return ret;
181  }
182  }
183 
185  std::vector<unsigned char> randbytes(size_t len);
186 
188  uint32_t rand32() noexcept { return randbits(32); }
189 
191  uint256 rand256() noexcept;
192 
194  bool randbool() noexcept { return randbits(1); }
195 
196  // Compatibility with the C++11 UniformRandomBitGenerator concept
197  typedef uint64_t result_type;
198  static constexpr uint64_t min() { return 0; }
199  static constexpr uint64_t max() { return std::numeric_limits<uint64_t>::max(); }
200  inline uint64_t operator()() noexcept { return rand64(); }
201 };
202 
213 template<typename I, typename R>
214 void Shuffle(I first, I last, R&& rng)
215 {
216  while (first != last) {
217  size_t j = rng.randrange(last - first);
218  if (j) {
219  using std::swap;
220  swap(*first, *(first + j));
221  }
222  ++first;
223  }
224 }
225 
226 /* Number of random bytes returned by GetOSRand.
227  * When changing this constant make sure to change all call sites, and make
228  * sure that the underlying OS APIs for all platforms support the number.
229  * (many cap out at 256 bytes).
230  */
231 static const int NUM_OS_RANDOM_BYTES = 32;
232 
236 void GetOSRand(unsigned char *ent32);
237 
241 bool Random_SanityCheck();
242 
249 void RandomInit();
250 
251 #endif // BITCOIN_RANDOM_H
static const int NUM_OS_RANDOM_BYTES
Definition: random.h:231
int GetRandInt(int nMax) noexcept
Definition: random.cpp:598
uint64_t bitbuf
Definition: random.h:114
bool Random_SanityCheck()
Check that OS randomness is available and returning the requested number of bytes.
Definition: random.cpp:643
void FillBitBuffer()
Definition: random.h:128
void FillByteBuffer()
Definition: random.h:119
A class for ChaCha20 256-bit stream cipher developed by Daniel J.
Definition: chacha20.h:13
uint64_t randbits(int bits) noexcept
Generate a random (bits)-bit integer.
Definition: random.h:158
void GetStrongRandBytes(unsigned char *buf, int num) noexcept
Gather entropy from various sources, feed it into the internal PRNG, and generate random data using i...
Definition: random.cpp:582
void RandomInit()
Initialize global RNG state and log any CPU features that are used.
Definition: random.cpp:712
Fast randomness source.
Definition: random.h:106
static constexpr uint64_t max()
Definition: random.h:199
std::chrono::microseconds GetRandMicros(std::chrono::microseconds duration_max) noexcept
Definition: random.cpp:593
void RandAddPeriodic() noexcept
Gather entropy from various expensive sources, and feed them to the PRNG state.
Definition: random.cpp:583
static uint64_t CountBits(uint64_t x)
Return the smallest number n such that (x >> n) == 0 (or 64 if the highest bit in x is set...
Definition: common.h:83
uint64_t result_type
Definition: random.h:197
uint32_t rand32() noexcept
Generate a random 32-bit integer.
Definition: random.h:188
void GetRandBytes(unsigned char *buf, int num) noexcept
Overall design of the RNG and entropy sources.
Definition: random.cpp:581
bool requires_seed
Definition: random.h:108
256-bit opaque blob.
Definition: uint256.h:120
void Shuffle(I first, I last, R &&rng)
More efficient than using std::shuffle on a FastRandomContext.
Definition: random.h:214
void Keystream(unsigned char *c, size_t bytes)
outputs the keystream of size <bytes> into
Definition: chacha20.cpp:74
uint256 GetRandHash() noexcept
Definition: random.cpp:603
void GetOSRand(unsigned char *ent32)
Get 32 bytes of system entropy.
Definition: random.cpp:276
uint64_t operator()() noexcept
Definition: random.h:200
static uint64_t ReadLE64(const unsigned char *ptr)
Definition: common.h:31
static constexpr uint64_t min()
Definition: random.h:198
bool randbool() noexcept
Generate a random boolean.
Definition: random.h:194
ChaCha20 rng
Definition: random.h:109
uint64_t rand64() noexcept
Generate a random 64-bit integer.
Definition: random.h:149
void RandAddEvent(const uint32_t event_info) noexcept
Gathers entropy from the low bits of the time at which events occur.
Definition: random.cpp:584
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
Definition: random.h:173
uint64_t GetRand(uint64_t nMax) noexcept
Definition: random.cpp:588