From ddc184d999d7e1a87efaf6bcb222186f0dcd87ec Mon Sep 17 00:00:00 2001 From: Pieter Wuille Date: Thu, 27 Jun 2024 11:40:00 -0400 Subject: [PATCH] random: get rid of GetRand by inlining --- src/addrdb.cpp | 2 +- src/common/bloom.cpp | 2 +- src/headerssync.cpp | 2 +- src/init.cpp | 5 +++-- src/net_processing.cpp | 8 ++++---- src/netaddress.h | 4 ++-- src/node/txreconciliation.cpp | 2 +- src/random.h | 16 +--------------- src/test/random_tests.cpp | 24 ++++++++++++------------ src/txmempool.cpp | 2 +- src/txrequest.cpp | 4 ++-- src/util/bytevectorhash.cpp | 4 ++-- src/util/hasher.cpp | 12 ++++++++---- src/validation.cpp | 2 +- 14 files changed, 40 insertions(+), 49 deletions(-) diff --git a/src/addrdb.cpp b/src/addrdb.cpp index 4d34c24ba9..e9838d7222 100644 --- a/src/addrdb.cpp +++ b/src/addrdb.cpp @@ -53,7 +53,7 @@ template bool SerializeFileDB(const std::string& prefix, const fs::path& path, const Data& data) { // Generate random temporary filename - const uint16_t randv{GetRand()}; + const uint16_t randv{FastRandomContext().rand()}; std::string tmpfn = strprintf("%s.%04x", prefix, randv); // open temp output file diff --git a/src/common/bloom.cpp b/src/common/bloom.cpp index ca6af90b76..076ee40635 100644 --- a/src/common/bloom.cpp +++ b/src/common/bloom.cpp @@ -239,7 +239,7 @@ bool CRollingBloomFilter::contains(Span vKey) const void CRollingBloomFilter::reset() { - nTweak = GetRand(); + nTweak = FastRandomContext().rand(); nEntriesThisGeneration = 0; nGeneration = 1; std::fill(data.begin(), data.end(), 0); diff --git a/src/headerssync.cpp b/src/headerssync.cpp index e14de004f5..b41fe07754 100644 --- a/src/headerssync.cpp +++ b/src/headerssync.cpp @@ -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(HEADER_COMMITMENT_PERIOD)), + m_commit_offset(FastRandomContext().randrange(HEADER_COMMITMENT_PERIOD)), m_id(id), m_consensus_params(consensus_params), m_chain_start(chain_start), m_minimum_required_work(minimum_required_work), diff --git a/src/init.cpp b/src/init.cpp index 44c256d203..0022aeb039 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -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(args.GetDataDirNet() / "banlist", &uiInterface, args.GetIntArg("-bantime", DEFAULT_MISBEHAVING_BANTIME)); assert(!node.connman); - node.connman = std::make_unique(GetRand(), - GetRand(), + node.connman = std::make_unique(rng.rand64(), + rng.rand64(), *node.addrman, *node.netgroupman, chainparams, args.GetBoolArg("-networkactive", true)); assert(!node.fee_estimator); diff --git a/src/net_processing.cpp b/src/net_processing.cpp index 3be4479587..d674811ba7 100644 --- a/src/net_processing.cpp +++ b/src/net_processing.cpp @@ -2124,7 +2124,7 @@ void PeerManagerImpl::BlockDisconnected(const std::shared_ptr &blo */ void PeerManagerImpl::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr& pblock) { - auto pcmpctblock = std::make_shared(*pblock, GetRand()); + auto pcmpctblock = std::make_shared(*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()}; + 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(); + 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()}; + CBlockHeaderAndShortTxIDs cmpctblock{block, m_rng.rand64()}; MakeAndPushMessage(*pto, NetMsgType::CMPCTBLOCK, cmpctblock); } state.pindexBestHeaderSent = pBestIndex; diff --git a/src/netaddress.h b/src/netaddress.h index 52fecada1c..24f5c3fb96 100644 --- a/src/netaddress.h +++ b/src/netaddress.h @@ -567,8 +567,8 @@ class CServiceHash { public: CServiceHash() - : m_salt_k0{GetRand()}, - m_salt_k1{GetRand()} + : m_salt_k0{FastRandomContext().rand64()}, + m_salt_k1{FastRandomContext().rand64()} { } diff --git a/src/node/txreconciliation.cpp b/src/node/txreconciliation.cpp index d62046daaa..e6e19c5756 100644 --- a/src/node/txreconciliation.cpp +++ b/src/node/txreconciliation.cpp @@ -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. diff --git a/src/random.h b/src/random.h index afbae0cec3..1573e49ef7 100644 --- a/src/random.h +++ b/src/random.h @@ -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 -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 -T GetRand() noexcept { - return T(FastRandomContext().rand()); -} - /** Generate a uniform random duration in the range [0..max). Precondition: max.count() > 0 */ template D GetRandomDuration(typename std::common_type::type max) noexcept @@ -448,7 +434,7 @@ D GetRandomDuration(typename std::common_type::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; constexpr auto GetRandMillis = GetRandomDuration; diff --git a/src/test/random_tests.cpp b/src/test/random_tests.cpp index 89546166b4..6932e186d5 100644 --- a/src/test/random_tests.cpp +++ b/src/test/random_tests.cpp @@ -28,18 +28,18 @@ BOOST_AUTO_TEST_CASE(fastrandom_tests_deterministic) FastRandomContext ctx2{true}; { - BOOST_CHECK_EQUAL(GetRand(), uint64_t{9330418229102544152u}); - BOOST_CHECK_EQUAL(GetRand(), int{618925161}); + BOOST_CHECK_EQUAL(FastRandomContext().rand(), uint64_t{9330418229102544152u}); + BOOST_CHECK_EQUAL(FastRandomContext().rand(), 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{10170981140880778086u}); - BOOST_CHECK_EQUAL(GetRand(), int{1689082725}); + BOOST_CHECK_EQUAL(FastRandomContext().rand(), uint64_t{10170981140880778086u}); + BOOST_CHECK_EQUAL(FastRandomContext().rand(), 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{5689404004456455543u}); - BOOST_CHECK_EQUAL(GetRand(), int{785839937}); + BOOST_CHECK_EQUAL(FastRandomContext().rand(), uint64_t{5689404004456455543u}); + BOOST_CHECK_EQUAL(FastRandomContext().rand(), 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{9330418229102544152u}); - BOOST_CHECK(GetRand() != int{618925161}); + BOOST_CHECK(FastRandomContext().rand() != uint64_t{9330418229102544152u}); + BOOST_CHECK(FastRandomContext().rand() != 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{10170981140880778086u}); - BOOST_CHECK(GetRand() != int{1689082725}); + BOOST_CHECK(FastRandomContext().rand() != uint64_t{10170981140880778086u}); + BOOST_CHECK(FastRandomContext().rand() != 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{5689404004456455543u}); - BOOST_CHECK(GetRand() != int{785839937}); + BOOST_CHECK(FastRandomContext().rand() != uint64_t{5689404004456455543u}); + BOOST_CHECK(FastRandomContext().rand() != int{785839937}); BOOST_CHECK(GetRandMicros(std::chrono::hours{1}).count() != 93558804); BOOST_CHECK(GetRandMillis(std::chrono::hours{1}).count() != 507022); } diff --git a/src/txmempool.cpp b/src/txmempool.cpp index 10674c07ac..f56da08e5f 100644 --- a/src/txmempool.cpp +++ b/src/txmempool.cpp @@ -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); diff --git a/src/txrequest.cpp b/src/txrequest.cpp index ce5fbd9a7f..6338ccb118 100644 --- a/src/txrequest.cpp +++ b/src/txrequest.cpp @@ -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 { diff --git a/src/util/bytevectorhash.cpp b/src/util/bytevectorhash.cpp index 92f1dbd5d8..79e4a21fe9 100644 --- a/src/util/bytevectorhash.cpp +++ b/src/util/bytevectorhash.cpp @@ -9,8 +9,8 @@ #include ByteVectorHash::ByteVectorHash() : - m_k0(GetRand()), - m_k1(GetRand()) + m_k0(FastRandomContext().rand64()), + m_k1(FastRandomContext().rand64()) { } diff --git a/src/util/hasher.cpp b/src/util/hasher.cpp index f571725786..3109ba02a8 100644 --- a/src/util/hasher.cpp +++ b/src/util/hasher.cpp @@ -7,14 +7,18 @@ #include #include -SaltedTxidHasher::SaltedTxidHasher() : k0(GetRand()), k1(GetRand()) {} +SaltedTxidHasher::SaltedTxidHasher() : + k0{FastRandomContext().rand64()}, + k1{FastRandomContext().rand64()} {} SaltedOutpointHasher::SaltedOutpointHasher(bool deterministic) : - k0(deterministic ? 0x8e819f2607a18de6 : GetRand()), - k1(deterministic ? 0xf4020d2e3983b0eb : GetRand()) + k0{deterministic ? 0x8e819f2607a18de6 : FastRandomContext().rand64()}, + k1{deterministic ? 0xf4020d2e3983b0eb : FastRandomContext().rand64()} {} -SaltedSipHasher::SaltedSipHasher() : m_k0(GetRand()), m_k1(GetRand()) {} +SaltedSipHasher::SaltedSipHasher() : + m_k0{FastRandomContext().rand64()}, + m_k1{FastRandomContext().rand64()} {} size_t SaltedSipHasher::operator()(const Span& script) const { diff --git a/src/validation.cpp b/src/validation.cpp index 3e9ba08bb1..7955a41f4f 100644 --- a/src/validation.cpp +++ b/src/validation.cpp @@ -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; }