random: get rid of GetRand by inlining

This commit is contained in:
Pieter Wuille 2024-06-27 11:40:00 -04:00
parent e2d1f84858
commit ddc184d999
14 changed files with 40 additions and 49 deletions

View file

@ -53,7 +53,7 @@ template <typename Data>
bool SerializeFileDB(const std::string& prefix, const fs::path& path, const Data& data)
{
// Generate random temporary filename
const uint16_t randv{GetRand<uint16_t>()};
const uint16_t randv{FastRandomContext().rand<uint16_t>()};
std::string tmpfn = strprintf("%s.%04x", prefix, randv);
// open temp output file

View file

@ -239,7 +239,7 @@ bool CRollingBloomFilter::contains(Span<const unsigned char> vKey) const
void CRollingBloomFilter::reset()
{
nTweak = GetRand<unsigned int>();
nTweak = FastRandomContext().rand<unsigned int>();
nEntriesThisGeneration = 0;
nGeneration = 1;
std::fill(data.begin(), data.end(), 0);

View file

@ -25,7 +25,7 @@ static_assert(sizeof(CompressedHeader) == 48);
HeadersSyncState::HeadersSyncState(NodeId id, const Consensus::Params& consensus_params,
const CBlockIndex* chain_start, const arith_uint256& minimum_required_work) :
m_commit_offset(GetRand<unsigned>(HEADER_COMMITMENT_PERIOD)),
m_commit_offset(FastRandomContext().randrange<unsigned>(HEADER_COMMITMENT_PERIOD)),
m_id(id), m_consensus_params(consensus_params),
m_chain_start(chain_start),
m_minimum_required_work(minimum_required_work),

View file

@ -1273,11 +1273,12 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
node.addrman = std::move(*addrman);
}
FastRandomContext rng;
assert(!node.banman);
node.banman = std::make_unique<BanMan>(args.GetDataDirNet() / "banlist", &uiInterface, args.GetIntArg("-bantime", DEFAULT_MISBEHAVING_BANTIME));
assert(!node.connman);
node.connman = std::make_unique<CConnman>(GetRand<uint64_t>(),
GetRand<uint64_t>(),
node.connman = std::make_unique<CConnman>(rng.rand64(),
rng.rand64(),
*node.addrman, *node.netgroupman, chainparams, args.GetBoolArg("-networkactive", true));
assert(!node.fee_estimator);

View file

@ -2124,7 +2124,7 @@ void PeerManagerImpl::BlockDisconnected(const std::shared_ptr<const CBlock> &blo
*/
void PeerManagerImpl::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock)
{
auto pcmpctblock = std::make_shared<const CBlockHeaderAndShortTxIDs>(*pblock, GetRand<uint64_t>());
auto pcmpctblock = std::make_shared<const CBlockHeaderAndShortTxIDs>(*pblock, FastRandomContext().rand64());
LOCK(cs_main);
@ -2522,7 +2522,7 @@ void PeerManagerImpl::ProcessGetBlockData(CNode& pfrom, Peer& peer, const CInv&
if (a_recent_compact_block && a_recent_compact_block->header.GetHash() == pindex->GetBlockHash()) {
MakeAndPushMessage(pfrom, NetMsgType::CMPCTBLOCK, *a_recent_compact_block);
} else {
CBlockHeaderAndShortTxIDs cmpctblock{*pblock, GetRand<uint64_t>()};
CBlockHeaderAndShortTxIDs cmpctblock{*pblock, FastRandomContext().rand64()};
MakeAndPushMessage(pfrom, NetMsgType::CMPCTBLOCK, cmpctblock);
}
} else {
@ -5617,7 +5617,7 @@ void PeerManagerImpl::MaybeSendPing(CNode& node_to, Peer& peer, std::chrono::mic
if (pingSend) {
uint64_t nonce;
do {
nonce = GetRand<uint64_t>();
nonce = FastRandomContext().rand64();
} while (nonce == 0);
peer.m_ping_queued = false;
peer.m_ping_start = now;
@ -5984,7 +5984,7 @@ bool PeerManagerImpl::SendMessages(CNode* pto)
CBlock block;
const bool ret{m_chainman.m_blockman.ReadBlockFromDisk(block, *pBestIndex)};
assert(ret);
CBlockHeaderAndShortTxIDs cmpctblock{block, GetRand<uint64_t>()};
CBlockHeaderAndShortTxIDs cmpctblock{block, m_rng.rand64()};
MakeAndPushMessage(*pto, NetMsgType::CMPCTBLOCK, cmpctblock);
}
state.pindexBestHeaderSent = pBestIndex;

View file

@ -567,8 +567,8 @@ class CServiceHash
{
public:
CServiceHash()
: m_salt_k0{GetRand<uint64_t>()},
m_salt_k1{GetRand<uint64_t>()}
: m_salt_k0{FastRandomContext().rand64()},
m_salt_k1{FastRandomContext().rand64()}
{
}

View file

@ -85,7 +85,7 @@ public:
LOCK(m_txreconciliation_mutex);
LogPrintLevel(BCLog::TXRECONCILIATION, BCLog::Level::Debug, "Pre-register peer=%d\n", peer_id);
const uint64_t local_salt{GetRand(UINT64_MAX)};
const uint64_t local_salt{FastRandomContext().rand64()};
// We do this exactly once per peer (which are unique by NodeId, see GetNewNodeId) so it's
// safe to assume we don't have this record yet.

View file

@ -426,20 +426,6 @@ void Shuffle(I first, I last, R&& rng)
}
}
/** Generate a uniform random integer of type T in the range [0..nMax)
* Precondition: nMax > 0, T is an integral type, no larger than uint64_t
*/
template<typename T>
T GetRand(T nMax) noexcept {
return T(FastRandomContext().randrange(nMax));
}
/** Generate a uniform random integer of type T in its entire non-negative range. */
template<typename T>
T GetRand() noexcept {
return T(FastRandomContext().rand<T>());
}
/** Generate a uniform random duration in the range [0..max). Precondition: max.count() > 0 */
template <typename D>
D GetRandomDuration(typename std::common_type<D>::type max) noexcept
@ -448,7 +434,7 @@ D GetRandomDuration(typename std::common_type<D>::type max) noexcept
// type than the function argument. So std::common_type is used to force the
// call site to specify the type of the return value.
{
return D{GetRand(max.count())};
return D{FastRandomContext().randrange(max.count())};
};
constexpr auto GetRandMicros = GetRandomDuration<std::chrono::microseconds>;
constexpr auto GetRandMillis = GetRandomDuration<std::chrono::milliseconds>;

View file

@ -28,18 +28,18 @@ BOOST_AUTO_TEST_CASE(fastrandom_tests_deterministic)
FastRandomContext ctx2{true};
{
BOOST_CHECK_EQUAL(GetRand<uint64_t>(), uint64_t{9330418229102544152u});
BOOST_CHECK_EQUAL(GetRand<int>(), int{618925161});
BOOST_CHECK_EQUAL(FastRandomContext().rand<uint64_t>(), uint64_t{9330418229102544152u});
BOOST_CHECK_EQUAL(FastRandomContext().rand<int>(), int{618925161});
BOOST_CHECK_EQUAL(GetRandMicros(std::chrono::hours{1}).count(), 1271170921);
BOOST_CHECK_EQUAL(GetRandMillis(std::chrono::hours{1}).count(), 2803534);
BOOST_CHECK_EQUAL(GetRand<uint64_t>(), uint64_t{10170981140880778086u});
BOOST_CHECK_EQUAL(GetRand<int>(), int{1689082725});
BOOST_CHECK_EQUAL(FastRandomContext().rand<uint64_t>(), uint64_t{10170981140880778086u});
BOOST_CHECK_EQUAL(FastRandomContext().rand<int>(), int{1689082725});
BOOST_CHECK_EQUAL(GetRandMicros(std::chrono::hours{1}).count(), 2464643716);
BOOST_CHECK_EQUAL(GetRandMillis(std::chrono::hours{1}).count(), 2312205);
BOOST_CHECK_EQUAL(GetRand<uint64_t>(), uint64_t{5689404004456455543u});
BOOST_CHECK_EQUAL(GetRand<int>(), int{785839937});
BOOST_CHECK_EQUAL(FastRandomContext().rand<uint64_t>(), uint64_t{5689404004456455543u});
BOOST_CHECK_EQUAL(FastRandomContext().rand<int>(), int{785839937});
BOOST_CHECK_EQUAL(GetRandMicros(std::chrono::hours{1}).count(), 93558804);
BOOST_CHECK_EQUAL(GetRandMillis(std::chrono::hours{1}).count(), 507022);
}
@ -82,18 +82,18 @@ BOOST_AUTO_TEST_CASE(fastrandom_tests_nondeterministic)
{
// Check that a nondeterministic ones are not
{
BOOST_CHECK(GetRand<uint64_t>() != uint64_t{9330418229102544152u});
BOOST_CHECK(GetRand<int>() != int{618925161});
BOOST_CHECK(FastRandomContext().rand<uint64_t>() != uint64_t{9330418229102544152u});
BOOST_CHECK(FastRandomContext().rand<int>() != int{618925161});
BOOST_CHECK(GetRandMicros(std::chrono::hours{1}).count() != 1271170921);
BOOST_CHECK(GetRandMillis(std::chrono::hours{1}).count() != 2803534);
BOOST_CHECK(GetRand<uint64_t>() != uint64_t{10170981140880778086u});
BOOST_CHECK(GetRand<int>() != int{1689082725});
BOOST_CHECK(FastRandomContext().rand<uint64_t>() != uint64_t{10170981140880778086u});
BOOST_CHECK(FastRandomContext().rand<int>() != int{1689082725});
BOOST_CHECK(GetRandMicros(std::chrono::hours{1}).count() != 2464643716);
BOOST_CHECK(GetRandMillis(std::chrono::hours{1}).count() != 2312205);
BOOST_CHECK(GetRand<uint64_t>() != uint64_t{5689404004456455543u});
BOOST_CHECK(GetRand<int>() != int{785839937});
BOOST_CHECK(FastRandomContext().rand<uint64_t>() != uint64_t{5689404004456455543u});
BOOST_CHECK(FastRandomContext().rand<int>() != int{785839937});
BOOST_CHECK(GetRandMicros(std::chrono::hours{1}).count() != 93558804);
BOOST_CHECK(GetRandMillis(std::chrono::hours{1}).count() != 507022);
}

View file

@ -657,7 +657,7 @@ void CTxMemPool::check(const CCoinsViewCache& active_coins_tip, int64_t spendhei
{
if (m_opts.check_ratio == 0) return;
if (GetRand(m_opts.check_ratio) >= 1) return;
if (FastRandomContext().randrange(m_opts.check_ratio) >= 1) return;
AssertLockHeld(::cs_main);
LOCK(cs);

View file

@ -113,8 +113,8 @@ class PriorityComputer {
const uint64_t m_k0, m_k1;
public:
explicit PriorityComputer(bool deterministic) :
m_k0{deterministic ? 0 : GetRand(0xFFFFFFFFFFFFFFFF)},
m_k1{deterministic ? 0 : GetRand(0xFFFFFFFFFFFFFFFF)} {}
m_k0{deterministic ? 0 : FastRandomContext().rand64()},
m_k1{deterministic ? 0 : FastRandomContext().rand64()} {}
Priority operator()(const uint256& txhash, NodeId peer, bool preferred) const
{

View file

@ -9,8 +9,8 @@
#include <vector>
ByteVectorHash::ByteVectorHash() :
m_k0(GetRand<uint64_t>()),
m_k1(GetRand<uint64_t>())
m_k0(FastRandomContext().rand64()),
m_k1(FastRandomContext().rand64())
{
}

View file

@ -7,14 +7,18 @@
#include <span.h>
#include <util/hasher.h>
SaltedTxidHasher::SaltedTxidHasher() : k0(GetRand<uint64_t>()), k1(GetRand<uint64_t>()) {}
SaltedTxidHasher::SaltedTxidHasher() :
k0{FastRandomContext().rand64()},
k1{FastRandomContext().rand64()} {}
SaltedOutpointHasher::SaltedOutpointHasher(bool deterministic) :
k0(deterministic ? 0x8e819f2607a18de6 : GetRand<uint64_t>()),
k1(deterministic ? 0xf4020d2e3983b0eb : GetRand<uint64_t>())
k0{deterministic ? 0x8e819f2607a18de6 : FastRandomContext().rand64()},
k1{deterministic ? 0xf4020d2e3983b0eb : FastRandomContext().rand64()}
{}
SaltedSipHasher::SaltedSipHasher() : m_k0(GetRand<uint64_t>()), m_k1(GetRand<uint64_t>()) {}
SaltedSipHasher::SaltedSipHasher() :
m_k0{FastRandomContext().rand64()},
m_k1{FastRandomContext().rand64()} {}
size_t SaltedSipHasher::operator()(const Span<const unsigned char>& script) const
{

View file

@ -5193,7 +5193,7 @@ bool ChainstateManager::ShouldCheckBlockIndex() const
{
// Assert to verify Flatten() has been called.
if (!*Assert(m_options.check_block_index)) return false;
if (GetRand(*m_options.check_block_index) >= 1) return false;
if (FastRandomContext().randrange(*m_options.check_block_index) >= 1) return false;
return true;
}