diff options
author | Bas van Kervel <bas@ethdev.com> | 2015-10-15 22:07:19 +0800 |
---|---|---|
committer | Bas van Kervel <bas@ethdev.com> | 2015-12-14 23:34:05 +0800 |
commit | eae81465c1c815c317cd30e4de6bdf4d59df2340 (patch) | |
tree | b6f4b7787967a58416171adb79fd12ac29d89577 /common | |
parent | 8db9d44ca9fb6baf406256cae491c475de2f4989 (diff) | |
download | go-tangerine-eae81465c1c815c317cd30e4de6bdf4d59df2340.tar go-tangerine-eae81465c1c815c317cd30e4de6bdf4d59df2340.tar.gz go-tangerine-eae81465c1c815c317cd30e4de6bdf4d59df2340.tar.bz2 go-tangerine-eae81465c1c815c317cd30e4de6bdf4d59df2340.tar.lz go-tangerine-eae81465c1c815c317cd30e4de6bdf4d59df2340.tar.xz go-tangerine-eae81465c1c815c317cd30e4de6bdf4d59df2340.tar.zst go-tangerine-eae81465c1c815c317cd30e4de6bdf4d59df2340.zip |
rpc: new RPC implementation with pub/sub support
Diffstat (limited to 'common')
-rw-r--r-- | common/types.go | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/common/types.go b/common/types.go index acbd5b28d..b1666d733 100644 --- a/common/types.go +++ b/common/types.go @@ -17,6 +17,8 @@ package common import ( + "encoding/hex" + "encoding/json" "fmt" "math/big" "math/rand" @@ -50,6 +52,21 @@ func (h Hash) Bytes() []byte { return h[:] } func (h Hash) Big() *big.Int { return Bytes2Big(h[:]) } func (h Hash) Hex() string { return "0x" + Bytes2Hex(h[:]) } +// UnmarshalJSON parses a hash in its hex from to a hash. +func (h *Hash) UnmarshalJSON(input []byte) error { + length := len(input) + if length >= 2 && input[0] == '"' && input[length-1] == '"' { + input = input[1 : length-1] + } + h.SetBytes(FromHex(string(input))) + return nil +} + +// Serialize given hash to JSON +func (h Hash) MarshalJSON() ([]byte, error) { + return json.Marshal(h.Hex()) +} + // Sets the hash to the value of b. If b is larger than len(h) it will panic func (h *Hash) SetBytes(b []byte) { if len(b) > len(h) { @@ -129,6 +146,38 @@ func (a *Address) Set(other Address) { } } +// Serialize given address to JSON +func (a Address) MarshalJSON() ([]byte, error) { + return json.Marshal(a.Hex()) +} + +// Parse address from raw json data +func (a *Address) UnmarshalJSON(data []byte) error { + if len(data) > 2 && data[0] == '"' && data[len(data)-1] == '"' { + data = data[:len(data)-1][1:] + } + + if len(data) > 2 && data[0] == '0' && data[1] == 'x' { + data = data[2:] + } + + if len(data) != 2*AddressLength { + return fmt.Errorf("Invalid address length, expected %d got %d bytes", 2*AddressLength, len(data)) + } + + n, err := hex.Decode(a[:], data) + if err != nil { + return err + } + + if n != AddressLength { + return fmt.Errorf("Invalid address") + } + + a.Set(HexToAddress(string(data))) + return nil +} + // PP Pretty Prints a byte slice in the following format: // hex(value[:4])...(hex[len(value)-4:]) func PP(value []byte) string { |