From ea74c596eb2c5a1abdceec121108565c5b32c962 Mon Sep 17 00:00:00 2001 From: anthdm Date: Sun, 4 Mar 2018 18:36:18 +0100 Subject: [PATCH] Started RPC package to allow querying balances and sending raw transactions for sc's --- main.go | 25 ++++++++++ pkg/api/.keep | 0 pkg/rpc/client.go | 123 ++++++++++++++++++++++++++++++++++++++++++++++ pkg/rpc/doc.go | 33 +++++++++++++ pkg/rpc/rpc.go | 29 +++++++++++ pkg/rpc/types.go | 53 ++++++++++++++++++++ 6 files changed, 263 insertions(+) create mode 100644 main.go delete mode 100644 pkg/api/.keep create mode 100644 pkg/rpc/client.go create mode 100644 pkg/rpc/doc.go create mode 100644 pkg/rpc/rpc.go create mode 100644 pkg/rpc/types.go diff --git a/main.go b/main.go new file mode 100644 index 000000000..704d9e3e1 --- /dev/null +++ b/main.go @@ -0,0 +1,25 @@ +package main + +import ( + "context" + "fmt" + "log" + + "github.com/CityOfZion/neo-go/pkg/rpc" +) + +func main() { + client, err := rpc.NewClient(context.TODO(), "http://seed5.bridgeprotocol.io:10332", rpc.ClientOptions{}) + if err != nil { + log.Fatal(err) + } + if err := client.Ping(); err != nil { + log.Fatal(err) + } + + resp, err := client.GetAccountState("AcsdonGS7EYbXzFWuMV2WKZ4DnKd9ddcc1") + if err != nil { + log.Fatal(err) + } + fmt.Printf("%+v\n", resp.ID) +} diff --git a/pkg/api/.keep b/pkg/api/.keep deleted file mode 100644 index e69de29bb..000000000 diff --git a/pkg/rpc/client.go b/pkg/rpc/client.go new file mode 100644 index 000000000..a9b70d3e2 --- /dev/null +++ b/pkg/rpc/client.go @@ -0,0 +1,123 @@ +package rpc + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net" + "net/http" + "net/url" + "time" +) + +var ( + defaultDialTimeout = 4 * time.Second + defaultRequestTimeout = 4 * time.Second + defaultClientVersion = "2.0" +) + +// Client represents the middleman for executing JSON RPC calls +// to remote NEO RPC nodes. +type Client struct { + // The underlying http client. It's never a good practice to use + // the http.DefaultClient, therefore we will role our own. + http.Client + endpoint *url.URL + ctx context.Context + version string +} + +// ClientOptions defines options for the RPC client. +// All Values are optional. If any duration is not specified +// a default of 3 seconds will be used. +type ClientOptions struct { + Cert string + Key string + CACert string + DialTimeout time.Duration + RequestTimeout time.Duration + // Version is the version of the client that will be send + // along with the request body. If no version is specified + // the default version (currently 2.0) will be used. + Version string +} + +// NewClient return a new Client ready to use. +func NewClient(ctx context.Context, endpoint string, opts ClientOptions) (*Client, error) { + url, err := url.Parse(endpoint) + if err != nil { + return nil, err + } + + if opts.DialTimeout == 0 { + opts.DialTimeout = defaultDialTimeout + } + if opts.RequestTimeout == 0 { + opts.RequestTimeout = defaultRequestTimeout + } + if opts.Version == "" { + opts.Version = defaultClientVersion + } + + transport := &http.Transport{ + Dial: (&net.Dialer{ + Timeout: opts.DialTimeout, + }).Dial, + } + + // TODO(@antdm): Enable SSL. + if opts.Cert != "" && opts.Key != "" { + + } + + return &Client{ + Client: http.Client{ + Timeout: opts.RequestTimeout, + Transport: transport, + }, + endpoint: url, + ctx: ctx, + version: opts.Version, + }, nil +} + +func (c *Client) performRequest(method string, p params, v interface{}) error { + r := request{ + JSONRPC: c.version, + Method: method, + Params: p.values, + ID: 1, + } + + b, err := json.Marshal(r) + if err != nil { + return err + } + req, err := http.NewRequest("POST", c.endpoint.String(), bytes.NewReader(b)) + if err != nil { + return err + } + resp, err := c.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("Remote responded with a non 200 response: %d", resp.StatusCode) + } + + return json.NewDecoder(resp.Body).Decode(v) +} + +// Ping attempts to create a connection to the endpoint. +// and returns an error if there is one. +func (c *Client) Ping() error { + conn, err := net.DialTimeout("tcp", c.endpoint.Host, defaultDialTimeout) + if err != nil { + return err + } + _ = conn.Close() + return nil +} diff --git a/pkg/rpc/doc.go b/pkg/rpc/doc.go new file mode 100644 index 000000000..36e114081 --- /dev/null +++ b/pkg/rpc/doc.go @@ -0,0 +1,33 @@ +package rpc + +/* +Package rpc provides interaction with a NEO node over JSON-RPC. +After creating a client instance with or without a ClientConfig +you can interact with the NEO blockchain by its exposed methods. + +Some of the methods also allow to pass a verbose bool. This will +return a more pretty printed response from the server instead of +a raw hex string. + +An example: + endpoint := "http://seed5.bridgeprotocol.io:10332" + opts := rpc.ClientOptions{} + + client, err := rpc.NewClient(context.TODO(), endpoint, opts) + if err != nil { + log.Fatal(err) + } + + if err := client.Ping(); err != nil { + log.Fatal(err) + } + + resp, err := client.GetAccountState("ATySFJAbLW7QHsZGHScLhxq6EyNBxx3eFP") + if err != nil { + log.Fatal(err) + } + log.Println(resp.Result.ScriptHash) + log.Println(resp.Result.Balances) + +To be continued with more in depth examples. +*/ diff --git a/pkg/rpc/rpc.go b/pkg/rpc/rpc.go new file mode 100644 index 000000000..889211651 --- /dev/null +++ b/pkg/rpc/rpc.go @@ -0,0 +1,29 @@ +package rpc + +// GetBlock returns a block by its hash or index/height. If verbose is true +// the response will contain a pretty Block object instead of the raw hex string. +func (c *Client) GetBlock(indexOrHash interface{}, verbose bool) (*response, error) { + var ( + params = newParams(indexOrHash) + resp = &response{} + ) + if verbose { + params = newParams(indexOrHash, 1) + } + if err := c.performRequest("getblock", params, resp); err != nil { + return nil, err + } + return resp, nil +} + +// GetAccountState will return detailed information about a NEO account. +func (c *Client) GetAccountState(address string) (*AccountStateResponse, error) { + var ( + params = newParams(address) + resp = &AccountStateResponse{} + ) + if err := c.performRequest("getaccountstate", params, resp); err != nil { + return nil, err + } + return resp, nil +} diff --git a/pkg/rpc/types.go b/pkg/rpc/types.go new file mode 100644 index 000000000..48e0eeb92 --- /dev/null +++ b/pkg/rpc/types.go @@ -0,0 +1,53 @@ +package rpc + +// AccountStateResponse holds the getaccountstate response. +type AccountStateResponse struct { + responseHeader + Result *Account `json:"result"` +} + +// Account respresents details about a NEO account. +type Account struct { + Version int `json:"version"` + ScriptHash string `json:"script_hash"` + Frozen bool + // TODO: need to check this field out. + Votes []interface{} + Balances []*Balance +} + +// Balance respresents details about a NEO account balance. +type Balance struct { + Asset string `json:"asset"` + Value string `json:"value"` +} + +type params struct { + values []interface{} +} + +func newParams(vals ...interface{}) params { + p := params{} + p.values = make([]interface{}, len(vals)) + for i := 0; i < len(p.values); i++ { + p.values[i] = vals[i] + } + return p +} + +type request struct { + JSONRPC string `json:"jsonrpc"` + Method string `json:"method"` + Params []interface{} `json:"params"` + ID int `json:"id"` +} + +type responseHeader struct { + ID int `json:"id"` + JSONRPC string `json:"jsonrpc"` +} + +type response struct { + responseHeader + Result interface{} `json:"result"` +}