1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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.
6 #ifndef BITCOIN_RANDOM_H
7 #define BITCOIN_RANDOM_H
9 #include "crypto/chacha20.h"
10 #include "crypto/common.h"
15 /* Seed OpenSSL PRNG with additional entropy data */
19 * Functions to gather random data via the OpenSSL PRNG
21 void GetRandBytes(unsigned char* buf
, int num
);
22 uint64_t GetRand(uint64_t nMax
);
23 int GetRandInt(int nMax
);
24 uint256
GetRandHash();
27 * Function to gather random data from multiple sources, failing whenever any
28 * of those source fail to provide a result.
30 void GetStrongRandBytes(unsigned char* buf
, int num
);
33 * Fast randomness source. This is seeded once with secure random data, but
34 * is completely deterministic and insecure after that.
35 * This class is not thread-safe.
37 class FastRandomContext
{
42 unsigned char bytebuf
[64];
55 rng
.Output(bytebuf
, sizeof(bytebuf
));
56 bytebuf_size
= sizeof(bytebuf
);
66 explicit FastRandomContext(bool fDeterministic
= false);
68 /** Initialize with explicit seed (only for testing) */
69 explicit FastRandomContext(const uint256
& seed
);
71 /** Generate a random 64-bit integer. */
74 if (bytebuf_size
< 8) FillByteBuffer();
75 uint64_t ret
= ReadLE64(bytebuf
+ 64 - bytebuf_size
);
80 /** Generate a random (bits)-bit integer. */
81 uint64_t randbits(int bits
) {
84 } else if (bits
> 32) {
85 return rand64() >> (64 - bits
);
87 if (bitbuf_size
< bits
) FillBitBuffer();
88 uint64_t ret
= bitbuf
& (~(uint64_t)0 >> (64 - bits
));
95 /** Generate a random integer in the range [0..range). */
96 uint64_t randrange(uint64_t range
)
99 int bits
= CountBits(range
);
101 uint64_t ret
= randbits(bits
);
102 if (ret
<= range
) return ret
;
106 /** Generate a random 32-bit integer. */
107 uint32_t rand32() { return randbits(32); }
109 /** Generate a random boolean. */
110 bool randbool() { return randbits(1); }
113 /* Number of random bytes returned by GetOSRand.
114 * When changing this constant make sure to change all call sites, and make
115 * sure that the underlying OS APIs for all platforms support the number.
116 * (many cap out at 256 bytes).
118 static const ssize_t NUM_OS_RANDOM_BYTES
= 32;
120 /** Get 32 bytes of system entropy. Do not use this in application code: use
121 * GetStrongRandBytes instead.
123 void GetOSRand(unsigned char *ent32
);
125 /** Check that OS randomness is available and returning the requested number
128 bool Random_SanityCheck();
130 #endif // BITCOIN_RANDOM_H