From eae81465c1c815c317cd30e4de6bdf4d59df2340 Mon Sep 17 00:00:00 2001
From: Bas van Kervel <bas@ethdev.com>
Date: Thu, 15 Oct 2015 16:07:19 +0200
Subject: rpc: new RPC implementation with pub/sub support

---
 common/types.go | 49 +++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 49 insertions(+)

(limited to 'common')

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 {
-- 
cgit v1.2.3