Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use Marshal and UnmarshalJSON for HexBytes #239

Merged
merged 9 commits into from
Jul 29, 2024
21 changes: 21 additions & 0 deletions libs/bytes/bytes.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,24 @@ func (bz HexBytes) Format(s fmt.State, verb rune) {
s.Write([]byte(fmt.Sprintf("%X", []byte(bz))))
}
}

func (bz HexBytes) MarshalJSON() ([]byte, error) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should treat this as an app-hash breaking change due to potentially wide-ranging impact.

jewei1997 marked this conversation as resolved.
Show resolved Hide resolved
s := strings.ToUpper(hex.EncodeToString(bz))
jbz := make([]byte, len(s)+2)
jbz[0] = '"'
copy(jbz[1:], s)
jbz[len(jbz)-1] = '"'
return jbz, nil
}

func (bz *HexBytes) UnmarshalJSON(data []byte) error {
if len(data) < 2 || data[0] != '"' || data[len(data)-1] != '"' {
return fmt.Errorf("invalid hex string: %s", data)
}
bz2, err := hex.DecodeString(string(data[1 : len(data)-1]))
if err != nil {
return err
}
*bz = bz2
return nil
}
Loading