Skip to content

Commit

Permalink
test: refactor: Accept any RandomNumberGenerator in RandMoney
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
MarcoFalke committed Aug 26, 2024
1 parent 68f77dd commit fa54cab
Show file tree
Hide file tree
Showing 4 changed files with 7 additions and 6 deletions.
2 changes: 1 addition & 1 deletion src/test/coins_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion src/test/sighash_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/test/util/coins.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
7 changes: 4 additions & 3 deletions src/test/util/random.h
Original file line number Diff line number Diff line change
@@ -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.

Expand Down Expand Up @@ -52,9 +52,10 @@ static inline bool InsecureRandBool()
return g_insecure_rand_ctx.randbool();
}

static inline CAmount InsecureRandMoneyAmount()
template <RandomNumberGenerator Rng>
inline CAmount RandMoney(Rng&& rng)
{
return static_cast<CAmount>(InsecureRandRange(MAX_MONEY + 1));
return CAmount{rng.randrange(MAX_MONEY + 1)};
}

#endif // BITCOIN_TEST_UTIL_RANDOM_H

0 comments on commit fa54cab

Please sign in to comment.