From 3fd6253e13bda5489164eaa7c5ba9de491e47b83 Mon Sep 17 00:00:00 2001 From: Pieter Wuille Date: Fri, 17 Oct 2014 16:04:00 -0700 Subject: [PATCH] Better randomization for tests --- src/tests.c | 23 ++++++++++++++++++++--- src/util.h | 3 +++ src/util_impl.h | 21 +++++++++++++++++---- 3 files changed, 40 insertions(+), 7 deletions(-) diff --git a/src/tests.c b/src/tests.c index 80ae0f4bf1..e5d27f72c7 100644 --- a/src/tests.c +++ b/src/tests.c @@ -19,7 +19,7 @@ #include "openssl/obj_mac.h" #endif -static int count = 100; +static int count = 750; /***** NUM TESTS *****/ @@ -632,6 +632,7 @@ void test_ecdsa_end_to_end() { CHECK(secp256k1_ecdsa_recover_compact(message, 32, csignature, recpubkey, &recpubkeylen, pubkeylen == 33, recid) != 1 || memcmp(pubkey, recpubkey, pubkeylen) != 0); CHECK(recpubkeylen == pubkeylen); + } void run_ecdsa_end_to_end() { @@ -698,10 +699,26 @@ void run_ecdsa_openssl() { #endif int main(int argc, char **argv) { - if (argc > 1) - count = strtol(argv[1], NULL, 0)*47; + // find iteration count + if (argc > 1) { + count = strtol(argv[1], NULL, 0); + } + + // find random seed + uint64_t seed; + if (argc > 2) { + seed = strtoull(argv[2], NULL, 0); + } else { + FILE *frand = fopen("/dev/urandom", "r"); + if (!frand || !fread(&seed, sizeof(seed), 1, frand)) { + seed = time(NULL) * 1337; + } + fclose(frand); + } + secp256k1_rand_seed(seed); printf("test count = %i\n", count); + printf("random seed = %llu\n", (unsigned long long)seed); // initialize secp256k1_start(SECP256K1_START_SIGN | SECP256K1_START_VERIFY); diff --git a/src/util.h b/src/util.h index 122889577e..c859523f49 100644 --- a/src/util.h +++ b/src/util.h @@ -43,6 +43,9 @@ #define VERIFY_CHECK(cond) do { (cond); } while(0) #endif +/** Seed the pseudorandom number generator. */ +static inline void secp256k1_rand_seed(uint64_t v); + /** Generate a pseudorandom 32-bit number. */ static uint32_t secp256k1_rand32(void); diff --git a/src/util_impl.h b/src/util_impl.h index 58750f8cfc..482fb31b1a 100644 --- a/src/util_impl.h +++ b/src/util_impl.h @@ -10,11 +10,24 @@ #include "util.h" +static uint32_t secp256k1_Rz = 11, secp256k1_Rw = 11; + +static inline void secp256k1_rand_seed(uint64_t v) { + secp256k1_Rz = v >> 32; + secp256k1_Rw = v; + + if (secp256k1_Rz == 0 || secp256k1_Rz == 0x9068ffffU) { + secp256k1_Rz = 111; + } + if (secp256k1_Rw == 0 || secp256k1_Rw == 0x464fffffU) { + secp256k1_Rw = 111; + } +} + static inline uint32_t secp256k1_rand32(void) { - static uint32_t Rz = 11, Rw = 11; - Rz = 36969 * (Rz & 0xFFFF) + (Rz >> 16); - Rw = 18000 * (Rw & 0xFFFF) + (Rw >> 16); - return (Rw << 16) + (Rw >> 16) + Rz; + secp256k1_Rz = 36969 * (secp256k1_Rz & 0xFFFF) + (secp256k1_Rz >> 16); + secp256k1_Rw = 18000 * (secp256k1_Rw & 0xFFFF) + (secp256k1_Rw >> 16); + return (secp256k1_Rw << 16) + (secp256k1_Rw >> 16) + secp256k1_Rz; } static void secp256k1_rand256(unsigned char *b32) {