Bitcoin Core  24.99.0
P2P Digital Currency
random.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2022 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 <span.h>
12 #include <uint256.h>
13 
14 #include <cassert>
15 #include <chrono>
16 #include <cstdint>
17 #include <limits>
18 #include <vector>
19 
72 void GetRandBytes(Span<unsigned char> bytes) noexcept;
74 uint64_t GetRandInternal(uint64_t nMax) noexcept;
79 template<typename T>
80 T GetRand(T nMax=std::numeric_limits<T>::max()) noexcept {
81  static_assert(std::is_integral<T>(), "T must be integral");
82  static_assert(std::numeric_limits<T>::max() <= std::numeric_limits<uint64_t>::max(), "GetRand only supports up to uint64_t");
83  return T(GetRandInternal(nMax));
84 }
86 template <typename D>
87 D GetRandomDuration(typename std::common_type<D>::type max) noexcept
88 // Having the compiler infer the template argument from the function argument
89 // is dangerous, because the desired return value generally has a different
90 // type than the function argument. So std::common_type is used to force the
91 // call site to specify the type of the return value.
92 {
93  assert(max.count() > 0);
94  return D{GetRand(max.count())};
95 };
96 constexpr auto GetRandMicros = GetRandomDuration<std::chrono::microseconds>;
97 constexpr auto GetRandMillis = GetRandomDuration<std::chrono::milliseconds>;
98 
108 std::chrono::microseconds GetExponentialRand(std::chrono::microseconds now, std::chrono::seconds average_interval);
109 
110 uint256 GetRandHash() noexcept;
111 
120 void GetStrongRandBytes(Span<unsigned char> bytes) noexcept;
121 
127 void RandAddPeriodic() noexcept;
128 
135 void RandAddEvent(const uint32_t event_info) noexcept;
136 
144 {
145 private:
148 
149  uint64_t bitbuf;
151 
152  void RandomSeed();
153 
155  {
156  bitbuf = rand64();
157  bitbuf_size = 64;
158  }
159 
160 public:
161  explicit FastRandomContext(bool fDeterministic = false) noexcept;
162 
164  explicit FastRandomContext(const uint256& seed) noexcept;
165 
166  // Do not permit copying a FastRandomContext (move it, or create a new one to get reseeded).
169  FastRandomContext& operator=(const FastRandomContext&) = delete;
170 
172  FastRandomContext& operator=(FastRandomContext&& from) noexcept;
173 
175  uint64_t rand64() noexcept
176  {
177  if (requires_seed) RandomSeed();
178  unsigned char buf[8];
179  rng.Keystream(buf, 8);
180  return ReadLE64(buf);
181  }
182 
184  uint64_t randbits(int bits) noexcept
185  {
186  if (bits == 0) {
187  return 0;
188  } else if (bits > 32) {
189  return rand64() >> (64 - bits);
190  } else {
191  if (bitbuf_size < bits) FillBitBuffer();
192  uint64_t ret = bitbuf & (~uint64_t{0} >> (64 - bits));
193  bitbuf >>= bits;
194  bitbuf_size -= bits;
195  return ret;
196  }
197  }
198 
202  uint64_t randrange(uint64_t range) noexcept
203  {
204  assert(range);
205  --range;
206  int bits = CountBits(range);
207  while (true) {
208  uint64_t ret = randbits(bits);
209  if (ret <= range) return ret;
210  }
211  }
212 
214  std::vector<unsigned char> randbytes(size_t len);
215 
217  uint32_t rand32() noexcept { return randbits(32); }
218 
220  uint256 rand256() noexcept;
221 
223  bool randbool() noexcept { return randbits(1); }
224 
226  template <typename Tp>
227  Tp rand_uniform_delay(const Tp& time, typename Tp::duration range)
228  {
229  return time + rand_uniform_duration<Tp>(range);
230  }
231 
233  template <typename Chrono>
234  typename Chrono::duration rand_uniform_duration(typename Chrono::duration range) noexcept
235  {
236  using Dur = typename Chrono::duration;
237  return range.count() > 0 ? /* interval [0..range) */ Dur{randrange(range.count())} :
238  range.count() < 0 ? /* interval (range..0] */ -Dur{randrange(-range.count())} :
239  /* interval [0..0] */ Dur{0};
240  };
241 
242  // Compatibility with the UniformRandomBitGenerator concept
243  typedef uint64_t result_type;
244  static constexpr uint64_t min() { return 0; }
245  static constexpr uint64_t max() { return std::numeric_limits<uint64_t>::max(); }
246  inline uint64_t operator()() noexcept { return rand64(); }
247 };
248 
259 template <typename I, typename R>
260 void Shuffle(I first, I last, R&& rng)
261 {
262  while (first != last) {
263  size_t j = rng.randrange(last - first);
264  if (j) {
265  using std::swap;
266  swap(*first, *(first + j));
267  }
268  ++first;
269  }
270 }
271 
272 /* Number of random bytes returned by GetOSRand.
273  * When changing this constant make sure to change all call sites, and make
274  * sure that the underlying OS APIs for all platforms support the number.
275  * (many cap out at 256 bytes).
276  */
277 static const int NUM_OS_RANDOM_BYTES = 32;
278 
282 void GetOSRand(unsigned char* ent32);
283 
287 bool Random_SanityCheck();
288 
295 void RandomInit();
296 
297 #endif // BITCOIN_RANDOM_H
int ret
Unrestricted ChaCha20 cipher.
Definition: chacha20.h:46
void Keystream(unsigned char *c, size_t bytes)
outputs the keystream of size <bytes> into
Definition: chacha20.cpp:274
Fast randomness source.
Definition: random.h:144
Chrono::duration rand_uniform_duration(typename Chrono::duration range) noexcept
Generate a uniform random duration in the range from 0 (inclusive) to range (exclusive).
Definition: random.h:234
uint32_t rand32() noexcept
Generate a random 32-bit integer.
Definition: random.h:217
void FillBitBuffer()
Definition: random.h:154
uint64_t bitbuf
Definition: random.h:149
Tp rand_uniform_delay(const Tp &time, typename Tp::duration range)
Return the time point advanced by a uniform random duration.
Definition: random.h:227
ChaCha20 rng
Definition: random.h:147
static constexpr uint64_t max()
Definition: random.h:245
uint64_t randbits(int bits) noexcept
Generate a random (bits)-bit integer.
Definition: random.h:184
static constexpr uint64_t min()
Definition: random.h:244
uint64_t result_type
Definition: random.h:240
bool requires_seed
Definition: random.h:146
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
Definition: random.h:202
uint64_t operator()() noexcept
Definition: random.h:246
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:97
256-bit opaque blob.
Definition: uint256.h:105
static uint64_t ReadLE64(const unsigned char *ptr)
Definition: common.h:31
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:90
#define T(expected, seed, data)
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....
Definition: random.cpp:702
D GetRandomDuration(typename std::common_type< D >::type max) noexcept
Generate a uniform random duration in the range [0..max).
Definition: random.h:87
constexpr auto GetRandMicros
Definition: random.h:96
void GetRandBytes(Span< unsigned char > bytes) noexcept
Overall design of the RNG and entropy sources.
Definition: random.cpp:579
void RandAddPeriodic() noexcept
Gather entropy from various expensive sources, and feed them to the PRNG state.
Definition: random.cpp:581
constexpr auto GetRandMillis
Definition: random.h:97
uint64_t GetRandInternal(uint64_t nMax) noexcept
Generate a uniform random integer in the range [0..range).
Definition: random.cpp:586
void Shuffle(I first, I last, R &&rng)
More efficient than using std::shuffle on a FastRandomContext.
Definition: random.h:260
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:580
bool Random_SanityCheck()
Check that OS randomness is available and returning the requested number of bytes.
Definition: random.cpp:628
uint256 GetRandHash() noexcept
Definition: random.cpp:591
static const int NUM_OS_RANDOM_BYTES
Definition: random.h:277
void RandomInit()
Initialize global RNG state and log any CPU features that are used.
Definition: random.cpp:694
void RandAddEvent(const uint32_t event_info) noexcept
Gathers entropy from the low bits of the time at which events occur.
Definition: random.cpp:582
void GetOSRand(unsigned char *ent32)
Get 32 bytes of system entropy.
Definition: random.cpp:275
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:80
assert(!tx.IsCoinBase())