1 // Copyright (c) 2017 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #include "test/test_bitcoin.h"
9 #include <boost/test/unit_test.hpp>
11 BOOST_FIXTURE_TEST_SUITE(random_tests
, BasicTestingSetup
)
13 BOOST_AUTO_TEST_CASE(osrandom_tests
)
15 BOOST_CHECK(Random_SanityCheck());
18 BOOST_AUTO_TEST_CASE(fastrandom_tests
)
20 // Check that deterministic FastRandomContexts are deterministic
21 FastRandomContext
ctx1(true);
22 FastRandomContext
ctx2(true);
24 BOOST_CHECK_EQUAL(ctx1
.rand32(), ctx2
.rand32());
25 BOOST_CHECK_EQUAL(ctx1
.rand32(), ctx2
.rand32());
26 BOOST_CHECK_EQUAL(ctx1
.rand64(), ctx2
.rand64());
27 BOOST_CHECK_EQUAL(ctx1
.randbits(3), ctx2
.randbits(3));
28 BOOST_CHECK(ctx1
.randbytes(17) == ctx2
.randbytes(17));
29 BOOST_CHECK(ctx1
.rand256() == ctx2
.rand256());
30 BOOST_CHECK_EQUAL(ctx1
.randbits(7), ctx2
.randbits(7));
31 BOOST_CHECK(ctx1
.randbytes(128) == ctx2
.randbytes(128));
32 BOOST_CHECK_EQUAL(ctx1
.rand32(), ctx2
.rand32());
33 BOOST_CHECK_EQUAL(ctx1
.randbits(3), ctx2
.randbits(3));
34 BOOST_CHECK(ctx1
.rand256() == ctx2
.rand256());
35 BOOST_CHECK(ctx1
.randbytes(50) == ctx2
.randbytes(50));
37 // Check that a nondeterministic ones are not
38 FastRandomContext ctx3
;
39 FastRandomContext ctx4
;
40 BOOST_CHECK(ctx3
.rand64() != ctx4
.rand64()); // extremely unlikely to be equal
41 BOOST_CHECK(ctx3
.rand256() != ctx4
.rand256());
42 BOOST_CHECK(ctx3
.randbytes(7) != ctx4
.randbytes(7));
45 BOOST_AUTO_TEST_CASE(fastrandom_randbits
)
47 FastRandomContext ctx1
;
48 FastRandomContext ctx2
;
49 for (int bits
= 0; bits
< 63; ++bits
) {
50 for (int j
= 0; j
< 1000; ++j
) {
51 uint64_t rangebits
= ctx1
.randbits(bits
);
52 BOOST_CHECK_EQUAL(rangebits
>> bits
, 0);
53 uint64_t range
= ((uint64_t)1) << bits
| rangebits
;
54 uint64_t rand
= ctx2
.randrange(range
);
55 BOOST_CHECK(rand
< range
);
60 BOOST_AUTO_TEST_SUITE_END()