Skip to content

Commit 628cf14

Browse files
committed
Don't use assert for catching randomness failures
1 parent fa2637a commit 628cf14

File tree

1 file changed

+20
-6
lines changed

1 file changed

+20
-6
lines changed

src/random.cpp

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
#include "util.h" // for LogPrint()
1616
#include "utilstrencodings.h" // for GetTime()
1717

18+
#include <stdlib.h>
1819
#include <limits>
1920

2021
#ifndef WIN32
@@ -24,6 +25,12 @@
2425
#include <openssl/err.h>
2526
#include <openssl/rand.h>
2627

28+
static void RandFailure()
29+
{
30+
LogPrintf("Failed to read randomness, aborting\n");
31+
abort();
32+
}
33+
2734
static inline int64_t GetPerformanceCounter()
2835
{
2936
int64_t nCounter = 0;
@@ -91,17 +98,25 @@ static void GetOSRand(unsigned char *ent32)
9198
#ifdef WIN32
9299
HCRYPTPROV hProvider;
93100
int ret = CryptAcquireContextW(&hProvider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
94-
assert(ret);
101+
if (!ret) {
102+
RandFailure();
103+
}
95104
ret = CryptGenRandom(hProvider, 32, ent32);
96-
assert(ret);
105+
if (!ret) {
106+
RandFailure();
107+
}
97108
CryptReleaseContext(hProvider, 0);
98109
#else
99110
int f = open("/dev/urandom", O_RDONLY);
100-
assert(f != -1);
111+
if (f == -1) {
112+
RandFailure();
113+
}
101114
int have = 0;
102115
do {
103116
ssize_t n = read(f, ent32 + have, 32 - have);
104-
assert(n > 0 && n <= 32 - have);
117+
if (n <= 0 || n + have > 32) {
118+
RandFailure();
119+
}
105120
have += n;
106121
} while (have < 32);
107122
close(f);
@@ -111,8 +126,7 @@ static void GetOSRand(unsigned char *ent32)
111126
void GetRandBytes(unsigned char* buf, int num)
112127
{
113128
if (RAND_bytes(buf, num) != 1) {
114-
LogPrintf("%s: OpenSSL RAND_bytes() failed with error: %s\n", __func__, ERR_error_string(ERR_get_error(), NULL));
115-
assert(false);
129+
RandFailure();
116130
}
117131
}
118132

0 commit comments

Comments
 (0)