Skip to content

Commit bddf5aa

Browse files
authored
les/utils: protect against WeightedRandomSelect overflow (#21839)
Also fixes a bug in les/flowcontrol that caused the overflow.
1 parent 3ef5277 commit bddf5aa

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

les/flowcontrol/control.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ package flowcontrol
1919

2020
import (
2121
"fmt"
22+
"math"
2223
"sync"
2324
"time"
2425

@@ -316,6 +317,9 @@ func (node *ServerNode) CanSend(maxCost uint64) (time.Duration, float64) {
316317
node.lock.RLock()
317318
defer node.lock.RUnlock()
318319

320+
if node.params.BufLimit == 0 {
321+
return time.Duration(math.MaxInt64), 0
322+
}
319323
now := node.clock.Now()
320324
node.recalcBLE(now)
321325
maxCost += uint64(safetyMargin) * node.params.MinRecharge / uint64(fcTimeConst)

les/utils/weighted_select.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,10 @@
1717
package utils
1818

1919
import (
20+
"math"
2021
"math/rand"
22+
23+
"github.com/ethereum/go-ethereum/log"
2124
)
2225

2326
type (
@@ -54,6 +57,14 @@ func (w *WeightedRandomSelect) IsEmpty() bool {
5457

5558
// setWeight sets an item's weight to a specific value (removes it if zero)
5659
func (w *WeightedRandomSelect) setWeight(item WrsItem, weight uint64) {
60+
if weight > math.MaxInt64-w.root.sumWeight {
61+
// old weight is still included in sumWeight, remove and check again
62+
w.setWeight(item, 0)
63+
if weight > math.MaxInt64-w.root.sumWeight {
64+
log.Error("WeightedRandomSelect overflow", "sumWeight", w.root.sumWeight, "new weight", weight)
65+
weight = math.MaxInt64 - w.root.sumWeight
66+
}
67+
}
5768
idx, ok := w.idx[item]
5869
if ok {
5970
w.root.setWeight(idx, weight)

0 commit comments

Comments
 (0)