Skip to content

Commit daf3e7d

Browse files
committed
Merge #10338: Maintain state across GetStrongRandBytes calls
97477c5 Maintain state across GetStrongRandBytes calls (Pieter Wuille) Tree-SHA512: 77e9b1f3c6eeb0c2a3e0c64358150767222ff0b7120ccd5f4ae0276cea0e4fa275c1b757e3f20be07dc0b4ef07f70ab0b70112080c8d3d0cb6ed703db8a59168
2 parents bc64b5a + 97477c5 commit daf3e7d

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

src/random.cpp

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@
3434
#include <sys/sysctl.h>
3535
#endif
3636

37+
#include <mutex>
38+
3739
#include <openssl/err.h>
3840
#include <openssl/rand.h>
3941

@@ -201,6 +203,10 @@ void GetRandBytes(unsigned char* buf, int num)
201203
}
202204
}
203205

206+
static std::mutex cs_rng_state;
207+
static unsigned char rng_state[32] = {0};
208+
static uint64_t rng_counter = 0;
209+
204210
void GetStrongRandBytes(unsigned char* out, int num)
205211
{
206212
assert(num <= 32);
@@ -216,8 +222,17 @@ void GetStrongRandBytes(unsigned char* out, int num)
216222
GetOSRand(buf);
217223
hasher.Write(buf, 32);
218224

225+
// Combine with and update state
226+
{
227+
std::unique_lock<std::mutex> lock(cs_rng_state);
228+
hasher.Write(rng_state, sizeof(rng_state));
229+
hasher.Write((const unsigned char*)&rng_counter, sizeof(rng_counter));
230+
++rng_counter;
231+
hasher.Finalize(buf);
232+
memcpy(rng_state, buf + 32, 32);
233+
}
234+
219235
// Produce output
220-
hasher.Finalize(buf);
221236
memcpy(out, buf, num);
222237
memory_cleanse(buf, 64);
223238
}

0 commit comments

Comments
 (0)