Merge #10321: Use FastRandomContext for all tests

e94584858 scripted-diff: Use new naming style for insecure_rand* functions (Pieter Wuille)
2fcd9cc86 scripted-diff: Use randbits/bool instead of randrange where possible (Pieter Wuille)
2ada67852 Use randbits instead of ad-hoc emulation in prevector tests (Pieter Wuille)
5f0b04eed Replace rand() & ((1 << N) - 1) with randbits(N) (Pieter Wuille)
3ecabae36 Replace more rand() % NUM by randranges (Pieter Wuille)
efee1db21 scripted-diff: use insecure_rand256/randrange more (Pieter Wuille)
1119927df Add various insecure_rand wrappers for tests (Pieter Wuille)
124d13a58 Merge test_random.h into test_bitcoin.h (Pieter Wuille)
90620d66c scripted-diff: Rename cuckoo tests' local rand context (Pieter Wuille)
37e864eb9 Add FastRandomContext::rand256() and ::randbytes() (Pieter Wuille)

Tree-SHA512: d09705a3ec718ae792f7d66a75401903ba7b9c9d3fc36669d6e3b9242f0194738106be26baefc8a8e3fa6df7c9a35978c71c0c430278a028b331df23a3ea3070
This commit is contained in:
Pieter Wuille 2017-06-07 14:59:41 -07:00
commit e801084dec
No known key found for this signature in database
GPG key ID: A636E97631F767E0
26 changed files with 202 additions and 190 deletions

View file

@ -74,7 +74,6 @@ BITCOIN_TESTS =\
test/test_bitcoin.cpp \ test/test_bitcoin.cpp \
test/test_bitcoin.h \ test/test_bitcoin.h \
test/test_bitcoin_main.cpp \ test/test_bitcoin_main.cpp \
test/test_random.h \
test/testutil.cpp \ test/testutil.cpp \
test/testutil.h \ test/testutil.h \
test/timedata_tests.cpp \ test/timedata_tests.cpp \

View file

@ -304,6 +304,26 @@ void FastRandomContext::RandomSeed()
requires_seed = false; requires_seed = false;
} }
uint256 FastRandomContext::rand256()
{
if (bytebuf_size < 32) {
FillByteBuffer();
}
uint256 ret;
memcpy(ret.begin(), bytebuf + 64 - bytebuf_size, 32);
bytebuf_size -= 32;
return ret;
}
std::vector<unsigned char> FastRandomContext::randbytes(size_t len)
{
std::vector<unsigned char> ret(len);
if (len > 0) {
rng.Output(&ret[0], len);
}
return ret;
}
FastRandomContext::FastRandomContext(const uint256& seed) : requires_seed(false), bytebuf_size(0), bitbuf_size(0) FastRandomContext::FastRandomContext(const uint256& seed) : requires_seed(false), bytebuf_size(0), bitbuf_size(0)
{ {
rng.SetKey(seed.begin(), 32); rng.SetKey(seed.begin(), 32);

View file

@ -110,9 +110,15 @@ public:
} }
} }
/** Generate random bytes. */
std::vector<unsigned char> randbytes(size_t len);
/** Generate a random 32-bit integer. */ /** Generate a random 32-bit integer. */
uint32_t rand32() { return randbits(32); } uint32_t rand32() { return randbits(32); }
/** generate a random uint256. */
uint256 rand256();
/** Generate a random boolean. */ /** Generate a random boolean. */
bool randbool() { return randbits(1); } bool randbool() { return randbits(1); }
}; };

View file

@ -129,7 +129,7 @@ BOOST_AUTO_TEST_CASE(DoS_bantime)
CTransactionRef RandomOrphan() CTransactionRef RandomOrphan()
{ {
std::map<uint256, COrphanTx>::iterator it; std::map<uint256, COrphanTx>::iterator it;
it = mapOrphanTransactions.lower_bound(GetRandHash()); it = mapOrphanTransactions.lower_bound(InsecureRand256());
if (it == mapOrphanTransactions.end()) if (it == mapOrphanTransactions.end())
it = mapOrphanTransactions.begin(); it = mapOrphanTransactions.begin();
return it->second.tx; return it->second.tx;
@ -148,7 +148,7 @@ BOOST_AUTO_TEST_CASE(DoS_mapOrphans)
CMutableTransaction tx; CMutableTransaction tx;
tx.vin.resize(1); tx.vin.resize(1);
tx.vin[0].prevout.n = 0; tx.vin[0].prevout.n = 0;
tx.vin[0].prevout.hash = GetRandHash(); tx.vin[0].prevout.hash = InsecureRand256();
tx.vin[0].scriptSig << OP_1; tx.vin[0].scriptSig << OP_1;
tx.vout.resize(1); tx.vout.resize(1);
tx.vout[0].nValue = 1*CENT; tx.vout[0].nValue = 1*CENT;

View file

@ -30,16 +30,16 @@ static CBlock BuildBlockTestCase() {
block.vtx.resize(3); block.vtx.resize(3);
block.vtx[0] = MakeTransactionRef(tx); block.vtx[0] = MakeTransactionRef(tx);
block.nVersion = 42; block.nVersion = 42;
block.hashPrevBlock = GetRandHash(); block.hashPrevBlock = InsecureRand256();
block.nBits = 0x207fffff; block.nBits = 0x207fffff;
tx.vin[0].prevout.hash = GetRandHash(); tx.vin[0].prevout.hash = InsecureRand256();
tx.vin[0].prevout.n = 0; tx.vin[0].prevout.n = 0;
block.vtx[1] = MakeTransactionRef(tx); block.vtx[1] = MakeTransactionRef(tx);
tx.vin.resize(10); tx.vin.resize(10);
for (size_t i = 0; i < tx.vin.size(); i++) { for (size_t i = 0; i < tx.vin.size(); i++) {
tx.vin[i].prevout.hash = GetRandHash(); tx.vin[i].prevout.hash = InsecureRand256();
tx.vin[i].prevout.n = 0; tx.vin[i].prevout.n = 0;
} }
block.vtx[2] = MakeTransactionRef(tx); block.vtx[2] = MakeTransactionRef(tx);
@ -283,7 +283,7 @@ BOOST_AUTO_TEST_CASE(EmptyBlockRoundTripTest)
block.vtx.resize(1); block.vtx.resize(1);
block.vtx[0] = MakeTransactionRef(std::move(coinbase)); block.vtx[0] = MakeTransactionRef(std::move(coinbase));
block.nVersion = 42; block.nVersion = 42;
block.hashPrevBlock = GetRandHash(); block.hashPrevBlock = InsecureRand256();
block.nBits = 0x207fffff; block.nBits = 0x207fffff;
bool mutated; bool mutated;
@ -316,7 +316,7 @@ BOOST_AUTO_TEST_CASE(EmptyBlockRoundTripTest)
BOOST_AUTO_TEST_CASE(TransactionsRequestSerializationTest) { BOOST_AUTO_TEST_CASE(TransactionsRequestSerializationTest) {
BlockTransactionsRequest req1; BlockTransactionsRequest req1;
req1.blockhash = GetRandHash(); req1.blockhash = InsecureRand256();
req1.indexes.resize(4); req1.indexes.resize(4);
req1.indexes[0] = 0; req1.indexes[0] = 0;
req1.indexes[1] = 1; req1.indexes[1] = 1;

View file

@ -463,7 +463,7 @@ BOOST_AUTO_TEST_CASE(merkle_block_4_test_update_none)
static std::vector<unsigned char> RandomData() static std::vector<unsigned char> RandomData()
{ {
uint256 r = GetRandHash(); uint256 r = InsecureRand256();
return std::vector<unsigned char>(r.begin(), r.end()); return std::vector<unsigned char>(r.begin(), r.end());
} }

View file

@ -160,7 +160,7 @@ void Correct_Queue_range(std::vector<size_t> range)
FakeCheckCheckCompletion::n_calls = 0; FakeCheckCheckCompletion::n_calls = 0;
CCheckQueueControl<FakeCheckCheckCompletion> control(small_queue.get()); CCheckQueueControl<FakeCheckCheckCompletion> control(small_queue.get());
while (total) { while (total) {
vChecks.resize(std::min(total, (size_t) GetRand(10))); vChecks.resize(std::min(total, (size_t) InsecureRandRange(10)));
total -= vChecks.size(); total -= vChecks.size();
control.Add(vChecks); control.Add(vChecks);
} }
@ -204,7 +204,7 @@ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Random)
{ {
std::vector<size_t> range; std::vector<size_t> range;
range.reserve(100000/1000); range.reserve(100000/1000);
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)))) 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))))
range.push_back(i); range.push_back(i);
Correct_Queue_range(range); Correct_Queue_range(range);
} }
@ -224,7 +224,7 @@ BOOST_AUTO_TEST_CASE(test_CheckQueue_Catches_Failure)
CCheckQueueControl<FailingCheck> control(fail_queue.get()); CCheckQueueControl<FailingCheck> control(fail_queue.get());
size_t remaining = i; size_t remaining = i;
while (remaining) { while (remaining) {
size_t r = GetRand(10); size_t r = InsecureRandRange(10);
std::vector<FailingCheck> vChecks; std::vector<FailingCheck> vChecks;
vChecks.reserve(r); vChecks.reserve(r);
@ -286,7 +286,7 @@ BOOST_AUTO_TEST_CASE(test_CheckQueue_UniqueCheck)
{ {
CCheckQueueControl<UniqueCheck> control(queue.get()); CCheckQueueControl<UniqueCheck> control(queue.get());
while (total) { while (total) {
size_t r = GetRand(10); size_t r = InsecureRandRange(10);
std::vector<UniqueCheck> vChecks; std::vector<UniqueCheck> vChecks;
for (size_t k = 0; k < r && total; k++) for (size_t k = 0; k < r && total; k++)
vChecks.emplace_back(--total); vChecks.emplace_back(--total);
@ -320,7 +320,7 @@ BOOST_AUTO_TEST_CASE(test_CheckQueue_Memory)
{ {
CCheckQueueControl<MemoryCheck> control(queue.get()); CCheckQueueControl<MemoryCheck> control(queue.get());
while (total) { while (total) {
size_t r = GetRand(10); size_t r = InsecureRandRange(10);
std::vector<MemoryCheck> vChecks; std::vector<MemoryCheck> vChecks;
for (size_t k = 0; k < r && total; k++) { for (size_t k = 0; k < r && total; k++) {
total--; total--;

View file

@ -8,7 +8,6 @@
#include "undo.h" #include "undo.h"
#include "utilstrencodings.h" #include "utilstrencodings.h"
#include "test/test_bitcoin.h" #include "test/test_bitcoin.h"
#include "test/test_random.h"
#include "validation.h" #include "validation.h"
#include "consensus/validation.h" #include "consensus/validation.h"
@ -44,7 +43,7 @@ public:
return false; return false;
} }
coin = it->second; coin = it->second;
if (coin.IsSpent() && insecure_rand() % 2 == 0) { if (coin.IsSpent() && InsecureRandBool() == 0) {
// Randomly return false in case of an empty entry. // Randomly return false in case of an empty entry.
return false; return false;
} }
@ -65,7 +64,7 @@ public:
if (it->second.flags & CCoinsCacheEntry::DIRTY) { if (it->second.flags & CCoinsCacheEntry::DIRTY) {
// Same optimization used in CCoinsViewDB is to only write dirty entries. // Same optimization used in CCoinsViewDB is to only write dirty entries.
map_[it->first] = it->second.coin; map_[it->first] = it->second.coin;
if (it->second.coin.IsSpent() && insecure_rand() % 3 == 0) { if (it->second.coin.IsSpent() && InsecureRandRange(3) == 0) {
// Randomly delete empty entries on write. // Randomly delete empty entries on write.
map_.erase(it->first); map_.erase(it->first);
} }
@ -140,31 +139,31 @@ BOOST_AUTO_TEST_CASE(coins_cache_simulation_test)
std::vector<uint256> txids; std::vector<uint256> txids;
txids.resize(NUM_SIMULATION_ITERATIONS / 8); txids.resize(NUM_SIMULATION_ITERATIONS / 8);
for (unsigned int i = 0; i < txids.size(); i++) { for (unsigned int i = 0; i < txids.size(); i++) {
txids[i] = GetRandHash(); txids[i] = InsecureRand256();
} }
for (unsigned int i = 0; i < NUM_SIMULATION_ITERATIONS; i++) { for (unsigned int i = 0; i < NUM_SIMULATION_ITERATIONS; i++) {
// Do a random modification. // Do a random modification.
{ {
uint256 txid = txids[insecure_rand() % txids.size()]; // txid we're going to modify in this iteration. uint256 txid = txids[InsecureRandRange(txids.size())]; // txid we're going to modify in this iteration.
Coin& coin = result[COutPoint(txid, 0)]; Coin& coin = result[COutPoint(txid, 0)];
const Coin& entry = (insecure_rand() % 500 == 0) ? AccessByTxid(*stack.back(), txid) : stack.back()->AccessCoin(COutPoint(txid, 0)); const Coin& entry = (InsecureRandRange(500) == 0) ? AccessByTxid(*stack.back(), txid) : stack.back()->AccessCoin(COutPoint(txid, 0));
BOOST_CHECK(coin == entry); BOOST_CHECK(coin == entry);
if (insecure_rand() % 5 == 0 || coin.IsSpent()) { if (InsecureRandRange(5) == 0 || coin.IsSpent()) {
Coin newcoin; Coin newcoin;
newcoin.out.nValue = insecure_rand(); newcoin.out.nValue = InsecureRand32();
newcoin.nHeight = 1; newcoin.nHeight = 1;
if (insecure_rand() % 16 == 0 && coin.IsSpent()) { if (InsecureRandRange(16) == 0 && coin.IsSpent()) {
newcoin.out.scriptPubKey.assign(1 + (insecure_rand() & 0x3F), OP_RETURN); newcoin.out.scriptPubKey.assign(1 + InsecureRandBits(6), OP_RETURN);
BOOST_CHECK(newcoin.out.scriptPubKey.IsUnspendable()); BOOST_CHECK(newcoin.out.scriptPubKey.IsUnspendable());
added_an_unspendable_entry = true; added_an_unspendable_entry = true;
} else { } else {
newcoin.out.scriptPubKey.assign(insecure_rand() & 0x3F, 0); // Random sizes so we can test memory usage accounting newcoin.out.scriptPubKey.assign(InsecureRandBits(6), 0); // Random sizes so we can test memory usage accounting
(coin.IsSpent() ? added_an_entry : updated_an_entry) = true; (coin.IsSpent() ? added_an_entry : updated_an_entry) = true;
coin = newcoin; coin = newcoin;
} }
stack.back()->AddCoin(COutPoint(txid, 0), std::move(newcoin), !coin.IsSpent() || insecure_rand() & 1); stack.back()->AddCoin(COutPoint(txid, 0), std::move(newcoin), !coin.IsSpent() || InsecureRand32() & 1);
} else { } else {
removed_an_entry = true; removed_an_entry = true;
coin.Clear(); coin.Clear();
@ -173,15 +172,15 @@ BOOST_AUTO_TEST_CASE(coins_cache_simulation_test)
} }
// One every 10 iterations, remove a random entry from the cache // One every 10 iterations, remove a random entry from the cache
if (insecure_rand() % 10 == 0) { if (InsecureRandRange(10) == 0) {
COutPoint out(txids[insecure_rand() % txids.size()], 0); COutPoint out(txids[InsecureRand32() % txids.size()], 0);
int cacheid = insecure_rand() % stack.size(); int cacheid = InsecureRand32() % stack.size();
stack[cacheid]->Uncache(out); stack[cacheid]->Uncache(out);
uncached_an_entry |= !stack[cacheid]->HaveCoinInCache(out); uncached_an_entry |= !stack[cacheid]->HaveCoinInCache(out);
} }
// Once every 1000 iterations and at the end, verify the full cache. // Once every 1000 iterations and at the end, verify the full cache.
if (insecure_rand() % 1000 == 1 || i == NUM_SIMULATION_ITERATIONS - 1) { if (InsecureRandRange(1000) == 1 || i == NUM_SIMULATION_ITERATIONS - 1) {
for (auto it = result.begin(); it != result.end(); it++) { for (auto it = result.begin(); it != result.end(); it++) {
bool have = stack.back()->HaveCoin(it->first); bool have = stack.back()->HaveCoin(it->first);
const Coin& coin = stack.back()->AccessCoin(it->first); const Coin& coin = stack.back()->AccessCoin(it->first);
@ -199,22 +198,22 @@ BOOST_AUTO_TEST_CASE(coins_cache_simulation_test)
} }
} }
if (insecure_rand() % 100 == 0) { if (InsecureRandRange(100) == 0) {
// Every 100 iterations, flush an intermediate cache // Every 100 iterations, flush an intermediate cache
if (stack.size() > 1 && insecure_rand() % 2 == 0) { if (stack.size() > 1 && InsecureRandBool() == 0) {
unsigned int flushIndex = insecure_rand() % (stack.size() - 1); unsigned int flushIndex = InsecureRandRange(stack.size() - 1);
stack[flushIndex]->Flush(); stack[flushIndex]->Flush();
} }
} }
if (insecure_rand() % 100 == 0) { if (InsecureRandRange(100) == 0) {
// Every 100 iterations, change the cache stack. // Every 100 iterations, change the cache stack.
if (stack.size() > 0 && insecure_rand() % 2 == 0) { if (stack.size() > 0 && InsecureRandBool() == 0) {
//Remove the top cache //Remove the top cache
stack.back()->Flush(); stack.back()->Flush();
delete stack.back(); delete stack.back();
stack.pop_back(); stack.pop_back();
} }
if (stack.size() == 0 || (stack.size() < 4 && insecure_rand() % 2)) { if (stack.size() == 0 || (stack.size() < 4 && InsecureRandBool())) {
//Add a new cache //Add a new cache
CCoinsView* tip = &base; CCoinsView* tip = &base;
if (stack.size() > 0) { if (stack.size() > 0) {
@ -254,7 +253,7 @@ UtxoData utxoData;
UtxoData::iterator FindRandomFrom(const std::set<COutPoint> &utxoSet) { UtxoData::iterator FindRandomFrom(const std::set<COutPoint> &utxoSet) {
assert(utxoSet.size()); assert(utxoSet.size());
auto utxoSetIt = utxoSet.lower_bound(COutPoint(GetRandHash(), 0)); auto utxoSetIt = utxoSet.lower_bound(COutPoint(InsecureRand256(), 0));
if (utxoSetIt == utxoSet.end()) { if (utxoSetIt == utxoSet.end()) {
utxoSetIt = utxoSet.begin(); utxoSetIt = utxoSet.begin();
} }
@ -287,7 +286,7 @@ BOOST_AUTO_TEST_CASE(updatecoins_simulation_test)
std::set<COutPoint> utxoset; std::set<COutPoint> utxoset;
for (unsigned int i = 0; i < NUM_SIMULATION_ITERATIONS; i++) { for (unsigned int i = 0; i < NUM_SIMULATION_ITERATIONS; i++) {
uint32_t randiter = insecure_rand(); uint32_t randiter = InsecureRand32();
// 19/20 txs add a new transaction // 19/20 txs add a new transaction
if (randiter % 20 < 19) { if (randiter % 20 < 19) {
@ -295,14 +294,14 @@ BOOST_AUTO_TEST_CASE(updatecoins_simulation_test)
tx.vin.resize(1); tx.vin.resize(1);
tx.vout.resize(1); tx.vout.resize(1);
tx.vout[0].nValue = i; //Keep txs unique unless intended to duplicate tx.vout[0].nValue = i; //Keep txs unique unless intended to duplicate
tx.vout[0].scriptPubKey.assign(insecure_rand() & 0x3F, 0); // Random sizes so we can test memory usage accounting tx.vout[0].scriptPubKey.assign(InsecureRand32() & 0x3F, 0); // Random sizes so we can test memory usage accounting
unsigned int height = insecure_rand(); unsigned int height = InsecureRand32();
Coin old_coin; Coin old_coin;
// 2/20 times create a new coinbase // 2/20 times create a new coinbase
if (randiter % 20 < 2 || coinbase_coins.size() < 10) { if (randiter % 20 < 2 || coinbase_coins.size() < 10) {
// 1/10 of those times create a duplicate coinbase // 1/10 of those times create a duplicate coinbase
if (insecure_rand() % 10 == 0 && coinbase_coins.size()) { if (InsecureRandRange(10) == 0 && coinbase_coins.size()) {
auto utxod = FindRandomFrom(coinbase_coins); auto utxod = FindRandomFrom(coinbase_coins);
// Reuse the exact same coinbase // Reuse the exact same coinbase
tx = std::get<0>(utxod->second); tx = std::get<0>(utxod->second);
@ -412,7 +411,7 @@ BOOST_AUTO_TEST_CASE(updatecoins_simulation_test)
} }
// Once every 1000 iterations and at the end, verify the full cache. // Once every 1000 iterations and at the end, verify the full cache.
if (insecure_rand() % 1000 == 1 || i == NUM_SIMULATION_ITERATIONS - 1) { if (InsecureRandRange(1000) == 1 || i == NUM_SIMULATION_ITERATIONS - 1) {
for (auto it = result.begin(); it != result.end(); it++) { for (auto it = result.begin(); it != result.end(); it++) {
bool have = stack.back()->HaveCoin(it->first); bool have = stack.back()->HaveCoin(it->first);
const Coin& coin = stack.back()->AccessCoin(it->first); const Coin& coin = stack.back()->AccessCoin(it->first);
@ -422,31 +421,31 @@ BOOST_AUTO_TEST_CASE(updatecoins_simulation_test)
} }
// One every 10 iterations, remove a random entry from the cache // One every 10 iterations, remove a random entry from the cache
if (utxoset.size() > 1 && insecure_rand() % 30 == 0) { if (utxoset.size() > 1 && InsecureRandRange(30) == 0) {
stack[insecure_rand() % stack.size()]->Uncache(FindRandomFrom(utxoset)->first); stack[InsecureRand32() % stack.size()]->Uncache(FindRandomFrom(utxoset)->first);
} }
if (disconnected_coins.size() > 1 && insecure_rand() % 30 == 0) { if (disconnected_coins.size() > 1 && InsecureRandRange(30) == 0) {
stack[insecure_rand() % stack.size()]->Uncache(FindRandomFrom(disconnected_coins)->first); stack[InsecureRand32() % stack.size()]->Uncache(FindRandomFrom(disconnected_coins)->first);
} }
if (duplicate_coins.size() > 1 && insecure_rand() % 30 == 0) { if (duplicate_coins.size() > 1 && InsecureRandRange(30) == 0) {
stack[insecure_rand() % stack.size()]->Uncache(FindRandomFrom(duplicate_coins)->first); stack[InsecureRand32() % stack.size()]->Uncache(FindRandomFrom(duplicate_coins)->first);
} }
if (insecure_rand() % 100 == 0) { if (InsecureRandRange(100) == 0) {
// Every 100 iterations, flush an intermediate cache // Every 100 iterations, flush an intermediate cache
if (stack.size() > 1 && insecure_rand() % 2 == 0) { if (stack.size() > 1 && InsecureRandBool() == 0) {
unsigned int flushIndex = insecure_rand() % (stack.size() - 1); unsigned int flushIndex = InsecureRandRange(stack.size() - 1);
stack[flushIndex]->Flush(); stack[flushIndex]->Flush();
} }
} }
if (insecure_rand() % 100 == 0) { if (InsecureRandRange(100) == 0) {
// Every 100 iterations, change the cache stack. // Every 100 iterations, change the cache stack.
if (stack.size() > 0 && insecure_rand() % 2 == 0) { if (stack.size() > 0 && InsecureRandBool() == 0) {
stack.back()->Flush(); stack.back()->Flush();
delete stack.back(); delete stack.back();
stack.pop_back(); stack.pop_back();
} }
if (stack.size() == 0 || (stack.size() < 4 && insecure_rand() % 2)) { if (stack.size() == 0 || (stack.size() < 4 && InsecureRandBool())) {
CCoinsView* tip = &base; CCoinsView* tip = &base;
if (stack.size() > 0) { if (stack.size() > 0) {
tip = stack.back(); tip = stack.back();

View file

@ -13,7 +13,6 @@
#include "random.h" #include "random.h"
#include "utilstrencodings.h" #include "utilstrencodings.h"
#include "test/test_bitcoin.h" #include "test/test_bitcoin.h"
#include "test/test_random.h"
#include <vector> #include <vector>
@ -39,7 +38,7 @@ void TestVector(const Hasher &h, const In &in, const Out &out) {
Hasher hasher(h); Hasher hasher(h);
size_t pos = 0; size_t pos = 0;
while (pos < in.size()) { while (pos < in.size()) {
size_t len = insecure_rand() % ((in.size() - pos + 1) / 2 + 1); size_t len = InsecureRandRange((in.size() - pos + 1) / 2 + 1);
hasher.Write((unsigned char*)&in[pos], len); hasher.Write((unsigned char*)&in[pos], len);
pos += len; pos += len;
if (pos > 0 && pos + 2 * out.size() > in.size() && pos < in.size()) { if (pos > 0 && pos + 2 * out.size() > in.size() && pos < in.size()) {

View file

@ -23,18 +23,18 @@
* using BOOST_CHECK_CLOSE to fail. * using BOOST_CHECK_CLOSE to fail.
* *
*/ */
FastRandomContext insecure_rand(true); FastRandomContext local_rand_ctx(true);
BOOST_AUTO_TEST_SUITE(cuckoocache_tests); BOOST_AUTO_TEST_SUITE(cuckoocache_tests);
/** insecure_GetRandHash fills in a uint256 from insecure_rand /** insecure_GetRandHash fills in a uint256 from local_rand_ctx
*/ */
void insecure_GetRandHash(uint256& t) void insecure_GetRandHash(uint256& t)
{ {
uint32_t* ptr = (uint32_t*)t.begin(); uint32_t* ptr = (uint32_t*)t.begin();
for (uint8_t j = 0; j < 8; ++j) for (uint8_t j = 0; j < 8; ++j)
*(ptr++) = insecure_rand.rand32(); *(ptr++) = local_rand_ctx.rand32();
} }
@ -45,7 +45,7 @@ void insecure_GetRandHash(uint256& t)
*/ */
BOOST_AUTO_TEST_CASE(test_cuckoocache_no_fakes) BOOST_AUTO_TEST_CASE(test_cuckoocache_no_fakes)
{ {
insecure_rand = FastRandomContext(true); local_rand_ctx = FastRandomContext(true);
CuckooCache::cache<uint256, SignatureCacheHasher> cc{}; CuckooCache::cache<uint256, SignatureCacheHasher> cc{};
size_t megabytes = 4; size_t megabytes = 4;
cc.setup_bytes(megabytes << 20); cc.setup_bytes(megabytes << 20);
@ -66,7 +66,7 @@ BOOST_AUTO_TEST_CASE(test_cuckoocache_no_fakes)
template <typename Cache> template <typename Cache>
double test_cache(size_t megabytes, double load) double test_cache(size_t megabytes, double load)
{ {
insecure_rand = FastRandomContext(true); local_rand_ctx = FastRandomContext(true);
std::vector<uint256> hashes; std::vector<uint256> hashes;
Cache set{}; Cache set{};
size_t bytes = megabytes * (1 << 20); size_t bytes = megabytes * (1 << 20);
@ -76,7 +76,7 @@ double test_cache(size_t megabytes, double load)
for (uint32_t i = 0; i < n_insert; ++i) { for (uint32_t i = 0; i < n_insert; ++i) {
uint32_t* ptr = (uint32_t*)hashes[i].begin(); uint32_t* ptr = (uint32_t*)hashes[i].begin();
for (uint8_t j = 0; j < 8; ++j) for (uint8_t j = 0; j < 8; ++j)
*(ptr++) = insecure_rand.rand32(); *(ptr++) = local_rand_ctx.rand32();
} }
/** We make a copy of the hashes because future optimizations of the /** We make a copy of the hashes because future optimizations of the
* cuckoocache may overwrite the inserted element, so the test is * cuckoocache may overwrite the inserted element, so the test is
@ -137,7 +137,7 @@ template <typename Cache>
void test_cache_erase(size_t megabytes) void test_cache_erase(size_t megabytes)
{ {
double load = 1; double load = 1;
insecure_rand = FastRandomContext(true); local_rand_ctx = FastRandomContext(true);
std::vector<uint256> hashes; std::vector<uint256> hashes;
Cache set{}; Cache set{};
size_t bytes = megabytes * (1 << 20); size_t bytes = megabytes * (1 << 20);
@ -147,7 +147,7 @@ void test_cache_erase(size_t megabytes)
for (uint32_t i = 0; i < n_insert; ++i) { for (uint32_t i = 0; i < n_insert; ++i) {
uint32_t* ptr = (uint32_t*)hashes[i].begin(); uint32_t* ptr = (uint32_t*)hashes[i].begin();
for (uint8_t j = 0; j < 8; ++j) for (uint8_t j = 0; j < 8; ++j)
*(ptr++) = insecure_rand.rand32(); *(ptr++) = local_rand_ctx.rand32();
} }
/** We make a copy of the hashes because future optimizations of the /** We make a copy of the hashes because future optimizations of the
* cuckoocache may overwrite the inserted element, so the test is * cuckoocache may overwrite the inserted element, so the test is
@ -200,7 +200,7 @@ template <typename Cache>
void test_cache_erase_parallel(size_t megabytes) void test_cache_erase_parallel(size_t megabytes)
{ {
double load = 1; double load = 1;
insecure_rand = FastRandomContext(true); local_rand_ctx = FastRandomContext(true);
std::vector<uint256> hashes; std::vector<uint256> hashes;
Cache set{}; Cache set{};
size_t bytes = megabytes * (1 << 20); size_t bytes = megabytes * (1 << 20);
@ -210,7 +210,7 @@ void test_cache_erase_parallel(size_t megabytes)
for (uint32_t i = 0; i < n_insert; ++i) { for (uint32_t i = 0; i < n_insert; ++i) {
uint32_t* ptr = (uint32_t*)hashes[i].begin(); uint32_t* ptr = (uint32_t*)hashes[i].begin();
for (uint8_t j = 0; j < 8; ++j) for (uint8_t j = 0; j < 8; ++j)
*(ptr++) = insecure_rand.rand32(); *(ptr++) = local_rand_ctx.rand32();
} }
/** We make a copy of the hashes because future optimizations of the /** We make a copy of the hashes because future optimizations of the
* cuckoocache may overwrite the inserted element, so the test is * cuckoocache may overwrite the inserted element, so the test is
@ -302,7 +302,7 @@ void test_cache_generations()
// iterations with non-deterministic values, so it isn't "overfit" to the // iterations with non-deterministic values, so it isn't "overfit" to the
// specific entropy in FastRandomContext(true) and implementation of the // specific entropy in FastRandomContext(true) and implementation of the
// cache. // cache.
insecure_rand = FastRandomContext(true); local_rand_ctx = FastRandomContext(true);
// block_activity models a chunk of network activity. n_insert elements are // block_activity models a chunk of network activity. n_insert elements are
// adde to the cache. The first and last n/4 are stored for removal later // adde to the cache. The first and last n/4 are stored for removal later
@ -319,7 +319,7 @@ void test_cache_generations()
for (uint32_t i = 0; i < n_insert; ++i) { for (uint32_t i = 0; i < n_insert; ++i) {
uint32_t* ptr = (uint32_t*)inserts[i].begin(); uint32_t* ptr = (uint32_t*)inserts[i].begin();
for (uint8_t j = 0; j < 8; ++j) for (uint8_t j = 0; j < 8; ++j)
*(ptr++) = insecure_rand.rand32(); *(ptr++) = local_rand_ctx.rand32();
} }
for (uint32_t i = 0; i < n_insert / 4; ++i) for (uint32_t i = 0; i < n_insert / 4; ++i)
reads.push_back(inserts[i]); reads.push_back(inserts[i]);

View file

@ -31,7 +31,7 @@ BOOST_AUTO_TEST_CASE(dbwrapper)
fs::path ph = fs::temp_directory_path() / fs::unique_path(); fs::path ph = fs::temp_directory_path() / fs::unique_path();
CDBWrapper dbw(ph, (1 << 20), true, false, obfuscate); CDBWrapper dbw(ph, (1 << 20), true, false, obfuscate);
char key = 'k'; char key = 'k';
uint256 in = GetRandHash(); uint256 in = InsecureRand256();
uint256 res; uint256 res;
// Ensure that we're doing real obfuscation when obfuscate=true // Ensure that we're doing real obfuscation when obfuscate=true
@ -53,11 +53,11 @@ BOOST_AUTO_TEST_CASE(dbwrapper_batch)
CDBWrapper dbw(ph, (1 << 20), true, false, obfuscate); CDBWrapper dbw(ph, (1 << 20), true, false, obfuscate);
char key = 'i'; char key = 'i';
uint256 in = GetRandHash(); uint256 in = InsecureRand256();
char key2 = 'j'; char key2 = 'j';
uint256 in2 = GetRandHash(); uint256 in2 = InsecureRand256();
char key3 = 'k'; char key3 = 'k';
uint256 in3 = GetRandHash(); uint256 in3 = InsecureRand256();
uint256 res; uint256 res;
CDBBatch batch(dbw); CDBBatch batch(dbw);
@ -91,10 +91,10 @@ BOOST_AUTO_TEST_CASE(dbwrapper_iterator)
// The two keys are intentionally chosen for ordering // The two keys are intentionally chosen for ordering
char key = 'j'; char key = 'j';
uint256 in = GetRandHash(); uint256 in = InsecureRand256();
BOOST_CHECK(dbw.Write(key, in)); BOOST_CHECK(dbw.Write(key, in));
char key2 = 'k'; char key2 = 'k';
uint256 in2 = GetRandHash(); uint256 in2 = InsecureRand256();
BOOST_CHECK(dbw.Write(key2, in2)); BOOST_CHECK(dbw.Write(key2, in2));
std::unique_ptr<CDBIterator> it(const_cast<CDBWrapper*>(&dbw)->NewIterator()); std::unique_ptr<CDBIterator> it(const_cast<CDBWrapper*>(&dbw)->NewIterator());
@ -132,7 +132,7 @@ BOOST_AUTO_TEST_CASE(existing_data_no_obfuscate)
// Set up a non-obfuscated wrapper to write some initial data. // Set up a non-obfuscated wrapper to write some initial data.
CDBWrapper* dbw = new CDBWrapper(ph, (1 << 10), false, false, false); CDBWrapper* dbw = new CDBWrapper(ph, (1 << 10), false, false, false);
char key = 'k'; char key = 'k';
uint256 in = GetRandHash(); uint256 in = InsecureRand256();
uint256 res; uint256 res;
BOOST_CHECK(dbw->Write(key, in)); BOOST_CHECK(dbw->Write(key, in));
@ -155,7 +155,7 @@ BOOST_AUTO_TEST_CASE(existing_data_no_obfuscate)
BOOST_CHECK(!odbw.IsEmpty()); // There should be existing data BOOST_CHECK(!odbw.IsEmpty()); // There should be existing data
BOOST_CHECK(is_null_key(dbwrapper_private::GetObfuscateKey(odbw))); // The key should be an empty string BOOST_CHECK(is_null_key(dbwrapper_private::GetObfuscateKey(odbw))); // The key should be an empty string
uint256 in2 = GetRandHash(); uint256 in2 = InsecureRand256();
uint256 res3; uint256 res3;
// Check that we can write successfully // Check that we can write successfully
@ -174,7 +174,7 @@ BOOST_AUTO_TEST_CASE(existing_data_reindex)
// Set up a non-obfuscated wrapper to write some initial data. // Set up a non-obfuscated wrapper to write some initial data.
CDBWrapper* dbw = new CDBWrapper(ph, (1 << 10), false, false, false); CDBWrapper* dbw = new CDBWrapper(ph, (1 << 10), false, false, false);
char key = 'k'; char key = 'k';
uint256 in = GetRandHash(); uint256 in = InsecureRand256();
uint256 res; uint256 res;
BOOST_CHECK(dbw->Write(key, in)); BOOST_CHECK(dbw->Write(key, in));
@ -193,7 +193,7 @@ BOOST_AUTO_TEST_CASE(existing_data_reindex)
BOOST_CHECK(!odbw.Read(key, res2)); BOOST_CHECK(!odbw.Read(key, res2));
BOOST_CHECK(!is_null_key(dbwrapper_private::GetObfuscateKey(odbw))); BOOST_CHECK(!is_null_key(dbwrapper_private::GetObfuscateKey(odbw)));
uint256 in2 = GetRandHash(); uint256 in2 = InsecureRand256();
uint256 res3; uint256 res3;
// Check that we can write successfully // Check that we can write successfully

View file

@ -134,7 +134,7 @@ BOOST_AUTO_TEST_CASE(siphash)
for (int i = 0; i < 16; ++i) { for (int i = 0; i < 16; ++i) {
uint64_t k1 = ctx.rand64(); uint64_t k1 = ctx.rand64();
uint64_t k2 = ctx.rand64(); uint64_t k2 = ctx.rand64();
uint256 x = GetRandHash(); uint256 x = InsecureRand256();
uint32_t n = ctx.rand32(); uint32_t n = ctx.rand32();
uint8_t nb[4]; uint8_t nb[4];
WriteLE32(nb, n); WriteLE32(nb, n);

View file

@ -4,7 +4,6 @@
#include "consensus/merkle.h" #include "consensus/merkle.h"
#include "test/test_bitcoin.h" #include "test/test_bitcoin.h"
#include "test/test_random.h"
#include <boost/test/unit_test.hpp> #include <boost/test/unit_test.hpp>
@ -68,7 +67,7 @@ BOOST_AUTO_TEST_CASE(merkle_test)
{ {
for (int i = 0; i < 32; i++) { for (int i = 0; i < 32; i++) {
// Try 32 block sizes: all sizes from 0 to 16 inclusive, and then 15 random sizes. // Try 32 block sizes: all sizes from 0 to 16 inclusive, and then 15 random sizes.
int ntx = (i <= 16) ? i : 17 + (insecure_rand() % 4000); int ntx = (i <= 16) ? i : 17 + (InsecureRandRange(4000));
// Try up to 3 mutations. // Try up to 3 mutations.
for (int mutate = 0; mutate <= 3; mutate++) { for (int mutate = 0; mutate <= 3; mutate++) {
int duplicate1 = mutate >= 1 ? 1 << ctz(ntx) : 0; // The last how many transactions to duplicate first. int duplicate1 = mutate >= 1 ? 1 << ctz(ntx) : 0; // The last how many transactions to duplicate first.
@ -121,7 +120,7 @@ BOOST_AUTO_TEST_CASE(merkle_test)
// If ntx <= 16, try all branches. Otherwise, try 16 random ones. // If ntx <= 16, try all branches. Otherwise, try 16 random ones.
int mtx = loop; int mtx = loop;
if (ntx > 16) { if (ntx > 16) {
mtx = insecure_rand() % ntx; mtx = InsecureRandRange(ntx);
} }
std::vector<uint256> newBranch = BlockMerkleBranch(block, mtx); std::vector<uint256> newBranch = BlockMerkleBranch(block, mtx);
std::vector<uint256> oldBranch = BlockGetMerkleBranch(block, merkleTree, mtx); std::vector<uint256> oldBranch = BlockGetMerkleBranch(block, merkleTree, mtx);

View file

@ -372,7 +372,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
while (chainActive.Tip()->nHeight < 209999) { while (chainActive.Tip()->nHeight < 209999) {
CBlockIndex* prev = chainActive.Tip(); CBlockIndex* prev = chainActive.Tip();
CBlockIndex* next = new CBlockIndex(); CBlockIndex* next = new CBlockIndex();
next->phashBlock = new uint256(GetRandHash()); next->phashBlock = new uint256(InsecureRand256());
pcoinsTip->SetBestBlock(next->GetBlockHash()); pcoinsTip->SetBestBlock(next->GetBlockHash());
next->pprev = prev; next->pprev = prev;
next->nHeight = prev->nHeight + 1; next->nHeight = prev->nHeight + 1;
@ -384,7 +384,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
while (chainActive.Tip()->nHeight < 210000) { while (chainActive.Tip()->nHeight < 210000) {
CBlockIndex* prev = chainActive.Tip(); CBlockIndex* prev = chainActive.Tip();
CBlockIndex* next = new CBlockIndex(); CBlockIndex* next = new CBlockIndex();
next->phashBlock = new uint256(GetRandHash()); next->phashBlock = new uint256(InsecureRand256());
pcoinsTip->SetBestBlock(next->GetBlockHash()); pcoinsTip->SetBestBlock(next->GetBlockHash());
next->pprev = prev; next->pprev = prev;
next->nHeight = prev->nHeight + 1; next->nHeight = prev->nHeight + 1;

View file

@ -10,7 +10,6 @@
#include "arith_uint256.h" #include "arith_uint256.h"
#include "version.h" #include "version.h"
#include "test/test_bitcoin.h" #include "test/test_bitcoin.h"
#include "test/test_random.h"
#include <vector> #include <vector>
@ -22,8 +21,8 @@ class CPartialMerkleTreeTester : public CPartialMerkleTree
public: public:
// flip one bit in one of the hashes - this should break the authentication // flip one bit in one of the hashes - this should break the authentication
void Damage() { void Damage() {
unsigned int n = insecure_rand() % vHash.size(); unsigned int n = InsecureRandRange(vHash.size());
int bit = insecure_rand() % 256; int bit = InsecureRandBits(8);
*(vHash[n].begin() + (bit>>3)) ^= 1<<(bit&7); *(vHash[n].begin() + (bit>>3)) ^= 1<<(bit&7);
} }
}; };
@ -32,7 +31,7 @@ BOOST_FIXTURE_TEST_SUITE(pmt_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(pmt_test1) BOOST_AUTO_TEST_CASE(pmt_test1)
{ {
seed_insecure_rand(false); SeedInsecureRand(false);
static const unsigned int nTxCounts[] = {1, 4, 7, 17, 56, 100, 127, 256, 312, 513, 1000, 4095}; static const unsigned int nTxCounts[] = {1, 4, 7, 17, 56, 100, 127, 256, 312, 513, 1000, 4095};
for (int i = 0; i < 12; i++) { for (int i = 0; i < 12; i++) {
@ -63,7 +62,7 @@ BOOST_AUTO_TEST_CASE(pmt_test1)
std::vector<bool> vMatch(nTx, false); std::vector<bool> vMatch(nTx, false);
std::vector<uint256> vMatchTxid1; std::vector<uint256> vMatchTxid1;
for (unsigned int j=0; j<nTx; j++) { for (unsigned int j=0; j<nTx; j++) {
bool fInclude = (insecure_rand() & ((1 << (att/2)) - 1)) == 0; bool fInclude = InsecureRandBits(att / 2) == 0;
vMatch[j] = fInclude; vMatch[j] = fInclude;
if (fInclude) if (fInclude)
vMatchTxid1.push_back(vTxid[j]); vMatchTxid1.push_back(vTxid[j]);

View file

@ -74,9 +74,9 @@ BOOST_AUTO_TEST_CASE(GetBlockProofEquivalentTime_test)
} }
for (int j = 0; j < 1000; j++) { for (int j = 0; j < 1000; j++) {
CBlockIndex *p1 = &blocks[GetRand(10000)]; CBlockIndex *p1 = &blocks[InsecureRandRange(10000)];
CBlockIndex *p2 = &blocks[GetRand(10000)]; CBlockIndex *p2 = &blocks[InsecureRandRange(10000)];
CBlockIndex *p3 = &blocks[GetRand(10000)]; CBlockIndex *p3 = &blocks[InsecureRandRange(10000)];
int64_t tdiff = GetBlockProofEquivalentTime(*p1, *p2, *p3, chainParams->GetConsensus()); int64_t tdiff = GetBlockProofEquivalentTime(*p1, *p2, *p3, chainParams->GetConsensus());
BOOST_CHECK_EQUAL(tdiff, p1->GetBlockTime() - p2->GetBlockTime()); BOOST_CHECK_EQUAL(tdiff, p1->GetBlockTime() - p2->GetBlockTime());

View file

@ -9,7 +9,6 @@
#include "streams.h" #include "streams.h"
#include "test/test_bitcoin.h" #include "test/test_bitcoin.h"
#include "test/test_random.h"
#include <boost/test/unit_test.hpp> #include <boost/test/unit_test.hpp>
@ -188,7 +187,7 @@ public:
} }
prevector_tester() { prevector_tester() {
seed_insecure_rand(); SeedInsecureRand();
rand_seed = insecure_rand_seed; rand_seed = insecure_rand_seed;
rand_cache = insecure_rand_ctx; rand_cache = insecure_rand_ctx;
} }
@ -199,67 +198,65 @@ BOOST_AUTO_TEST_CASE(PrevectorTestInt)
for (int j = 0; j < 64; j++) { for (int j = 0; j < 64; j++) {
prevector_tester<8, int> test; prevector_tester<8, int> test;
for (int i = 0; i < 2048; i++) { for (int i = 0; i < 2048; i++) {
int r = insecure_rand(); if (InsecureRandBits(2) == 0) {
if ((r % 4) == 0) { test.insert(InsecureRandRange(test.size() + 1), InsecureRand32());
test.insert(insecure_rand() % (test.size() + 1), insecure_rand());
} }
if (test.size() > 0 && ((r >> 2) % 4) == 1) { if (test.size() > 0 && InsecureRandBits(2) == 1) {
test.erase(insecure_rand() % test.size()); test.erase(InsecureRandRange(test.size()));
} }
if (((r >> 4) % 8) == 2) { if (InsecureRandBits(3) == 2) {
int new_size = std::max<int>(0, std::min<int>(30, test.size() + (insecure_rand() % 5) - 2)); int new_size = std::max<int>(0, std::min<int>(30, test.size() + (InsecureRandRange(5)) - 2));
test.resize(new_size); test.resize(new_size);
} }
if (((r >> 7) % 8) == 3) { if (InsecureRandBits(3) == 3) {
test.insert(insecure_rand() % (test.size() + 1), 1 + (insecure_rand() % 2), insecure_rand()); test.insert(InsecureRandRange(test.size() + 1), 1 + InsecureRandBool(), InsecureRand32());
} }
if (((r >> 10) % 8) == 4) { if (InsecureRandBits(3) == 4) {
int del = std::min<int>(test.size(), 1 + (insecure_rand() % 2)); int del = std::min<int>(test.size(), 1 + (InsecureRandBool()));
int beg = insecure_rand() % (test.size() + 1 - del); int beg = InsecureRandRange(test.size() + 1 - del);
test.erase(beg, beg + del); test.erase(beg, beg + del);
} }
if (((r >> 13) % 16) == 5) { if (InsecureRandBits(4) == 5) {
test.push_back(insecure_rand()); test.push_back(InsecureRand32());
} }
if (test.size() > 0 && ((r >> 17) % 16) == 6) { if (test.size() > 0 && InsecureRandBits(4) == 6) {
test.pop_back(); test.pop_back();
} }
if (((r >> 21) % 32) == 7) { if (InsecureRandBits(5) == 7) {
int values[4]; int values[4];
int num = 1 + (insecure_rand() % 4); int num = 1 + (InsecureRandBits(2));
for (int k = 0; k < num; k++) { for (int k = 0; k < num; k++) {
values[k] = insecure_rand(); values[k] = InsecureRand32();
} }
test.insert_range(insecure_rand() % (test.size() + 1), values, values + num); test.insert_range(InsecureRandRange(test.size() + 1), values, values + num);
} }
if (((r >> 26) % 32) == 8) { if (InsecureRandBits(5) == 8) {
int del = std::min<int>(test.size(), 1 + (insecure_rand() % 4)); int del = std::min<int>(test.size(), 1 + (InsecureRandBits(2)));
int beg = insecure_rand() % (test.size() + 1 - del); int beg = InsecureRandRange(test.size() + 1 - del);
test.erase(beg, beg + del); test.erase(beg, beg + del);
} }
r = insecure_rand(); if (InsecureRandBits(5) == 9) {
if (r % 32 == 9) { test.reserve(InsecureRandBits(5));
test.reserve(insecure_rand() % 32);
} }
if ((r >> 5) % 64 == 10) { if (InsecureRandBits(6) == 10) {
test.shrink_to_fit(); test.shrink_to_fit();
} }
if (test.size() > 0) { if (test.size() > 0) {
test.update(insecure_rand() % test.size(), insecure_rand()); test.update(InsecureRandRange(test.size()), InsecureRand32());
} }
if (((r >> 11) % 1024) == 11) { if (InsecureRandBits(10) == 11) {
test.clear(); test.clear();
} }
if (((r >> 21) % 512) == 12) { if (InsecureRandBits(9) == 12) {
test.assign(insecure_rand() % 32, insecure_rand()); test.assign(InsecureRandBits(5), InsecureRand32());
} }
if (((r >> 15) % 8) == 3) { if (InsecureRandBits(3) == 3) {
test.swap(); test.swap();
} }
if (((r >> 15) % 16) == 8) { if (InsecureRandBits(4) == 8) {
test.copy(); test.copy();
} }
if (((r >> 15) % 32) == 18) { if (InsecureRandBits(5) == 18) {
test.move(); test.move();
} }
} }

View file

@ -25,14 +25,21 @@ BOOST_AUTO_TEST_CASE(fastrandom_tests)
BOOST_CHECK_EQUAL(ctx1.rand32(), ctx2.rand32()); BOOST_CHECK_EQUAL(ctx1.rand32(), ctx2.rand32());
BOOST_CHECK_EQUAL(ctx1.rand64(), ctx2.rand64()); BOOST_CHECK_EQUAL(ctx1.rand64(), ctx2.rand64());
BOOST_CHECK_EQUAL(ctx1.randbits(3), ctx2.randbits(3)); BOOST_CHECK_EQUAL(ctx1.randbits(3), ctx2.randbits(3));
BOOST_CHECK(ctx1.randbytes(17) == ctx2.randbytes(17));
BOOST_CHECK(ctx1.rand256() == ctx2.rand256());
BOOST_CHECK_EQUAL(ctx1.randbits(7), ctx2.randbits(7)); BOOST_CHECK_EQUAL(ctx1.randbits(7), ctx2.randbits(7));
BOOST_CHECK(ctx1.randbytes(128) == ctx2.randbytes(128));
BOOST_CHECK_EQUAL(ctx1.rand32(), ctx2.rand32()); BOOST_CHECK_EQUAL(ctx1.rand32(), ctx2.rand32());
BOOST_CHECK_EQUAL(ctx1.randbits(3), ctx2.randbits(3)); BOOST_CHECK_EQUAL(ctx1.randbits(3), ctx2.randbits(3));
BOOST_CHECK(ctx1.rand256() == ctx2.rand256());
BOOST_CHECK(ctx1.randbytes(50) == ctx2.randbytes(50));
// Check that a nondeterministic ones are not // Check that a nondeterministic ones are not
FastRandomContext ctx3; FastRandomContext ctx3;
FastRandomContext ctx4; FastRandomContext ctx4;
BOOST_CHECK(ctx3.rand64() != ctx4.rand64()); // extremely unlikely to be equal BOOST_CHECK(ctx3.rand64() != ctx4.rand64()); // extremely unlikely to be equal
BOOST_CHECK(ctx3.rand256() != ctx4.rand256());
BOOST_CHECK(ctx3.randbytes(7) != ctx4.randbytes(7));
} }
BOOST_AUTO_TEST_CASE(fastrandom_randbits) BOOST_AUTO_TEST_CASE(fastrandom_randbits)

View file

@ -11,7 +11,6 @@
#include "serialize.h" #include "serialize.h"
#include "streams.h" #include "streams.h"
#include "test/test_bitcoin.h" #include "test/test_bitcoin.h"
#include "test/test_random.h"
#include "util.h" #include "util.h"
#include "utilstrencodings.h" #include "utilstrencodings.h"
#include "version.h" #include "version.h"
@ -90,30 +89,30 @@ uint256 static SignatureHashOld(CScript scriptCode, const CTransaction& txTo, un
void static RandomScript(CScript &script) { void static RandomScript(CScript &script) {
static const opcodetype oplist[] = {OP_FALSE, OP_1, OP_2, OP_3, OP_CHECKSIG, OP_IF, OP_VERIF, OP_RETURN, OP_CODESEPARATOR}; static const opcodetype oplist[] = {OP_FALSE, OP_1, OP_2, OP_3, OP_CHECKSIG, OP_IF, OP_VERIF, OP_RETURN, OP_CODESEPARATOR};
script = CScript(); script = CScript();
int ops = (insecure_rand() % 10); int ops = (InsecureRandRange(10));
for (int i=0; i<ops; i++) for (int i=0; i<ops; i++)
script << oplist[insecure_rand() % (sizeof(oplist)/sizeof(oplist[0]))]; script << oplist[InsecureRandRange(sizeof(oplist)/sizeof(oplist[0]))];
} }
void static RandomTransaction(CMutableTransaction &tx, bool fSingle) { void static RandomTransaction(CMutableTransaction &tx, bool fSingle) {
tx.nVersion = insecure_rand(); tx.nVersion = InsecureRand32();
tx.vin.clear(); tx.vin.clear();
tx.vout.clear(); tx.vout.clear();
tx.nLockTime = (insecure_rand() % 2) ? insecure_rand() : 0; tx.nLockTime = (InsecureRandBool()) ? InsecureRand32() : 0;
int ins = (insecure_rand() % 4) + 1; int ins = (InsecureRandBits(2)) + 1;
int outs = fSingle ? ins : (insecure_rand() % 4) + 1; int outs = fSingle ? ins : (InsecureRandBits(2)) + 1;
for (int in = 0; in < ins; in++) { for (int in = 0; in < ins; in++) {
tx.vin.push_back(CTxIn()); tx.vin.push_back(CTxIn());
CTxIn &txin = tx.vin.back(); CTxIn &txin = tx.vin.back();
txin.prevout.hash = GetRandHash(); txin.prevout.hash = InsecureRand256();
txin.prevout.n = insecure_rand() % 4; txin.prevout.n = InsecureRandBits(2);
RandomScript(txin.scriptSig); RandomScript(txin.scriptSig);
txin.nSequence = (insecure_rand() % 2) ? insecure_rand() : (unsigned int)-1; txin.nSequence = (InsecureRandBool()) ? InsecureRand32() : (unsigned int)-1;
} }
for (int out = 0; out < outs; out++) { for (int out = 0; out < outs; out++) {
tx.vout.push_back(CTxOut()); tx.vout.push_back(CTxOut());
CTxOut &txout = tx.vout.back(); CTxOut &txout = tx.vout.back();
txout.nValue = insecure_rand() % 100000000; txout.nValue = InsecureRandRange(100000000);
RandomScript(txout.scriptPubKey); RandomScript(txout.scriptPubKey);
} }
} }
@ -122,7 +121,7 @@ BOOST_FIXTURE_TEST_SUITE(sighash_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(sighash_test) BOOST_AUTO_TEST_CASE(sighash_test)
{ {
seed_insecure_rand(false); SeedInsecureRand(false);
#if defined(PRINT_SIGHASH_JSON) #if defined(PRINT_SIGHASH_JSON)
std::cout << "[\n"; std::cout << "[\n";
@ -134,12 +133,12 @@ BOOST_AUTO_TEST_CASE(sighash_test)
nRandomTests = 500; nRandomTests = 500;
#endif #endif
for (int i=0; i<nRandomTests; i++) { for (int i=0; i<nRandomTests; i++) {
int nHashType = insecure_rand(); int nHashType = InsecureRand32();
CMutableTransaction txTo; CMutableTransaction txTo;
RandomTransaction(txTo, (nHashType & 0x1f) == SIGHASH_SINGLE); RandomTransaction(txTo, (nHashType & 0x1f) == SIGHASH_SINGLE);
CScript scriptCode; CScript scriptCode;
RandomScript(scriptCode); RandomScript(scriptCode);
int nIn = insecure_rand() % txTo.vin.size(); int nIn = InsecureRandRange(txTo.vin.size());
uint256 sh, sho; uint256 sh, sho;
sho = SignatureHashOld(scriptCode, txTo, nIn, nHashType); sho = SignatureHashOld(scriptCode, txTo, nIn, nHashType);

View file

@ -5,7 +5,6 @@
#include "chain.h" #include "chain.h"
#include "util.h" #include "util.h"
#include "test/test_bitcoin.h" #include "test/test_bitcoin.h"
#include "test/test_random.h"
#include <vector> #include <vector>
@ -35,8 +34,8 @@ BOOST_AUTO_TEST_CASE(skiplist_test)
} }
for (int i=0; i < 1000; i++) { for (int i=0; i < 1000; i++) {
int from = insecure_rand() % (SKIPLIST_LENGTH - 1); int from = InsecureRandRange(SKIPLIST_LENGTH - 1);
int to = insecure_rand() % (from + 1); int to = InsecureRandRange(from + 1);
BOOST_CHECK(vIndex[SKIPLIST_LENGTH - 1].GetAncestor(from) == &vIndex[from]); BOOST_CHECK(vIndex[SKIPLIST_LENGTH - 1].GetAncestor(from) == &vIndex[from]);
BOOST_CHECK(vIndex[from].GetAncestor(to) == &vIndex[to]); BOOST_CHECK(vIndex[from].GetAncestor(to) == &vIndex[to]);
@ -78,7 +77,7 @@ BOOST_AUTO_TEST_CASE(getlocator_test)
// Test 100 random starting points for locators. // Test 100 random starting points for locators.
for (int n=0; n<100; n++) { for (int n=0; n<100; n++) {
int r = insecure_rand() % 150000; int r = InsecureRandRange(150000);
CBlockIndex* tip = (r < 100000) ? &vBlocksMain[r] : &vBlocksSide[r - 100000]; CBlockIndex* tip = (r < 100000) ? &vBlocksMain[r] : &vBlocksSide[r - 100000];
CBlockLocator locator = chain.GetLocator(tip); CBlockLocator locator = chain.GetLocator(tip);
@ -116,7 +115,7 @@ BOOST_AUTO_TEST_CASE(findearliestatleast_test)
} else { } else {
// randomly choose something in the range [MTP, MTP*2] // randomly choose something in the range [MTP, MTP*2]
int64_t medianTimePast = vBlocksMain[i].GetMedianTimePast(); int64_t medianTimePast = vBlocksMain[i].GetMedianTimePast();
int r = insecure_rand() % medianTimePast; int r = InsecureRandRange(medianTimePast);
vBlocksMain[i].nTime = r + medianTimePast; vBlocksMain[i].nTime = r + medianTimePast;
vBlocksMain[i].nTimeMax = std::max(vBlocksMain[i].nTime, vBlocksMain[i-1].nTimeMax); vBlocksMain[i].nTimeMax = std::max(vBlocksMain[i].nTime, vBlocksMain[i-1].nTimeMax);
} }
@ -135,7 +134,7 @@ BOOST_AUTO_TEST_CASE(findearliestatleast_test)
// Verify that FindEarliestAtLeast is correct. // Verify that FindEarliestAtLeast is correct.
for (unsigned int i=0; i<10000; ++i) { for (unsigned int i=0; i<10000; ++i) {
// Pick a random element in vBlocksMain. // Pick a random element in vBlocksMain.
int r = insecure_rand() % vBlocksMain.size(); int r = InsecureRandRange(vBlocksMain.size());
int64_t test_time = vBlocksMain[r].nTime; int64_t test_time = vBlocksMain[r].nTime;
CBlockIndex *ret = chain.FindEarliestAtLeast(test_time); CBlockIndex *ret = chain.FindEarliestAtLeast(test_time);
BOOST_CHECK(ret->nTimeMax >= test_time); BOOST_CHECK(ret->nTimeMax >= test_time);

View file

@ -59,7 +59,7 @@ TestingSetup::TestingSetup(const std::string& chainName) : BasicTestingSetup(cha
RegisterAllCoreRPCCommands(tableRPC); RegisterAllCoreRPCCommands(tableRPC);
ClearDatadirCache(); ClearDatadirCache();
pathTemp = GetTempPath() / strprintf("test_bitcoin_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000))); pathTemp = GetTempPath() / strprintf("test_bitcoin_%lu_%i", (unsigned long)GetTime(), (int)(InsecureRandRange(100000)));
fs::create_directories(pathTemp); fs::create_directories(pathTemp);
ForceSetArg("-datadir", pathTemp.string()); ForceSetArg("-datadir", pathTemp.string());
mempool.setSanityCheck(1.0); mempool.setSanityCheck(1.0);

View file

@ -9,11 +9,32 @@
#include "fs.h" #include "fs.h"
#include "key.h" #include "key.h"
#include "pubkey.h" #include "pubkey.h"
#include "random.h"
#include "txdb.h" #include "txdb.h"
#include "txmempool.h" #include "txmempool.h"
#include <boost/thread.hpp> #include <boost/thread.hpp>
extern uint256 insecure_rand_seed;
extern FastRandomContext insecure_rand_ctx;
static inline void SeedInsecureRand(bool fDeterministic = false)
{
if (fDeterministic) {
insecure_rand_seed = uint256();
} else {
insecure_rand_seed = GetRandHash();
}
insecure_rand_ctx = FastRandomContext(insecure_rand_seed);
}
static inline uint32_t InsecureRand32() { return insecure_rand_ctx.rand32(); }
static inline uint256 InsecureRand256() { return insecure_rand_ctx.rand256(); }
static inline uint64_t InsecureRandBits(int bits) { return insecure_rand_ctx.randbits(bits); }
static inline uint64_t InsecureRandRange(uint64_t range) { return insecure_rand_ctx.randrange(range); }
static inline bool InsecureRandBool() { return insecure_rand_ctx.randbool(); }
static inline std::vector<unsigned char> InsecureRandBytes(size_t len) { return insecure_rand_ctx.randbytes(len); }
/** Basic testing setup. /** Basic testing setup.
* This just configures logging and chain parameters. * This just configures logging and chain parameters.
*/ */

View file

@ -1,29 +0,0 @@
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_TEST_RANDOM_H
#define BITCOIN_TEST_RANDOM_H
#include "random.h"
extern uint256 insecure_rand_seed;
extern FastRandomContext insecure_rand_ctx;
static inline void seed_insecure_rand(bool fDeterministic = false)
{
if (fDeterministic) {
insecure_rand_seed = uint256();
} else {
insecure_rand_seed = GetRandHash();
}
insecure_rand_ctx = FastRandomContext(insecure_rand_seed);
}
static inline uint32_t insecure_rand(void)
{
return insecure_rand_ctx.rand32();
}
#endif

View file

@ -10,7 +10,6 @@
#include "utilstrencodings.h" #include "utilstrencodings.h"
#include "utilmoneystr.h" #include "utilmoneystr.h"
#include "test/test_bitcoin.h" #include "test/test_bitcoin.h"
#include "test/test_random.h"
#include <stdint.h> #include <stdint.h>
#include <vector> #include <vector>
@ -256,7 +255,7 @@ BOOST_AUTO_TEST_CASE(util_IsHex)
BOOST_AUTO_TEST_CASE(util_seed_insecure_rand) BOOST_AUTO_TEST_CASE(util_seed_insecure_rand)
{ {
seed_insecure_rand(true); SeedInsecureRand(true);
for (int mod=2;mod<11;mod++) for (int mod=2;mod<11;mod++)
{ {
int mask = 1; int mask = 1;
@ -270,7 +269,7 @@ BOOST_AUTO_TEST_CASE(util_seed_insecure_rand)
for (int i = 0; i < 10000; i++) { for (int i = 0; i < 10000; i++) {
uint32_t rval; uint32_t rval;
do{ do{
rval=insecure_rand()&mask; rval=InsecureRand32()&mask;
}while(rval>=(uint32_t)mod); }while(rval>=(uint32_t)mod);
count += rval==0; count += rval==0;
} }

View file

@ -5,7 +5,6 @@
#include "chain.h" #include "chain.h"
#include "versionbits.h" #include "versionbits.h"
#include "test/test_bitcoin.h" #include "test/test_bitcoin.h"
#include "test/test_random.h"
#include "chainparams.h" #include "chainparams.h"
#include "validation.h" #include "validation.h"
#include "consensus/params.h" #include "consensus/params.h"
@ -81,7 +80,7 @@ public:
VersionBitsTester& TestStateSinceHeight(int height) { VersionBitsTester& TestStateSinceHeight(int height) {
for (int i = 0; i < CHECKERS; i++) { for (int i = 0; i < CHECKERS; i++) {
if ((insecure_rand() & ((1 << i) - 1)) == 0) { if (InsecureRandBits(i) == 0) {
BOOST_CHECK_MESSAGE(checker[i].GetStateSinceHeightFor(vpblock.empty() ? NULL : vpblock.back()) == height, strprintf("Test %i for StateSinceHeight", num)); BOOST_CHECK_MESSAGE(checker[i].GetStateSinceHeightFor(vpblock.empty() ? NULL : vpblock.back()) == height, strprintf("Test %i for StateSinceHeight", num));
} }
} }
@ -91,7 +90,7 @@ public:
VersionBitsTester& TestDefined() { VersionBitsTester& TestDefined() {
for (int i = 0; i < CHECKERS; i++) { for (int i = 0; i < CHECKERS; i++) {
if ((insecure_rand() & ((1 << i) - 1)) == 0) { if (InsecureRandBits(i) == 0) {
BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? NULL : vpblock.back()) == THRESHOLD_DEFINED, strprintf("Test %i for DEFINED", num)); BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? NULL : vpblock.back()) == THRESHOLD_DEFINED, strprintf("Test %i for DEFINED", num));
} }
} }
@ -101,7 +100,7 @@ public:
VersionBitsTester& TestStarted() { VersionBitsTester& TestStarted() {
for (int i = 0; i < CHECKERS; i++) { for (int i = 0; i < CHECKERS; i++) {
if ((insecure_rand() & ((1 << i) - 1)) == 0) { if (InsecureRandBits(i) == 0) {
BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? NULL : vpblock.back()) == THRESHOLD_STARTED, strprintf("Test %i for STARTED", num)); BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? NULL : vpblock.back()) == THRESHOLD_STARTED, strprintf("Test %i for STARTED", num));
} }
} }
@ -111,7 +110,7 @@ public:
VersionBitsTester& TestLockedIn() { VersionBitsTester& TestLockedIn() {
for (int i = 0; i < CHECKERS; i++) { for (int i = 0; i < CHECKERS; i++) {
if ((insecure_rand() & ((1 << i) - 1)) == 0) { if (InsecureRandBits(i) == 0) {
BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? NULL : vpblock.back()) == THRESHOLD_LOCKED_IN, strprintf("Test %i for LOCKED_IN", num)); BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? NULL : vpblock.back()) == THRESHOLD_LOCKED_IN, strprintf("Test %i for LOCKED_IN", num));
} }
} }
@ -121,7 +120,7 @@ public:
VersionBitsTester& TestActive() { VersionBitsTester& TestActive() {
for (int i = 0; i < CHECKERS; i++) { for (int i = 0; i < CHECKERS; i++) {
if ((insecure_rand() & ((1 << i) - 1)) == 0) { if (InsecureRandBits(i) == 0) {
BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? NULL : vpblock.back()) == THRESHOLD_ACTIVE, strprintf("Test %i for ACTIVE", num)); BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? NULL : vpblock.back()) == THRESHOLD_ACTIVE, strprintf("Test %i for ACTIVE", num));
} }
} }
@ -131,7 +130,7 @@ public:
VersionBitsTester& TestFailed() { VersionBitsTester& TestFailed() {
for (int i = 0; i < CHECKERS; i++) { for (int i = 0; i < CHECKERS; i++) {
if ((insecure_rand() & ((1 << i) - 1)) == 0) { if (InsecureRandBits(i) == 0) {
BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? NULL : vpblock.back()) == THRESHOLD_FAILED, strprintf("Test %i for FAILED", num)); BOOST_CHECK_MESSAGE(checker[i].GetStateFor(vpblock.empty() ? NULL : vpblock.back()) == THRESHOLD_FAILED, strprintf("Test %i for FAILED", num));
} }
} }

View file

@ -2,9 +2,8 @@
// Distributed under the MIT software license, see the accompanying // Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "test/test_random.h"
#include "utilstrencodings.h"
#include "test/test_bitcoin.h" #include "test/test_bitcoin.h"
#include "utilstrencodings.h"
#include "wallet/crypter.h" #include "wallet/crypter.h"
#include <vector> #include <vector>
@ -193,7 +192,7 @@ BOOST_AUTO_TEST_CASE(passphrase) {
std::string hash(GetRandHash().ToString()); std::string hash(GetRandHash().ToString());
std::vector<unsigned char> vchSalt(8); std::vector<unsigned char> vchSalt(8);
GetRandBytes(&vchSalt[0], vchSalt.size()); GetRandBytes(&vchSalt[0], vchSalt.size());
uint32_t rounds = insecure_rand(); uint32_t rounds = InsecureRand32();
if (rounds > 30000) if (rounds > 30000)
rounds = 30000; rounds = 30000;
TestCrypter::TestPassphrase(vchSalt, SecureString(hash.begin(), hash.end()), rounds); TestCrypter::TestPassphrase(vchSalt, SecureString(hash.begin(), hash.end()), rounds);