]> Git Repo - VerusCoin.git/blame - src/random.h
Merge pull request #42 from jl777/dev
[VerusCoin.git] / src / random.h
CommitLineData
6354935c 1// Copyright (c) 2009-2010 Satoshi Nakamoto
f914f1a7 2// Copyright (c) 2009-2014 The Bitcoin Core developers
78253fcb 3// Distributed under the MIT software license, see the accompanying
6354935c
PK
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 "uint256.h"
10
0382417f 11#include <functional>
6354935c
PK
12#include <stdint.h>
13
6354935c 14/**
bf6a1383 15 * Functions to gather random data via the libsodium CSPRNG
6354935c 16 */
e5df7ee7 17void GetRandBytes(unsigned char* buf, size_t num);
6354935c
PK
18uint64_t GetRand(uint64_t nMax);
19int GetRandInt(int nMax);
20uint256 GetRandHash();
21
38276c6b
S
22/**
23 * Identity function for MappedShuffle, so that elements retain their original order.
24 */
25 int GenIdentity(int n);
26
0382417f
JG
27/**
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).
31 *
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.
34 *
35 * gen takes an integer n and produces a uniform random output in [0,n).
36 */
37template <typename RandomAccessIterator, typename MapRandomAccessIterator>
38void MappedShuffle(RandomAccessIterator first,
39 MapRandomAccessIterator mapFirst,
40 size_t len,
41 std::function<int(int)> gen)
42{
43 for (size_t i = len-1; i > 0; --i) {
44 auto r = gen(i+1);
aa36398b
JG
45 assert(r >= 0);
46 assert(r <= i);
0382417f
JG
47 std::swap(first[i], first[r]);
48 std::swap(mapFirst[i], mapFirst[r]);
49 }
50}
51
6354935c
PK
52/**
53 * Seed insecure_rand using the random pool.
3a05ba1b 54 * @param Deterministic Use a deterministic seed
6354935c
PK
55 */
56void seed_insecure_rand(bool fDeterministic = false);
57
58/**
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.
62 *
63 * @return random value
64 */
65extern uint32_t insecure_rand_Rz;
66extern uint32_t insecure_rand_Rw;
67static inline uint32_t insecure_rand(void)
68{
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;
72}
73
74#endif // BITCOIN_RANDOM_H
This page took 0.133886 seconds and 4 git commands to generate.