Skip to content

Commit 9ce0474

Browse files
authored
common: fix json marshaller MixedcaseAddress (#26998)
Fix the json marshaller of MixedcaseAddress
1 parent 50317bd commit 9ce0474

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

common/types.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -400,7 +400,7 @@ func (ma *MixedcaseAddress) UnmarshalJSON(input []byte) error {
400400
}
401401

402402
// MarshalJSON marshals the original value
403-
func (ma *MixedcaseAddress) MarshalJSON() ([]byte, error) {
403+
func (ma MixedcaseAddress) MarshalJSON() ([]byte, error) {
404404
if strings.HasPrefix(ma.original, "0x") || strings.HasPrefix(ma.original, "0X") {
405405
return json.Marshal(fmt.Sprintf("0x%s", ma.original[2:]))
406406
}

common/types_test.go

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,31 @@ func BenchmarkAddressHex(b *testing.B) {
154154
}
155155
}
156156

157+
// Test checks if the customized json marshaller of MixedcaseAddress object
158+
// is invoked correctly. In golang the struct pointer will inherit the
159+
// non-pointer receiver methods, the reverse is not true. In the case of
160+
// MixedcaseAddress, it must define the MarshalJSON method in the object
161+
// but not the pointer level, so that this customized marshalled can be used
162+
// for both MixedcaseAddress object and pointer.
163+
func TestMixedcaseAddressMarshal(t *testing.T) {
164+
var (
165+
output string
166+
input = "0xae967917c465db8578ca9024c205720b1a3651A9"
167+
)
168+
addr, err := NewMixedcaseAddressFromString(input)
169+
if err != nil {
170+
t.Fatal(err)
171+
}
172+
blob, err := json.Marshal(*addr)
173+
if err != nil {
174+
t.Fatal(err)
175+
}
176+
json.Unmarshal(blob, &output)
177+
if output != input {
178+
t.Fatal("Failed to marshal/unmarshal MixedcaseAddress object")
179+
}
180+
}
181+
157182
func TestMixedcaseAccount_Address(t *testing.T) {
158183
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md
159184
// Note: 0X{checksum_addr} is not valid according to spec above
@@ -177,7 +202,7 @@ func TestMixedcaseAccount_Address(t *testing.T) {
177202
}
178203
}
179204

180-
//These should throw exceptions:
205+
// These should throw exceptions:
181206
var r2 []MixedcaseAddress
182207
for _, r := range []string{
183208
`["0x11111111111111111111122222222222233333"]`, // Too short

0 commit comments

Comments
 (0)