File tree 3 files changed +33
-0
lines changed
3 files changed +33
-0
lines changed Original file line number Diff line number Diff line change @@ -304,6 +304,26 @@ void FastRandomContext::RandomSeed()
304
304
requires_seed = false ;
305
305
}
306
306
307
+ uint256 FastRandomContext::rand256 ()
308
+ {
309
+ if (bytebuf_size < 32 ) {
310
+ FillByteBuffer ();
311
+ }
312
+ uint256 ret;
313
+ memcpy (ret.begin (), bytebuf + 64 - bytebuf_size, 32 );
314
+ bytebuf_size -= 32 ;
315
+ return ret;
316
+ }
317
+
318
+ std::vector<unsigned char > FastRandomContext::randbytes (size_t len)
319
+ {
320
+ std::vector<unsigned char > ret (len);
321
+ if (len > 0 ) {
322
+ rng.Output (&ret[0 ], len);
323
+ }
324
+ return ret;
325
+ }
326
+
307
327
FastRandomContext::FastRandomContext (const uint256& seed) : requires_seed(false ), bytebuf_size(0 ), bitbuf_size(0 )
308
328
{
309
329
rng.SetKey (seed.begin (), 32 );
Original file line number Diff line number Diff line change @@ -110,9 +110,15 @@ class FastRandomContext {
110
110
}
111
111
}
112
112
113
+ /* * Generate random bytes. */
114
+ std::vector<unsigned char > randbytes (size_t len);
115
+
113
116
/* * Generate a random 32-bit integer. */
114
117
uint32_t rand32 () { return randbits (32 ); }
115
118
119
+ /* * generate a random uint256. */
120
+ uint256 rand256 ();
121
+
116
122
/* * Generate a random boolean. */
117
123
bool randbool () { return randbits (1 ); }
118
124
};
Original file line number Diff line number Diff line change @@ -25,14 +25,21 @@ BOOST_AUTO_TEST_CASE(fastrandom_tests)
25
25
BOOST_CHECK_EQUAL (ctx1.rand32 (), ctx2.rand32 ());
26
26
BOOST_CHECK_EQUAL (ctx1.rand64 (), ctx2.rand64 ());
27
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 ());
28
30
BOOST_CHECK_EQUAL (ctx1.randbits (7 ), ctx2.randbits (7 ));
31
+ BOOST_CHECK (ctx1.randbytes (128 ) == ctx2.randbytes (128 ));
29
32
BOOST_CHECK_EQUAL (ctx1.rand32 (), ctx2.rand32 ());
30
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 ));
31
36
32
37
// Check that a nondeterministic ones are not
33
38
FastRandomContext ctx3;
34
39
FastRandomContext ctx4;
35
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 ));
36
43
}
37
44
38
45
BOOST_AUTO_TEST_CASE (fastrandom_randbits)
You can’t perform that action at this time.
0 commit comments