Skip to content

Commit

Permalink
Merge #10338: Maintain state across GetStrongRandBytes calls
Browse files Browse the repository at this point in the history
97477c5 Maintain state across GetStrongRandBytes calls (Pieter Wuille)

Tree-SHA512: 77e9b1f3c6eeb0c2a3e0c64358150767222ff0b7120ccd5f4ae0276cea0e4fa275c1b757e3f20be07dc0b4ef07f70ab0b70112080c8d3d0cb6ed703db8a59168
  • Loading branch information
sipa committed May 9, 2017
2 parents bc64b5a + 97477c5 commit daf3e7d
Showing 1 changed file with 16 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/random.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@
#include <sys/sysctl.h>
#endif

#include <mutex>

#include <openssl/err.h>
#include <openssl/rand.h>

Expand Down Expand Up @@ -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);
Expand All @@ -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);
}
Expand Down

0 comments on commit daf3e7d

Please sign in to comment.