diff options
author | Pieter Wuille <pieter.wuille@gmail.com> | 2017-02-25 12:16:58 -0800 |
---|---|---|
committer | Pieter Wuille <pieter.wuille@gmail.com> | 2017-03-29 11:26:08 -0700 |
commit | 4fd2d2fc97e21efceab849576e544160fd5e3e3d (patch) | |
tree | 4d36745b0b5a72bf51b2e54bfd13151920a2c57b /src/test | |
parent | 16329224e70d0525208f6b0ba00c5e1531a4f5ea (diff) |
Add a FastRandomContext::randrange and use it
Diffstat (limited to 'src/test')
-rw-r--r-- | src/test/crypto_tests.cpp | 23 | ||||
-rw-r--r-- | src/test/random_tests.cpp | 15 |
2 files changed, 38 insertions, 0 deletions
diff --git a/src/test/crypto_tests.cpp b/src/test/crypto_tests.cpp index a20182afb8..72e562808a 100644 --- a/src/test/crypto_tests.cpp +++ b/src/test/crypto_tests.cpp @@ -10,6 +10,7 @@ #include "crypto/sha512.h" #include "crypto/hmac_sha256.h" #include "crypto/hmac_sha512.h" +#include "random.h" #include "utilstrencodings.h" #include "test/test_bitcoin.h" #include "test/test_random.h" @@ -484,4 +485,26 @@ BOOST_AUTO_TEST_CASE(chacha20_testvector) "fab78c9"); } +BOOST_AUTO_TEST_CASE(countbits_tests) +{ + FastRandomContext ctx; + for (int i = 0; i <= 64; ++i) { + if (i == 0) { + // Check handling of zero. + BOOST_CHECK_EQUAL(CountBits(0), 0); + } else if (i < 10) { + for (uint64_t j = 1 << (i - 1); (j >> i) == 0; ++j) { + // Exhaustively test up to 10 bits + BOOST_CHECK_EQUAL(CountBits(j), i); + } + } else { + for (int k = 0; k < 1000; k++) { + // Randomly test 1000 samples of each length above 10 bits. + uint64_t j = ((uint64_t)1) << (i - 1) | ctx.randbits(i - 1); + BOOST_CHECK_EQUAL(CountBits(j), i); + } + } + } +} + BOOST_AUTO_TEST_SUITE_END() diff --git a/src/test/random_tests.cpp b/src/test/random_tests.cpp index 31b993cd38..8596734226 100644 --- a/src/test/random_tests.cpp +++ b/src/test/random_tests.cpp @@ -35,4 +35,19 @@ BOOST_AUTO_TEST_CASE(fastrandom_tests) BOOST_CHECK(ctx3.rand64() != ctx4.rand64()); // extremely unlikely to be equal } +BOOST_AUTO_TEST_CASE(fastrandom_randbits) +{ + FastRandomContext ctx1; + FastRandomContext ctx2; + for (int bits = 0; bits < 63; ++bits) { + for (int j = 0; j < 1000; ++j) { + uint64_t rangebits = ctx1.randbits(bits); + BOOST_CHECK_EQUAL(rangebits >> bits, 0); + uint64_t range = ((uint64_t)1) << bits | rangebits; + uint64_t rand = ctx2.randrange(range); + BOOST_CHECK(rand < range); + } + } +} + BOOST_AUTO_TEST_SUITE_END() |