Merge #10338: Maintain state across GetStrongRandBytes calls

97477c5 Maintain state across GetStrongRandBytes calls (Pieter Wuille)

Tree-SHA512: 77e9b1f3c6eeb0c2a3e0c64358150767222ff0b7120ccd5f4ae0276cea0e4fa275c1b757e3f20be07dc0b4ef07f70ab0b70112080c8d3d0cb6ed703db8a59168
This commit is contained in:
Pieter Wuille 2017-05-09 10:13:45 -07:00
commit daf3e7def7
No known key found for this signature in database
GPG key ID: A636E97631F767E0

View file

@ -34,6 +34,8 @@
#include <sys/sysctl.h>
#endif
#include <mutex>
#include <openssl/err.h>
#include <openssl/rand.h>
@ -201,6 +203,10 @@ void GetRandBytes(unsigned char* buf, int num)
}
}
static std::mutex cs_rng_state;
static unsigned char rng_state[32] = {0};
static uint64_t rng_counter = 0;
void GetStrongRandBytes(unsigned char* out, int num)
{
assert(num <= 32);
@ -216,8 +222,17 @@ void GetStrongRandBytes(unsigned char* out, int num)
GetOSRand(buf);
hasher.Write(buf, 32);
// Combine with and update state
{
std::unique_lock<std::mutex> lock(cs_rng_state);
hasher.Write(rng_state, sizeof(rng_state));
hasher.Write((const unsigned char*)&rng_counter, sizeof(rng_counter));
++rng_counter;
hasher.Finalize(buf);
memcpy(rng_state, buf + 32, 32);
}
// Produce output
hasher.Finalize(buf);
memcpy(out, buf, num);
memory_cleanse(buf, 64);
}