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

e064487ca28c12ba774c2f43a3c7acbdb1a278c9 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 e064487ca28c12ba774c2f43a3c7acbdb1a278c9
  amitiuttarwar:
    ACK e064487ca28c12ba774c2f43a3c7acbdb1a278c9
  stratospher:
    ACK e064487ca28c12ba774c2f43a3c7acbdb1a278c9. 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 committed by pasta
parent 2e162da06f
commit 03e0bd3347
No known key found for this signature in database
GPG Key ID: E2F3D7916E722D38

View File

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