Merge bitcoin/bitcoin#27319: addrman, refactor: improve stochastic test in AddSingle

e064487ca2 addrman, refactor: improve stochastic test in `AddSingle` (brunoerg)

Pull request description:

  This PR changes this algorithm to be O(1) instead of O(n). Also, in the current implementation, if `pinfo->nRefCount` is 0, we created an unnecessary variable (`nFactor`), this changes it. the change is relatively simple and does not cause conflicts.

ACKs for top commit:
  achow101:
    ACK e064487ca2
  amitiuttarwar:
    ACK e064487ca2
  stratospher:
    ACK e064487ca2. simple use of << instead of a loop, didn't observe any behaviour difference before and after.

Tree-SHA512: ff0a65155e47f65d2ce3cb5a3fd7a86efef1861181143df13a9d8e59cb16aee9be2f8801457bba8478b17fac47b015bff5cc656f6fac2ccc071ee7178a38d291
This commit is contained in:
Ava Chow
2024-02-08 13:41:02 -05:00

View File

@@ -585,11 +585,10 @@ bool AddrManImpl::AddSingle(const CAddress& addr, const CNetAddr& source, std::c
return false; return false;
// stochastic test: previous nRefCount == N: 2^N times harder to increase it // stochastic test: previous nRefCount == N: 2^N times harder to increase it
int nFactor = 1; if (pinfo->nRefCount > 0) {
for (int n = 0; n < pinfo->nRefCount; n++) const int nFactor{1 << pinfo->nRefCount};
nFactor *= 2; if (insecure_rand.randrange(nFactor) != 0) return false;
if (nFactor > 1 && (insecure_rand.randrange(nFactor) != 0)) }
return false;
} else { } else {
pinfo = Create(addr, source, &nId); pinfo = Create(addr, source, &nId);
pinfo->nTime = std::max(NodeSeconds{0s}, pinfo->nTime - time_penalty); pinfo->nTime = std::max(NodeSeconds{0s}, pinfo->nTime - time_penalty);