mirror of
https://github.com/nspcc-dev/neo-go.git
synced 2024-11-22 19:29:39 +00:00
RPC client (#42)
* Started RPC package to allow querying balances and sending raw transactions for sc's * integrate invoke cmd in cli * bumped version * added sendrawtransaction to the rpc client.
This commit is contained in:
parent
1a1a19da7d
commit
b2a5e34aac
7 changed files with 343 additions and 4 deletions
2
VERSION
2
VERSION
|
@ -1 +1 @@
|
|||
0.24.0
|
||||
0.25.0
|
||||
|
|
|
@ -1,12 +1,19 @@
|
|||
package smartcontract
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
|
||||
"github.com/CityOfZion/neo-go/pkg/rpc"
|
||||
"github.com/CityOfZion/neo-go/pkg/vm/compiler"
|
||||
"github.com/urfave/cli"
|
||||
)
|
||||
|
||||
const (
|
||||
ErrNoInput = "Input file is mandatory and should be passed using -i flag."
|
||||
errNoInput = "Input file is mandatory and should be passed using -i flag."
|
||||
)
|
||||
|
||||
// NewCommand returns a new contract command.
|
||||
|
@ -30,6 +37,17 @@ func NewCommand() cli.Command {
|
|||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "invoke",
|
||||
Usage: "Test an invocation of a smart contract on the blockchain",
|
||||
Action: testInvoke,
|
||||
Flags: []cli.Flag{
|
||||
cli.StringFlag{
|
||||
Name: "in, i",
|
||||
Usage: "Input location of the avm file that needs to be invoked",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "opdump",
|
||||
Usage: "dump the opcode of a .go file",
|
||||
|
@ -48,7 +66,7 @@ func NewCommand() cli.Command {
|
|||
func contractCompile(ctx *cli.Context) error {
|
||||
src := ctx.String("in")
|
||||
if len(src) == 0 {
|
||||
return cli.NewExitError(ErrNoInput, 1)
|
||||
return cli.NewExitError(errNoInput, 1)
|
||||
}
|
||||
|
||||
o := &compiler.Options{
|
||||
|
@ -62,10 +80,46 @@ func contractCompile(ctx *cli.Context) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func testInvoke(ctx *cli.Context) error {
|
||||
src := ctx.String("in")
|
||||
if len(src) == 0 {
|
||||
return cli.NewExitError(errNoInput, 1)
|
||||
}
|
||||
b, err := ioutil.ReadFile(src)
|
||||
if err != nil {
|
||||
return cli.NewExitError(err, 1)
|
||||
}
|
||||
|
||||
// For now we will hardcode the endpoint.
|
||||
// On the long term the internal VM will run the script.
|
||||
// TODO: remove RPC dependency, hardcoded node.
|
||||
endpoint := "http://seed5.bridgeprotocol.io:10332"
|
||||
opts := rpc.ClientOptions{}
|
||||
client, err := rpc.NewClient(context.TODO(), endpoint, opts)
|
||||
if err != nil {
|
||||
return cli.NewExitError(err, 1)
|
||||
}
|
||||
|
||||
scriptHex := hex.EncodeToString(b)
|
||||
resp, err := client.InvokeScript(scriptHex)
|
||||
if err != nil {
|
||||
return cli.NewExitError(err, 1)
|
||||
}
|
||||
|
||||
b, err = json.MarshalIndent(resp.Result, "", " ")
|
||||
if err != nil {
|
||||
return cli.NewExitError(err, 1)
|
||||
}
|
||||
|
||||
fmt.Println(string(b))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func contractDumpOpcode(ctx *cli.Context) error {
|
||||
src := ctx.String("in")
|
||||
if len(src) == 0 {
|
||||
return cli.NewExitError(ErrNoInput, 1)
|
||||
return cli.NewExitError(errNoInput, 1)
|
||||
}
|
||||
if err := compiler.DumpOpcode(src); err != nil {
|
||||
return cli.NewExitError(err, 1)
|
||||
|
|
123
pkg/rpc/client.go
Normal file
123
pkg/rpc/client.go
Normal 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
33
pkg/rpc/doc.go
Normal 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.
|
||||
*/
|
57
pkg/rpc/rpc.go
Normal file
57
pkg/rpc/rpc.go
Normal file
|
@ -0,0 +1,57 @@
|
|||
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
|
||||
}
|
||||
|
||||
// InvokeScipt returns the result of the given script after running it true the VM.
|
||||
// NOTE: This is a test invoke and will not affect the blokchain.
|
||||
func (c *Client) InvokeScript(script string) (*InvokeScriptResponse, error) {
|
||||
var (
|
||||
params = newParams(script)
|
||||
resp = &InvokeScriptResponse{}
|
||||
)
|
||||
if err := c.performRequest("invokescript", params, resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// SendRawTransaction broadcasts a transaction over the NEO network.
|
||||
// The given hex string needs to be signed with a keypair.
|
||||
// When the result of the response object is true, the TX has successfully
|
||||
// been broadcasted to the network.
|
||||
func (c *Client) SendRawTransaction(rawTX string) (*response, error) {
|
||||
var (
|
||||
params = newParams(rawTX)
|
||||
resp = &response{}
|
||||
)
|
||||
if err := c.performRequest("sendrawtransaction", params, resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return resp, nil
|
||||
}
|
72
pkg/rpc/types.go
Normal file
72
pkg/rpc/types.go
Normal file
|
@ -0,0 +1,72 @@
|
|||
package rpc
|
||||
|
||||
type InvokeScriptResponse struct {
|
||||
responseHeader
|
||||
Result *InvokeResult
|
||||
}
|
||||
|
||||
// InvokeResult represents the outcome of a script that is
|
||||
// executed by the NEO VM.
|
||||
type InvokeResult struct {
|
||||
State string `json:"state"`
|
||||
GasConsumed string `json:"gas_consumed"`
|
||||
Stack []*StackParam
|
||||
}
|
||||
|
||||
// StackParam respresent a stack parameter.
|
||||
type StackParam struct {
|
||||
Type string `json:"type"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
// 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"`
|
||||
}
|
Loading…
Reference in a new issue