From fa54cab4734f02422f28fdffc0f11e6d3d51b8f0 Mon Sep 17 00:00:00 2001 From: MarcoFalke <*~=`'#}+{/-|&$^_@721217.xyz> Date: Fri, 2 Aug 2024 12:30:13 +0200 Subject: [PATCH] test: refactor: Accept any RandomNumberGenerator in RandMoney Accepting any Rng in RandMoney makes tests more flexible to use a different Rng. Also, passing in the Rng clarifies the call sites, so that they all use g_rand_ctx explicitly and consistently. --- src/test/coins_tests.cpp | 2 +- src/test/sighash_tests.cpp | 2 +- src/test/util/coins.cpp | 2 +- src/test/util/random.h | 7 ++++--- 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/test/coins_tests.cpp b/src/test/coins_tests.cpp index ac52cb9b2be..de62ad99674 100644 --- a/src/test/coins_tests.cpp +++ b/src/test/coins_tests.cpp @@ -182,7 +182,7 @@ void SimulationTest(CCoinsView* base, bool fake_best_block) if (InsecureRandRange(5) == 0 || coin.IsSpent()) { Coin newcoin; - newcoin.out.nValue = InsecureRandMoneyAmount(); + newcoin.out.nValue = RandMoney(m_rng); newcoin.nHeight = 1; // Infrequently test adding unspendable coins. diff --git a/src/test/sighash_tests.cpp b/src/test/sighash_tests.cpp index a77e921c664..884370e73d7 100644 --- a/src/test/sighash_tests.cpp +++ b/src/test/sighash_tests.cpp @@ -110,7 +110,7 @@ void RandomTransaction(CMutableTransaction& tx, bool fSingle) for (int out = 0; out < outs; out++) { tx.vout.emplace_back(); CTxOut &txout = tx.vout.back(); - txout.nValue = InsecureRandMoneyAmount(); + txout.nValue = RandMoney(m_rng); RandomScript(txout.scriptPubKey); } } diff --git a/src/test/util/coins.cpp b/src/test/util/coins.cpp index 0a52581d0ec..7e10c7c58d3 100644 --- a/src/test/util/coins.cpp +++ b/src/test/util/coins.cpp @@ -18,7 +18,7 @@ COutPoint AddTestCoin(FastRandomContext& rng, CCoinsViewCache& coins_view) Coin new_coin; COutPoint outpoint{Txid::FromUint256(rng.rand256()), /*nIn=*/0}; new_coin.nHeight = 1; - new_coin.out.nValue = InsecureRandMoneyAmount(); + new_coin.out.nValue = RandMoney(rng); new_coin.out.scriptPubKey.assign(uint32_t{56}, 1); coins_view.AddCoin(outpoint, std::move(new_coin), /*possible_overwrite=*/false); diff --git a/src/test/util/random.h b/src/test/util/random.h index 5ffb06bde77..10215ccbe5d 100644 --- a/src/test/util/random.h +++ b/src/test/util/random.h @@ -1,4 +1,4 @@ -// Copyright (c) 2023 The Bitcoin Core developers +// Copyright (c) 2023-present The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. @@ -52,9 +52,10 @@ static inline bool InsecureRandBool() return g_insecure_rand_ctx.randbool(); } -static inline CAmount InsecureRandMoneyAmount() +template +inline CAmount RandMoney(Rng&& rng) { - return static_cast(InsecureRandRange(MAX_MONEY + 1)); + return CAmount{rng.randrange(MAX_MONEY + 1)}; } #endif // BITCOIN_TEST_UTIL_RANDOM_H