Skip to content

Commit e801084

Browse files
committed
Merge #10321: Use FastRandomContext for all tests
e945848 scripted-diff: Use new naming style for insecure_rand* functions (Pieter Wuille) 2fcd9cc scripted-diff: Use randbits/bool instead of randrange where possible (Pieter Wuille) 2ada678 Use randbits instead of ad-hoc emulation in prevector tests (Pieter Wuille) 5f0b04e Replace rand() & ((1 << N) - 1) with randbits(N) (Pieter Wuille) 3ecabae Replace more rand() % NUM by randranges (Pieter Wuille) efee1db scripted-diff: use insecure_rand256/randrange more (Pieter Wuille) 1119927 Add various insecure_rand wrappers for tests (Pieter Wuille) 124d13a Merge test_random.h into test_bitcoin.h (Pieter Wuille) 90620d6 scripted-diff: Rename cuckoo tests' local rand context (Pieter Wuille) 37e864e Add FastRandomContext::rand256() and ::randbytes() (Pieter Wuille) Tree-SHA512: d09705a3ec718ae792f7d66a75401903ba7b9c9d3fc36669d6e3b9242f0194738106be26baefc8a8e3fa6df7c9a35978c71c0c430278a028b331df23a3ea3070
2 parents 46311e7 + e945848 commit e801084

26 files changed

+202
-190
lines changed

src/Makefile.test.include

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,6 @@ BITCOIN_TESTS =\
7474
test/test_bitcoin.cpp \
7575
test/test_bitcoin.h \
7676
test/test_bitcoin_main.cpp \
77-
test/test_random.h \
7877
test/testutil.cpp \
7978
test/testutil.h \
8079
test/timedata_tests.cpp \

src/random.cpp

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,26 @@ void FastRandomContext::RandomSeed()
304304
requires_seed = false;
305305
}
306306

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+
307327
FastRandomContext::FastRandomContext(const uint256& seed) : requires_seed(false), bytebuf_size(0), bitbuf_size(0)
308328
{
309329
rng.SetKey(seed.begin(), 32);

src/random.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,9 +110,15 @@ class FastRandomContext {
110110
}
111111
}
112112

113+
/** Generate random bytes. */
114+
std::vector<unsigned char> randbytes(size_t len);
115+
113116
/** Generate a random 32-bit integer. */
114117
uint32_t rand32() { return randbits(32); }
115118

119+
/** generate a random uint256. */
120+
uint256 rand256();
121+
116122
/** Generate a random boolean. */
117123
bool randbool() { return randbits(1); }
118124
};

src/test/DoS_tests.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ BOOST_AUTO_TEST_CASE(DoS_bantime)
129129
CTransactionRef RandomOrphan()
130130
{
131131
std::map<uint256, COrphanTx>::iterator it;
132-
it = mapOrphanTransactions.lower_bound(GetRandHash());
132+
it = mapOrphanTransactions.lower_bound(InsecureRand256());
133133
if (it == mapOrphanTransactions.end())
134134
it = mapOrphanTransactions.begin();
135135
return it->second.tx;
@@ -148,7 +148,7 @@ BOOST_AUTO_TEST_CASE(DoS_mapOrphans)
148148
CMutableTransaction tx;
149149
tx.vin.resize(1);
150150
tx.vin[0].prevout.n = 0;
151-
tx.vin[0].prevout.hash = GetRandHash();
151+
tx.vin[0].prevout.hash = InsecureRand256();
152152
tx.vin[0].scriptSig << OP_1;
153153
tx.vout.resize(1);
154154
tx.vout[0].nValue = 1*CENT;

src/test/blockencodings_tests.cpp

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,16 +30,16 @@ static CBlock BuildBlockTestCase() {
3030
block.vtx.resize(3);
3131
block.vtx[0] = MakeTransactionRef(tx);
3232
block.nVersion = 42;
33-
block.hashPrevBlock = GetRandHash();
33+
block.hashPrevBlock = InsecureRand256();
3434
block.nBits = 0x207fffff;
3535

36-
tx.vin[0].prevout.hash = GetRandHash();
36+
tx.vin[0].prevout.hash = InsecureRand256();
3737
tx.vin[0].prevout.n = 0;
3838
block.vtx[1] = MakeTransactionRef(tx);
3939

4040
tx.vin.resize(10);
4141
for (size_t i = 0; i < tx.vin.size(); i++) {
42-
tx.vin[i].prevout.hash = GetRandHash();
42+
tx.vin[i].prevout.hash = InsecureRand256();
4343
tx.vin[i].prevout.n = 0;
4444
}
4545
block.vtx[2] = MakeTransactionRef(tx);
@@ -283,7 +283,7 @@ BOOST_AUTO_TEST_CASE(EmptyBlockRoundTripTest)
283283
block.vtx.resize(1);
284284
block.vtx[0] = MakeTransactionRef(std::move(coinbase));
285285
block.nVersion = 42;
286-
block.hashPrevBlock = GetRandHash();
286+
block.hashPrevBlock = InsecureRand256();
287287
block.nBits = 0x207fffff;
288288

289289
bool mutated;
@@ -316,7 +316,7 @@ BOOST_AUTO_TEST_CASE(EmptyBlockRoundTripTest)
316316

317317
BOOST_AUTO_TEST_CASE(TransactionsRequestSerializationTest) {
318318
BlockTransactionsRequest req1;
319-
req1.blockhash = GetRandHash();
319+
req1.blockhash = InsecureRand256();
320320
req1.indexes.resize(4);
321321
req1.indexes[0] = 0;
322322
req1.indexes[1] = 1;

src/test/bloom_tests.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -463,7 +463,7 @@ BOOST_AUTO_TEST_CASE(merkle_block_4_test_update_none)
463463

464464
static std::vector<unsigned char> RandomData()
465465
{
466-
uint256 r = GetRandHash();
466+
uint256 r = InsecureRand256();
467467
return std::vector<unsigned char>(r.begin(), r.end());
468468
}
469469

src/test/checkqueue_tests.cpp

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ void Correct_Queue_range(std::vector<size_t> range)
160160
FakeCheckCheckCompletion::n_calls = 0;
161161
CCheckQueueControl<FakeCheckCheckCompletion> control(small_queue.get());
162162
while (total) {
163-
vChecks.resize(std::min(total, (size_t) GetRand(10)));
163+
vChecks.resize(std::min(total, (size_t) InsecureRandRange(10)));
164164
total -= vChecks.size();
165165
control.Add(vChecks);
166166
}
@@ -204,7 +204,7 @@ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Random)
204204
{
205205
std::vector<size_t> range;
206206
range.reserve(100000/1000);
207-
for (size_t i = 2; i < 100000; i += std::max((size_t)1, (size_t)GetRand(std::min((size_t)1000, ((size_t)100000) - i))))
207+
for (size_t i = 2; i < 100000; i += std::max((size_t)1, (size_t)InsecureRandRange(std::min((size_t)1000, ((size_t)100000) - i))))
208208
range.push_back(i);
209209
Correct_Queue_range(range);
210210
}
@@ -224,7 +224,7 @@ BOOST_AUTO_TEST_CASE(test_CheckQueue_Catches_Failure)
224224
CCheckQueueControl<FailingCheck> control(fail_queue.get());
225225
size_t remaining = i;
226226
while (remaining) {
227-
size_t r = GetRand(10);
227+
size_t r = InsecureRandRange(10);
228228

229229
std::vector<FailingCheck> vChecks;
230230
vChecks.reserve(r);
@@ -286,7 +286,7 @@ BOOST_AUTO_TEST_CASE(test_CheckQueue_UniqueCheck)
286286
{
287287
CCheckQueueControl<UniqueCheck> control(queue.get());
288288
while (total) {
289-
size_t r = GetRand(10);
289+
size_t r = InsecureRandRange(10);
290290
std::vector<UniqueCheck> vChecks;
291291
for (size_t k = 0; k < r && total; k++)
292292
vChecks.emplace_back(--total);
@@ -320,7 +320,7 @@ BOOST_AUTO_TEST_CASE(test_CheckQueue_Memory)
320320
{
321321
CCheckQueueControl<MemoryCheck> control(queue.get());
322322
while (total) {
323-
size_t r = GetRand(10);
323+
size_t r = InsecureRandRange(10);
324324
std::vector<MemoryCheck> vChecks;
325325
for (size_t k = 0; k < r && total; k++) {
326326
total--;

src/test/coins_tests.cpp

Lines changed: 39 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
#include "undo.h"
99
#include "utilstrencodings.h"
1010
#include "test/test_bitcoin.h"
11-
#include "test/test_random.h"
1211
#include "validation.h"
1312
#include "consensus/validation.h"
1413

@@ -44,7 +43,7 @@ class CCoinsViewTest : public CCoinsView
4443
return false;
4544
}
4645
coin = it->second;
47-
if (coin.IsSpent() && insecure_rand() % 2 == 0) {
46+
if (coin.IsSpent() && InsecureRandBool() == 0) {
4847
// Randomly return false in case of an empty entry.
4948
return false;
5049
}
@@ -65,7 +64,7 @@ class CCoinsViewTest : public CCoinsView
6564
if (it->second.flags & CCoinsCacheEntry::DIRTY) {
6665
// Same optimization used in CCoinsViewDB is to only write dirty entries.
6766
map_[it->first] = it->second.coin;
68-
if (it->second.coin.IsSpent() && insecure_rand() % 3 == 0) {
67+
if (it->second.coin.IsSpent() && InsecureRandRange(3) == 0) {
6968
// Randomly delete empty entries on write.
7069
map_.erase(it->first);
7170
}
@@ -140,31 +139,31 @@ BOOST_AUTO_TEST_CASE(coins_cache_simulation_test)
140139
std::vector<uint256> txids;
141140
txids.resize(NUM_SIMULATION_ITERATIONS / 8);
142141
for (unsigned int i = 0; i < txids.size(); i++) {
143-
txids[i] = GetRandHash();
142+
txids[i] = InsecureRand256();
144143
}
145144

146145
for (unsigned int i = 0; i < NUM_SIMULATION_ITERATIONS; i++) {
147146
// Do a random modification.
148147
{
149-
uint256 txid = txids[insecure_rand() % txids.size()]; // txid we're going to modify in this iteration.
148+
uint256 txid = txids[InsecureRandRange(txids.size())]; // txid we're going to modify in this iteration.
150149
Coin& coin = result[COutPoint(txid, 0)];
151-
const Coin& entry = (insecure_rand() % 500 == 0) ? AccessByTxid(*stack.back(), txid) : stack.back()->AccessCoin(COutPoint(txid, 0));
150+
const Coin& entry = (InsecureRandRange(500) == 0) ? AccessByTxid(*stack.back(), txid) : stack.back()->AccessCoin(COutPoint(txid, 0));
152151
BOOST_CHECK(coin == entry);
153152

154-
if (insecure_rand() % 5 == 0 || coin.IsSpent()) {
153+
if (InsecureRandRange(5) == 0 || coin.IsSpent()) {
155154
Coin newcoin;
156-
newcoin.out.nValue = insecure_rand();
155+
newcoin.out.nValue = InsecureRand32();
157156
newcoin.nHeight = 1;
158-
if (insecure_rand() % 16 == 0 && coin.IsSpent()) {
159-
newcoin.out.scriptPubKey.assign(1 + (insecure_rand() & 0x3F), OP_RETURN);
157+
if (InsecureRandRange(16) == 0 && coin.IsSpent()) {
158+
newcoin.out.scriptPubKey.assign(1 + InsecureRandBits(6), OP_RETURN);
160159
BOOST_CHECK(newcoin.out.scriptPubKey.IsUnspendable());
161160
added_an_unspendable_entry = true;
162161
} else {
163-
newcoin.out.scriptPubKey.assign(insecure_rand() & 0x3F, 0); // Random sizes so we can test memory usage accounting
162+
newcoin.out.scriptPubKey.assign(InsecureRandBits(6), 0); // Random sizes so we can test memory usage accounting
164163
(coin.IsSpent() ? added_an_entry : updated_an_entry) = true;
165164
coin = newcoin;
166165
}
167-
stack.back()->AddCoin(COutPoint(txid, 0), std::move(newcoin), !coin.IsSpent() || insecure_rand() & 1);
166+
stack.back()->AddCoin(COutPoint(txid, 0), std::move(newcoin), !coin.IsSpent() || InsecureRand32() & 1);
168167
} else {
169168
removed_an_entry = true;
170169
coin.Clear();
@@ -173,15 +172,15 @@ BOOST_AUTO_TEST_CASE(coins_cache_simulation_test)
173172
}
174173

175174
// One every 10 iterations, remove a random entry from the cache
176-
if (insecure_rand() % 10 == 0) {
177-
COutPoint out(txids[insecure_rand() % txids.size()], 0);
178-
int cacheid = insecure_rand() % stack.size();
175+
if (InsecureRandRange(10) == 0) {
176+
COutPoint out(txids[InsecureRand32() % txids.size()], 0);
177+
int cacheid = InsecureRand32() % stack.size();
179178
stack[cacheid]->Uncache(out);
180179
uncached_an_entry |= !stack[cacheid]->HaveCoinInCache(out);
181180
}
182181

183182
// Once every 1000 iterations and at the end, verify the full cache.
184-
if (insecure_rand() % 1000 == 1 || i == NUM_SIMULATION_ITERATIONS - 1) {
183+
if (InsecureRandRange(1000) == 1 || i == NUM_SIMULATION_ITERATIONS - 1) {
185184
for (auto it = result.begin(); it != result.end(); it++) {
186185
bool have = stack.back()->HaveCoin(it->first);
187186
const Coin& coin = stack.back()->AccessCoin(it->first);
@@ -199,22 +198,22 @@ BOOST_AUTO_TEST_CASE(coins_cache_simulation_test)
199198
}
200199
}
201200

202-
if (insecure_rand() % 100 == 0) {
201+
if (InsecureRandRange(100) == 0) {
203202
// Every 100 iterations, flush an intermediate cache
204-
if (stack.size() > 1 && insecure_rand() % 2 == 0) {
205-
unsigned int flushIndex = insecure_rand() % (stack.size() - 1);
203+
if (stack.size() > 1 && InsecureRandBool() == 0) {
204+
unsigned int flushIndex = InsecureRandRange(stack.size() - 1);
206205
stack[flushIndex]->Flush();
207206
}
208207
}
209-
if (insecure_rand() % 100 == 0) {
208+
if (InsecureRandRange(100) == 0) {
210209
// Every 100 iterations, change the cache stack.
211-
if (stack.size() > 0 && insecure_rand() % 2 == 0) {
210+
if (stack.size() > 0 && InsecureRandBool() == 0) {
212211
//Remove the top cache
213212
stack.back()->Flush();
214213
delete stack.back();
215214
stack.pop_back();
216215
}
217-
if (stack.size() == 0 || (stack.size() < 4 && insecure_rand() % 2)) {
216+
if (stack.size() == 0 || (stack.size() < 4 && InsecureRandBool())) {
218217
//Add a new cache
219218
CCoinsView* tip = &base;
220219
if (stack.size() > 0) {
@@ -254,7 +253,7 @@ UtxoData utxoData;
254253

255254
UtxoData::iterator FindRandomFrom(const std::set<COutPoint> &utxoSet) {
256255
assert(utxoSet.size());
257-
auto utxoSetIt = utxoSet.lower_bound(COutPoint(GetRandHash(), 0));
256+
auto utxoSetIt = utxoSet.lower_bound(COutPoint(InsecureRand256(), 0));
258257
if (utxoSetIt == utxoSet.end()) {
259258
utxoSetIt = utxoSet.begin();
260259
}
@@ -287,22 +286,22 @@ BOOST_AUTO_TEST_CASE(updatecoins_simulation_test)
287286
std::set<COutPoint> utxoset;
288287

289288
for (unsigned int i = 0; i < NUM_SIMULATION_ITERATIONS; i++) {
290-
uint32_t randiter = insecure_rand();
289+
uint32_t randiter = InsecureRand32();
291290

292291
// 19/20 txs add a new transaction
293292
if (randiter % 20 < 19) {
294293
CMutableTransaction tx;
295294
tx.vin.resize(1);
296295
tx.vout.resize(1);
297296
tx.vout[0].nValue = i; //Keep txs unique unless intended to duplicate
298-
tx.vout[0].scriptPubKey.assign(insecure_rand() & 0x3F, 0); // Random sizes so we can test memory usage accounting
299-
unsigned int height = insecure_rand();
297+
tx.vout[0].scriptPubKey.assign(InsecureRand32() & 0x3F, 0); // Random sizes so we can test memory usage accounting
298+
unsigned int height = InsecureRand32();
300299
Coin old_coin;
301300

302301
// 2/20 times create a new coinbase
303302
if (randiter % 20 < 2 || coinbase_coins.size() < 10) {
304303
// 1/10 of those times create a duplicate coinbase
305-
if (insecure_rand() % 10 == 0 && coinbase_coins.size()) {
304+
if (InsecureRandRange(10) == 0 && coinbase_coins.size()) {
306305
auto utxod = FindRandomFrom(coinbase_coins);
307306
// Reuse the exact same coinbase
308307
tx = std::get<0>(utxod->second);
@@ -412,7 +411,7 @@ BOOST_AUTO_TEST_CASE(updatecoins_simulation_test)
412411
}
413412

414413
// Once every 1000 iterations and at the end, verify the full cache.
415-
if (insecure_rand() % 1000 == 1 || i == NUM_SIMULATION_ITERATIONS - 1) {
414+
if (InsecureRandRange(1000) == 1 || i == NUM_SIMULATION_ITERATIONS - 1) {
416415
for (auto it = result.begin(); it != result.end(); it++) {
417416
bool have = stack.back()->HaveCoin(it->first);
418417
const Coin& coin = stack.back()->AccessCoin(it->first);
@@ -422,31 +421,31 @@ BOOST_AUTO_TEST_CASE(updatecoins_simulation_test)
422421
}
423422

424423
// One every 10 iterations, remove a random entry from the cache
425-
if (utxoset.size() > 1 && insecure_rand() % 30 == 0) {
426-
stack[insecure_rand() % stack.size()]->Uncache(FindRandomFrom(utxoset)->first);
424+
if (utxoset.size() > 1 && InsecureRandRange(30) == 0) {
425+
stack[InsecureRand32() % stack.size()]->Uncache(FindRandomFrom(utxoset)->first);
427426
}
428-
if (disconnected_coins.size() > 1 && insecure_rand() % 30 == 0) {
429-
stack[insecure_rand() % stack.size()]->Uncache(FindRandomFrom(disconnected_coins)->first);
427+
if (disconnected_coins.size() > 1 && InsecureRandRange(30) == 0) {
428+
stack[InsecureRand32() % stack.size()]->Uncache(FindRandomFrom(disconnected_coins)->first);
430429
}
431-
if (duplicate_coins.size() > 1 && insecure_rand() % 30 == 0) {
432-
stack[insecure_rand() % stack.size()]->Uncache(FindRandomFrom(duplicate_coins)->first);
430+
if (duplicate_coins.size() > 1 && InsecureRandRange(30) == 0) {
431+
stack[InsecureRand32() % stack.size()]->Uncache(FindRandomFrom(duplicate_coins)->first);
433432
}
434433

435-
if (insecure_rand() % 100 == 0) {
434+
if (InsecureRandRange(100) == 0) {
436435
// Every 100 iterations, flush an intermediate cache
437-
if (stack.size() > 1 && insecure_rand() % 2 == 0) {
438-
unsigned int flushIndex = insecure_rand() % (stack.size() - 1);
436+
if (stack.size() > 1 && InsecureRandBool() == 0) {
437+
unsigned int flushIndex = InsecureRandRange(stack.size() - 1);
439438
stack[flushIndex]->Flush();
440439
}
441440
}
442-
if (insecure_rand() % 100 == 0) {
441+
if (InsecureRandRange(100) == 0) {
443442
// Every 100 iterations, change the cache stack.
444-
if (stack.size() > 0 && insecure_rand() % 2 == 0) {
443+
if (stack.size() > 0 && InsecureRandBool() == 0) {
445444
stack.back()->Flush();
446445
delete stack.back();
447446
stack.pop_back();
448447
}
449-
if (stack.size() == 0 || (stack.size() < 4 && insecure_rand() % 2)) {
448+
if (stack.size() == 0 || (stack.size() < 4 && InsecureRandBool())) {
450449
CCoinsView* tip = &base;
451450
if (stack.size() > 0) {
452451
tip = stack.back();

src/test/crypto_tests.cpp

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
#include "random.h"
1414
#include "utilstrencodings.h"
1515
#include "test/test_bitcoin.h"
16-
#include "test/test_random.h"
1716

1817
#include <vector>
1918

@@ -39,7 +38,7 @@ void TestVector(const Hasher &h, const In &in, const Out &out) {
3938
Hasher hasher(h);
4039
size_t pos = 0;
4140
while (pos < in.size()) {
42-
size_t len = insecure_rand() % ((in.size() - pos + 1) / 2 + 1);
41+
size_t len = InsecureRandRange((in.size() - pos + 1) / 2 + 1);
4342
hasher.Write((unsigned char*)&in[pos], len);
4443
pos += len;
4544
if (pos > 0 && pos + 2 * out.size() > in.size() && pos < in.size()) {

0 commit comments

Comments
 (0)