Skip to content

Commit f15849c

Browse files
accounts/abi faster unpacking of int256 (#20850)
1 parent bf35e27 commit f15849c

File tree

2 files changed

+10
-14
lines changed

2 files changed

+10
-14
lines changed

accounts/abi/unpack.go

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,9 @@ import (
2727

2828
var (
2929
// MaxUint256 is the maximum value that can be represented by a uint256
30-
MaxUint256 = big.NewInt(0).Add(
31-
big.NewInt(0).Exp(big.NewInt(2), big.NewInt(256), nil),
32-
big.NewInt(-1))
30+
MaxUint256 = new(big.Int).Sub(new(big.Int).Lsh(common.Big1, 256), common.Big1)
3331
// MaxInt256 is the maximum value that can be represented by a int256
34-
MaxInt256 = big.NewInt(0).Add(
35-
big.NewInt(0).Exp(big.NewInt(2), big.NewInt(255), nil),
36-
big.NewInt(-1))
32+
MaxInt256 = new(big.Int).Sub(new(big.Int).Lsh(common.Big1, 255), common.Big1)
3733
)
3834

3935
// ReadInteger reads the integer based on its kind and returns the appropriate value
@@ -56,17 +52,17 @@ func ReadInteger(typ byte, kind reflect.Kind, b []byte) interface{} {
5652
case reflect.Int64:
5753
return int64(binary.BigEndian.Uint64(b[len(b)-8:]))
5854
default:
59-
// the only case lefts for integer is int256/uint256.
60-
// big.SetBytes can't tell if a number is negative, positive on itself.
61-
// On EVM, if the returned number > max int256, it is negative.
55+
// the only case left for integer is int256/uint256.
6256
ret := new(big.Int).SetBytes(b)
6357
if typ == UintTy {
6458
return ret
6559
}
66-
67-
if ret.Cmp(MaxInt256) > 0 {
68-
ret.Add(MaxUint256, big.NewInt(0).Neg(ret))
69-
ret.Add(ret, big.NewInt(1))
60+
// big.SetBytes can't tell if a number is negative or positive in itself.
61+
// On EVM, if the returned number > max int256, it is negative.
62+
// A number is > max int256 if the bit at position 255 is set.
63+
if ret.Bit(255) == 1 {
64+
ret.Add(MaxUint256, new(big.Int).Neg(ret))
65+
ret.Add(ret, common.Big1)
7066
ret.Neg(ret)
7167
}
7268
return ret

accounts/abi/unpack_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1009,7 +1009,7 @@ func TestUnpackTuple(t *testing.T) {
10091009
t.Errorf("unexpected value unpacked: want %x, got %x", 1, v.A)
10101010
}
10111011
if v.B.Cmp(big.NewInt(-1)) != 0 {
1012-
t.Errorf("unexpected value unpacked: want %x, got %x", v.B, -1)
1012+
t.Errorf("unexpected value unpacked: want %x, got %x", -1, v.B)
10131013
}
10141014
}
10151015

0 commit comments

Comments
 (0)