Changeset View
Changeset View
Standalone View
Standalone View
src/random.h
Show First 20 Lines • Show All 64 Lines • ▼ Show 20 Lines | |||||
* Generate random data via the internal PRNG. | * Generate random data via the internal PRNG. | ||||
* | * | ||||
* These functions are designed to be fast (sub microsecond), but do not | * These functions are designed to be fast (sub microsecond), but do not | ||||
* necessarily meaningfully add entropy to the PRNG state. | * necessarily meaningfully add entropy to the PRNG state. | ||||
* | * | ||||
* Thread-safe. | * Thread-safe. | ||||
*/ | */ | ||||
void GetRandBytes(uint8_t *buf, int num) noexcept; | void GetRandBytes(uint8_t *buf, int num) noexcept; | ||||
/** | |||||
* Generate a uniform random integer in the range [0..range). | |||||
* Precondition: range > 0 | |||||
*/ | |||||
uint64_t GetRand(uint64_t nMax) noexcept; | uint64_t GetRand(uint64_t nMax) noexcept; | ||||
std::chrono::microseconds | /** | ||||
GetRandMicros(std::chrono::microseconds duration_max) noexcept; | * Generate a uniform random duration in the range [0..max). | ||||
std::chrono::milliseconds | * Precondition: max.count() > 0 | ||||
GetRandMillis(std::chrono::milliseconds duration_max) noexcept; | */ | ||||
template <typename D> | |||||
D GetRandomDuration(typename std::common_type<D>::type max) noexcept { | |||||
// Having the compiler infer the template argument from the function | |||||
// argument is dangerous, because the desired return value generally has a | |||||
// different type than the function argument. So std::common_type is used to | |||||
// force the call site to specify the type of the return value. | |||||
assert(max.count() > 0); | |||||
return D{GetRand(max.count())}; | |||||
}; | |||||
constexpr auto GetRandMicros = GetRandomDuration<std::chrono::microseconds>; | |||||
constexpr auto GetRandMillis = GetRandomDuration<std::chrono::milliseconds>; | |||||
int GetRandInt(int nMax) noexcept; | int GetRandInt(int nMax) noexcept; | ||||
uint256 GetRandHash() noexcept; | uint256 GetRandHash() noexcept; | ||||
/** | /** | ||||
* Gather entropy from various sources, feed it into the internal PRNG, and | * Gather entropy from various sources, feed it into the internal PRNG, and | ||||
* generate random data using it. | * generate random data using it. | ||||
* | * | ||||
* This function will cause failure whenever the OS RNG fails. | * This function will cause failure whenever the OS RNG fails. | ||||
▲ Show 20 Lines • Show All 189 Lines • Show Last 20 Lines |