1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 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
15 * Seed OpenSSL PRNG with additional entropy data
18 void RandAddSeedPerfmon();
21 * Functions to gather random data via the OpenSSL PRNG
23 void GetRandBytes(unsigned char* buf, int num);
24 uint64_t GetRand(uint64_t nMax);
25 int GetRandInt(int nMax);
26 uint256 GetRandHash();
29 * Rearranges the elements in the range [first,first+len) randomly, assuming
30 * that gen is a uniform random number generator. Follows the same algorithm as
31 * std::shuffle in C++11 (a Durstenfeld shuffle).
33 * The elements in the range [mapFirst,mapFirst+len) are rearranged according to
34 * the same permutation, enabling the permutation to be tracked by the caller.
36 * gen takes an integer n and produces a uniform random output in [0,n).
38 template <typename RandomAccessIterator, typename MapRandomAccessIterator>
39 void MappedShuffle(RandomAccessIterator first,
40 MapRandomAccessIterator mapFirst,
42 std::function<int(int)> gen)
44 for (size_t i = len-1; i > 0; --i) {
48 std::swap(first[i], first[r]);
49 std::swap(mapFirst[i], mapFirst[r]);
54 * Seed insecure_rand using the random pool.
55 * @param Deterministic Use a deterministic seed
57 void seed_insecure_rand(bool fDeterministic = false);
60 * MWC RNG of George Marsaglia
61 * This is intended to be fast. It has a period of 2^59.3, though the
62 * least significant 16 bits only have a period of about 2^30.1.
64 * @return random value
66 extern uint32_t insecure_rand_Rz;
67 extern uint32_t insecure_rand_Rw;
68 static inline uint32_t insecure_rand(void)
70 insecure_rand_Rz = 36969 * (insecure_rand_Rz & 65535) + (insecure_rand_Rz >> 16);
71 insecure_rand_Rw = 18000 * (insecure_rand_Rw & 65535) + (insecure_rand_Rw >> 16);
72 return (insecure_rand_Rw << 16) + insecure_rand_Rz;
75 #endif // BITCOIN_RANDOM_H