Skip to content

Commit

Permalink
accounts/abi: fix MakeTopics mutation of big.Int inputs (#30785)
Browse files Browse the repository at this point in the history
#28764 updated `func MakeTopics` to support negative `*big.Int`s.
However, it also changed the behavior of the function from just
_reading_ the input `*big.Int` via `Bytes()`, to leveraging
`big.U256Bytes` which is documented as being _destructive_:

This change updates `MakeTopics` to not mutate the original, and 
also applies the same change in signer/core/apitypes.
  • Loading branch information
jmank88 authored Nov 25, 2024
1 parent 19fa71b commit 3c754e2
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
2 changes: 1 addition & 1 deletion accounts/abi/topics.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func MakeTopics(query ...[]interface{}) ([][]common.Hash, error) {
case common.Address:
copy(topic[common.HashLength-common.AddressLength:], rule[:])
case *big.Int:
copy(topic[:], math.U256Bytes(rule))
copy(topic[:], math.U256Bytes(new(big.Int).Set(rule)))
case bool:
if rule {
topic[common.HashLength-1] = 1
Expand Down
17 changes: 17 additions & 0 deletions accounts/abi/topics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,23 @@ func TestMakeTopics(t *testing.T) {
}
})
}

t.Run("does not mutate big.Int", func(t *testing.T) {
t.Parallel()
want := [][]common.Hash{{common.HexToHash("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")}}

in := big.NewInt(-1)
got, err := MakeTopics([]interface{}{in})
if err != nil {
t.Fatalf("makeTopics() error = %v", err)
}
if !reflect.DeepEqual(got, want) {
t.Fatalf("makeTopics() = %v, want %v", got, want)
}
if orig := big.NewInt(-1); in.Cmp(orig) != 0 {
t.Fatalf("makeTopics() mutated an input parameter from %v to %v", orig, in)
}
})
}

type args struct {
Expand Down
2 changes: 1 addition & 1 deletion signer/core/apitypes/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -676,7 +676,7 @@ func (typedData *TypedData) EncodePrimitiveValue(encType string, encValue interf
if err != nil {
return nil, err
}
return math.U256Bytes(b), nil
return math.U256Bytes(new(big.Int).Set(b)), nil
}
return nil, fmt.Errorf("unrecognized type '%s'", encType)
}
Expand Down

0 comments on commit 3c754e2

Please sign in to comment.