From fb89c03dd2b4c05847b7f3f7eeb965cae2e2087e Mon Sep 17 00:00:00 2001 From: "zugz (tox)" Date: Thu, 2 Aug 2018 21:00:43 +0100 Subject: Add simple deterministic random number generator for tests --- testing/misc_tools.c | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++++ testing/misc_tools.h | 2 ++ 2 files changed, 77 insertions(+) diff --git a/testing/misc_tools.c b/testing/misc_tools.c index 8683830d..f039740d 100644 --- a/testing/misc_tools.c +++ b/testing/misc_tools.c @@ -21,6 +21,10 @@ * You should have received a copy of the GNU General Public License * along with Tox. If not, see . */ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + #ifndef _POSIX_C_SOURCE // For nanosleep(). #define _POSIX_C_SOURCE 199309L @@ -35,6 +39,10 @@ #include #include +#ifndef VANILLA_NACL +#include "sodium.h" +#endif + #if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) #include #else @@ -189,3 +197,70 @@ Tox *tox_new_log(struct Tox_Options *options, TOX_ERR_NEW *err, void *log_user_d { return tox_new_log_lan(options, err, log_user_data, false); } + + +#ifndef VANILLA_NACL +static const char *test_rng_name(void) +{ + return "test_rng"; +} + +static uint32_t rng_state; + +static uint32_t test_rng_random(void) +{ + rng_state = 2624534371 * rng_state + 1; + return rng_state; +} + +static void test_rng_buf(void *const buf, const size_t size) +{ + uint8_t *p = (uint8_t *)buf; + uint32_t r = 0; + + for (size_t i = 0; i < size; i++) { + if ((i % 4) == 0) { + r = test_rng_random(); + } + + *p = (r >> ((i % 4) * 8)) & 0xff; + ++p; + } +} + +static uint32_t test_rng_uniform(const uint32_t upper_bound) +{ + // XXX: Not uniform! But that's ok for testing purposes. + return test_rng_random() % upper_bound; +} + +static void test_rng_stir(void) { } +static int test_rng_close(void) +{ + return 0; +} + +static randombytes_implementation test_rng = { + test_rng_name, + test_rng_random, + test_rng_stir, + test_rng_uniform, + test_rng_buf, + test_rng_close +}; + +/* Simple insecure PRNG for testing purposes */ +int use_test_rng(uint32_t seed) +{ + rng_state = seed; + + return randombytes_set_implementation(&test_rng); +} + +#else + +int use_test_rng(uint32_t seed) +{ + assert(!"libsodium required for use_test_rng"); +} +#endif diff --git a/testing/misc_tools.h b/testing/misc_tools.h index deaa177d..b715c8cc 100644 --- a/testing/misc_tools.h +++ b/testing/misc_tools.h @@ -22,6 +22,8 @@ void print_debug_log(Tox *m, TOX_LOG_LEVEL level, const char *file, uint32_t lin Tox *tox_new_log(struct Tox_Options *options, TOX_ERR_NEW *err, void *log_user_data); Tox *tox_new_log_lan(struct Tox_Options *options, TOX_ERR_NEW *err, void *log_user_data, bool lan_discovery); +int use_test_rng(uint32_t seed); + #ifdef __cplusplus } #endif -- cgit v1.2.3