Started RPC package to allow querying balances and sending raw transactions for sc's

This commit is contained in:
anthdm 2018-03-04 18:36:18 +01:00
parent dc83b584be
commit ea74c596eb
6 changed files with 263 additions and 0 deletions

25
main.go Normal file
View file

@ -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)
}

View file

123
pkg/rpc/client.go Normal file
View file

@ -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
}

33
pkg/rpc/doc.go Normal file
View file

@ -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.
*/

29
pkg/rpc/rpc.go Normal file
View file

@ -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
}

53
pkg/rpc/types.go Normal file
View file

@ -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"`
}