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
import (
"strings"
"bytes"
"fmt"
"encoding/hex"
"fmt"
"strings"
)
type Hash [32]byte
@ -15,7 +15,10 @@ func (h Hash) MarshalJSON() ([]byte, error) {
func (h *Hash) UnmarshalJSON(data []byte) error {
d := bytes.TrimPrefix(bytes.Trim(data, `"`), []byte("0x"))
_, err := hex.Decode(h[(64 - len(d)) / 2:], d)
if len(d) > 64 {
return fmt.Errorf("argument of invalid length")
}
_, err := hex.Decode(h[(64-len(d))/2:], d)
return err
}
@ -30,7 +33,7 @@ func (h Hash) String() string {
func HexToHash(data string) Hash {
h := Hash{}
b, _ := hex.DecodeString(strings.TrimPrefix(strings.Trim(data, `"`), "0x"))
copy(h[32 - len(b):], b)
copy(h[32-len(b):], b)
return h
}
@ -48,7 +51,10 @@ func (h Address) MarshalJSON() ([]byte, error) {
func (h *Address) UnmarshalJSON(data []byte) error {
d := bytes.TrimPrefix(bytes.Trim(data, `"`), []byte("0x"))
_, err := hex.Decode(h[(40 - len(d))/2:], d)
if len(d) > 40 {
return fmt.Errorf("argument of invalid length")
}
_, err := hex.Decode(h[(40-len(d))/2:], d)
return err
}
@ -56,11 +62,10 @@ func (h Address) String() string {
return fmt.Sprintf("%#x", h[:])
}
func HexToAddress(data string) Address {
h := Address{}
b, _ := hex.DecodeString(strings.TrimPrefix(strings.Trim(data, `"`), "0x"))
copy(h[20 - len(b):], b)
copy(h[20-len(b):], b)
return h
}
@ -70,7 +75,6 @@ func BytesToAddress(b []byte) Address {
return h
}
type ChainEvent struct {
Block []byte // RLP Encoded block
Hash Hash
@ -81,12 +85,12 @@ type ChainSideEvent struct {
Block []byte // RLP Encoded block
}
type ChainHeadEvent struct{
Block []byte // RLP Encoded block
type ChainHeadEvent struct {
Block []byte // RLP Encoded block
}
type NewTxsEvent struct{
Txs [][]byte // []RLP encoded transaction
type NewTxsEvent struct {
Txs [][]byte // []RLP encoded transaction
}
type API struct {
@ -96,7 +100,6 @@ type API struct {
Public bool
}
func CopyBytes(a []byte) []byte {
b := make([]byte, len(a))
copy(b[:], a[:])