Appending unmarshalJSON methods to avoid panic if mal-formed arguments are passed.

This commit is contained in:
philip-morlier 2022-01-27 11:12:56 -08:00
parent 44c7e0e589
commit ff5d2e8030

View File

@ -1,10 +1,10 @@
package core package core
import ( import (
"strings"
"bytes" "bytes"
"fmt"
"encoding/hex" "encoding/hex"
"fmt"
"strings"
) )
type Hash [32]byte type Hash [32]byte
@ -15,6 +15,9 @@ func (h Hash) MarshalJSON() ([]byte, error) {
func (h *Hash) UnmarshalJSON(data []byte) error { func (h *Hash) UnmarshalJSON(data []byte) error {
d := bytes.TrimPrefix(bytes.Trim(data, `"`), []byte("0x")) d := bytes.TrimPrefix(bytes.Trim(data, `"`), []byte("0x"))
if len(d) > 64 {
return fmt.Errorf("argument of invalid length")
}
_, err := hex.Decode(h[(64-len(d))/2:], d) _, err := hex.Decode(h[(64-len(d))/2:], d)
return err return err
} }
@ -48,6 +51,9 @@ func (h Address) MarshalJSON() ([]byte, error) {
func (h *Address) UnmarshalJSON(data []byte) error { func (h *Address) UnmarshalJSON(data []byte) error {
d := bytes.TrimPrefix(bytes.Trim(data, `"`), []byte("0x")) d := bytes.TrimPrefix(bytes.Trim(data, `"`), []byte("0x"))
if len(d) > 40 {
return fmt.Errorf("argument of invalid length")
}
_, err := hex.Decode(h[(40-len(d))/2:], d) _, err := hex.Decode(h[(40-len(d))/2:], d)
return err return err
} }
@ -56,7 +62,6 @@ func (h Address) String() string {
return fmt.Sprintf("%#x", h[:]) return fmt.Sprintf("%#x", h[:])
} }
func HexToAddress(data string) Address { func HexToAddress(data string) Address {
h := Address{} h := Address{}
b, _ := hex.DecodeString(strings.TrimPrefix(strings.Trim(data, `"`), "0x")) b, _ := hex.DecodeString(strings.TrimPrefix(strings.Trim(data, `"`), "0x"))
@ -70,7 +75,6 @@ func BytesToAddress(b []byte) Address {
return h return h
} }
type ChainEvent struct { type ChainEvent struct {
Block []byte // RLP Encoded block Block []byte // RLP Encoded block
Hash Hash Hash Hash
@ -96,7 +100,6 @@ type API struct {
Public bool Public bool
} }
func CopyBytes(a []byte) []byte { func CopyBytes(a []byte) []byte {
b := make([]byte, len(a)) b := make([]byte, len(a))
copy(b[:], a[:]) copy(b[:], a[:])