From 3bc18a3be50822100773789cb3ecff08cb17f938 Mon Sep 17 00:00:00 2001 From: Jonathan Chappelow Date: Fri, 20 Jan 2023 10:04:54 -0600 Subject: [PATCH] addrmgr: set min value and optimize address chance This updates the (*KnownAddress).chance method in the following ways: 1. Apply a lower limit to the return value. Using 0.01 as this minimum prevents tiny chance values from causing excessive iterations in (*AddrManager).GetAddress, currently the only caller. 2. Replace an inefficient loop with a single math.Pow. These changes are mitigations to excessive CPU use in the GetAddress method that manifest when the number of attempts for a KnownAddress becomes large. However, this method and much of addrmgr should be rewritten in the future since there are some ad hoc and questionable approaches to candidate address selection. --- addrmgr/knownaddress.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/addrmgr/knownaddress.go b/addrmgr/knownaddress.go index 5243385127..94320cf940 100644 --- a/addrmgr/knownaddress.go +++ b/addrmgr/knownaddress.go @@ -6,6 +6,7 @@ package addrmgr import ( + "math" "sync" "time" ) @@ -69,19 +70,18 @@ func (ka *KnownAddress) chance() float64 { lastAttempt = 0 } - c := 1.0 + // Apply a lower limit to the value returned. + const minChance = 0.01 // Very recent attempts are less likely to be retried. if lastAttempt < 10*time.Minute { - c *= 0.01 + return minChance } // Failed attempts deprioritise. - for i := ka.attempts; i > 0; i-- { - c /= 1.5 - } + c := 1.0 / math.Pow(1.5, float64(ka.attempts)) - return c + return math.Max(c, minChance) } // isBad returns true if the address in question has not been tried in the last