[yul-phaser] SimulationRNG: Use a single, shared and seedable generator

This commit is contained in:
Kamil Śliwak
2020-02-16 02:18:21 +01:00
parent 342a4e5dee
commit db140a667a
3 changed files with 93 additions and 7 deletions
+11 -7
View File
@@ -25,20 +25,24 @@
using namespace solidity;
using namespace solidity::phaser;
thread_local boost::random::mt19937 SimulationRNG::s_generator(SimulationRNG::generateSeed());
uint32_t SimulationRNG::uniformInt(uint32_t _min, uint32_t _max)
{
// TODO: Seed must be configurable
static boost::random::mt19937 generator(time(0));
boost::random::uniform_int_distribution<> distribution(_min, _max);
return distribution(generator);
return distribution(s_generator);
}
uint32_t SimulationRNG::binomialInt(uint32_t _numTrials, double _successProbability)
{
// TODO: Seed must be configurable
static boost::random::mt19937 generator(time(0));
boost::random::binomial_distribution<> distribution(_numTrials, _successProbability);
return distribution(s_generator);
}
return distribution(generator);
uint32_t SimulationRNG::generateSeed()
{
// This is not a secure way to seed the generator but it's good enough for simulation purposes.
// The only thing that matters for us is that the sequence is different on each run and that
// it fits the expected distribution. It does not have to be 100% unpredictable.
return time(0);
}
+16
View File
@@ -27,6 +27,10 @@ namespace solidity::phaser
/**
* A class that provides functions for generating random numbers good enough for simulation purposes.
*
* The functions share a common instance of the generator which can be reset with a known seed
* to deterministically generate a given sequence of numbers. Initially the generator is seeded with
* a value from @a generateSeed() which is different on each run.
*
* The numbers are not cryptographically secure so do not use this for anything that requires
* them to be truly unpredictable.
*/
@@ -35,6 +39,18 @@ class SimulationRNG
public:
static uint32_t uniformInt(uint32_t _min, uint32_t _max);
static uint32_t binomialInt(uint32_t _numTrials, double _successProbability);
/// Resets generator to a known state given by the @a seed. Given the same seed, a fixed
/// sequence of calls to the members generating random values is guaranteed to produce the
/// same results.
static void reset(uint32_t seed) { s_generator = boost::random::mt19937(seed); }
/// Generates a seed that's different on each run of the program.
/// Does **not** use the generator and is not affected by @a reset().
static uint32_t generateSeed();
private:
thread_local static boost::random::mt19937 s_generator;
};
}