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 * Functions to gather random data via the libsodium CSPRNG
17 void GetRandBytes(unsigned char* buf, size_t num);
18 uint64_t GetRand(uint64_t nMax);
19 int GetRandInt(int nMax);
20 uint256 GetRandHash();
23 * Identity function for MappedShuffle, so that elements retain their original order.
25 int GenIdentity(int n);
28 * Rearranges the elements in the range [first,first+len) randomly, assuming
29 * that gen is a uniform random number generator. Follows the same algorithm as
30 * std::shuffle in C++11 (a Durstenfeld shuffle).
32 * The elements in the range [mapFirst,mapFirst+len) are rearranged according to
33 * the same permutation, enabling the permutation to be tracked by the caller.
35 * gen takes an integer n and produces a uniform random output in [0,n).
37 template <typename RandomAccessIterator, typename MapRandomAccessIterator>
38 void MappedShuffle(RandomAccessIterator first,
39 MapRandomAccessIterator mapFirst,
41 std::function<int(int)> gen)
43 for (size_t i = len-1; i > 0; --i) {
47 std::swap(first[i], first[r]);
48 std::swap(mapFirst[i], mapFirst[r]);
53 * Seed insecure_rand using the random pool.
54 * @param Deterministic Use a deterministic seed
56 void seed_insecure_rand(bool fDeterministic = false);
59 * MWC RNG of George Marsaglia
60 * This is intended to be fast. It has a period of 2^59.3, though the
61 * least significant 16 bits only have a period of about 2^30.1.
63 * @return random value
65 extern uint32_t insecure_rand_Rz;
66 extern uint32_t insecure_rand_Rw;
67 static inline uint32_t insecure_rand(void)
69 insecure_rand_Rz = 36969 * (insecure_rand_Rz & 65535) + (insecure_rand_Rz >> 16);
70 insecure_rand_Rw = 18000 * (insecure_rand_Rw & 65535) + (insecure_rand_Rw >> 16);
71 return (insecure_rand_Rw << 16) + insecure_rand_Rz;
74 #endif // BITCOIN_RANDOM_H