Skip to content

Commit 3c754e2

Browse files
authored
accounts/abi: fix MakeTopics mutation of big.Int inputs (#30785)
#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.
1 parent 19fa71b commit 3c754e2

File tree

3 files changed

+19
-2
lines changed

3 files changed

+19
-2
lines changed

accounts/abi/topics.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ func MakeTopics(query ...[]interface{}) ([][]common.Hash, error) {
4242
case common.Address:
4343
copy(topic[common.HashLength-common.AddressLength:], rule[:])
4444
case *big.Int:
45-
copy(topic[:], math.U256Bytes(rule))
45+
copy(topic[:], math.U256Bytes(new(big.Int).Set(rule)))
4646
case bool:
4747
if rule {
4848
topic[common.HashLength-1] = 1

accounts/abi/topics_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,23 @@ func TestMakeTopics(t *testing.T) {
149149
}
150150
})
151151
}
152+
153+
t.Run("does not mutate big.Int", func(t *testing.T) {
154+
t.Parallel()
155+
want := [][]common.Hash{{common.HexToHash("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")}}
156+
157+
in := big.NewInt(-1)
158+
got, err := MakeTopics([]interface{}{in})
159+
if err != nil {
160+
t.Fatalf("makeTopics() error = %v", err)
161+
}
162+
if !reflect.DeepEqual(got, want) {
163+
t.Fatalf("makeTopics() = %v, want %v", got, want)
164+
}
165+
if orig := big.NewInt(-1); in.Cmp(orig) != 0 {
166+
t.Fatalf("makeTopics() mutated an input parameter from %v to %v", orig, in)
167+
}
168+
})
152169
}
153170

154171
type args struct {

signer/core/apitypes/types.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -676,7 +676,7 @@ func (typedData *TypedData) EncodePrimitiveValue(encType string, encValue interf
676676
if err != nil {
677677
return nil, err
678678
}
679-
return math.U256Bytes(b), nil
679+
return math.U256Bytes(new(big.Int).Set(b)), nil
680680
}
681681
return nil, fmt.Errorf("unrecognized type '%s'", encType)
682682
}

0 commit comments

Comments
 (0)