From c3379da2f57869ff5c060c69ece1637d7df68185 Mon Sep 17 00:00:00 2001 From: Jared Wasinger Date: Fri, 9 May 2025 13:32:35 +0800 Subject: [PATCH] accounts/abi: return an error if attempting to pack a negative big.Int into a uint val --- accounts/abi/pack.go | 13 +++++++++++++ accounts/abi/pack_test.go | 7 +++++++ 2 files changed, 20 insertions(+) diff --git a/accounts/abi/pack.go b/accounts/abi/pack.go index beef1fa37f..01761c37c4 100644 --- a/accounts/abi/pack.go +++ b/accounts/abi/pack.go @@ -33,11 +33,24 @@ func packBytesSlice(bytes []byte, l int) []byte { return append(len, common.RightPadBytes(bytes, (l+31)/32*32)...) } +func validateNum(t Type, reflectValue reflect.Value) error { + if t.T == UintTy && reflectValue.Kind() == reflect.Ptr { + val := new(big.Int).Set(reflectValue.Interface().(*big.Int)) + if val.Sign() == -1 { + return fmt.Errorf("cannot pack negative big.Int value to a uint type") + } + } + return nil +} + // packElement packs the given reflect value according to the abi specification in // t. func packElement(t Type, reflectValue reflect.Value) ([]byte, error) { switch t.T { case IntTy, UintTy: + if err := validateNum(t, reflectValue); err != nil { + return nil, err + } return packNum(reflectValue), nil case StringTy: return packBytesSlice([]byte(reflectValue.String()), reflectValue.Len()), nil diff --git a/accounts/abi/pack_test.go b/accounts/abi/pack_test.go index cda31b6204..72f372d40d 100644 --- a/accounts/abi/pack_test.go +++ b/accounts/abi/pack_test.go @@ -177,6 +177,13 @@ func TestMethodPack(t *testing.T) { if !bytes.Equal(packed, sig) { t.Errorf("expected %x got %x", sig, packed) } + + _, err = abi.Pack("send", big.NewInt(-1)) + if err == nil { + t.Fatal("expected error when trying to pack negative big.Int into uint256 value") + } + + // TODO: examine what happens if we supply a negative non-big int to a method expect smaller uint val } func TestPackNumber(t *testing.T) {