Skip to content

Commit 8fa0b86

Browse files
Fix SaturatingDecrement underflow bug
1 parent 02159c6 commit 8fa0b86

File tree

2 files changed

+27
-11
lines changed

2 files changed

+27
-11
lines changed

arbitrum/multigas/resources.go

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -327,16 +327,20 @@ func (z MultiGas) SaturatingIncrement(kind ResourceKind, gas uint64) MultiGas {
327327
func (z MultiGas) SaturatingDecrement(kind ResourceKind, gas uint64) MultiGas {
328328
res := z
329329

330-
if v, c := bits.Sub64(res.gas[kind], gas, 0); c != 0 {
331-
res.gas[kind] = 0 // clamp
330+
current := res.gas[kind]
331+
var reduced uint64
332+
if current < gas {
333+
reduced = current
334+
res.gas[kind] = 0
332335
} else {
333-
res.gas[kind] = v
336+
reduced = gas
337+
res.gas[kind] = current - gas
334338
}
335339

336-
if t, c := bits.Sub64(res.total, gas, 0); c != 0 {
337-
res.total = 0 // clamp
340+
if res.total < reduced {
341+
res.total = 0
338342
} else {
339-
res.total = t
343+
res.total -= reduced
340344
}
341345

342346
return res

arbitrum/multigas/resources_test.go

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -400,13 +400,25 @@ func TestSaturatingDecrement(t *testing.T) {
400400
}
401401

402402
// saturating decrement on kind
403-
gas = ComputationGas(0)
404-
newGas = gas.SaturatingDecrement(ResourceKindComputation, 1)
403+
gas = MultiGasFromPairs(
404+
Pair{ResourceKindComputation, 10},
405+
Pair{ResourceKindStorageAccess, 10},
406+
)
407+
408+
newGas = gas.SaturatingDecrement(ResourceKindComputation, 20)
405409
if got, want := newGas.Get(ResourceKindComputation), uint64(0); got != want {
406-
t.Errorf("expected computation gas to clamp to zero: got %v, want %v", got, want)
410+
t.Errorf("unexpected comp gas: got %v, want %v", got, want)
407411
}
408-
if got, want := newGas.SingleGas(), uint64(0); got != want {
409-
t.Errorf("expected total to clamp to zero: got %v, want %v", got, want)
412+
if got, want := newGas.Get(ResourceKindStorageAccess), uint64(10); got != want {
413+
t.Errorf("unexpected storage access gas: got %v, want %v", got, want)
414+
}
415+
if got, want := newGas.SingleGas(), uint64(10); got != want {
416+
t.Errorf("unexpected total (should drop by 10 only): got %v, want %v", got, want)
417+
}
418+
419+
if got, want := newGas.SingleGas(),
420+
newGas.Get(ResourceKindComputation)+newGas.Get(ResourceKindStorageAccess); got != want {
421+
t.Errorf("total/sum mismatch: total=%v sum=%v", got, want)
410422
}
411423

412424
// total-only decrement case

0 commit comments

Comments
 (0)