neo-go: github.com/nspcc-dev/neo-go/pkg/rpc Index | Files | Directories

package rpc

import "github.com/nspcc-dev/neo-go/pkg/rpc"

Package rpc implements NEO-specific JSON-RPC 2.0 client and server. This package is currently in alpha and is subject to change.

Client

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)

TODO:

Merge structs so can be used by both server and client.
Add missing methods to client.
Allow client to connect using client cert.
More in-depth examples.

Supported methods

getblock
getaccountstate
getunspents
invokescript
invokefunction
sendrawtransaction
invoke
getrawtransaction

Unsupported methods

validateaddress
getblocksysfee
getcontractstate
getrawmempool
getstorage
submitblock
gettxout
getassetstate
getpeers
getversion
getconnectioncount
getblockhash
getblockcount
getbestblockhash

Server

The server is written to support as much of the JSON-RPC 2.0 Spec as possible. The server is run as part of the node currently.

TODO:

Implement HTTPS server.
Add remaining methods (Documented below).
Add Swagger spec and test using dredd in circleCI.

Example call

An example would be viewing the version of the node:

$ curl -X POST -d '{"jsonrpc": "2.0", "method": "getversion", "params": [], "id": 1}' http://localhost:20332

which would yield the response:

{
  "jsonrpc" : "2.0",
    "id" : 1,
    "result" : {
      "port" : 20333,
      "useragent" : "/NEO-GO:0.36.0-dev/",
      "nonce" : 9318417
    }
}

Unsupported methods

getblocksysfee
getcontractstate (needs to be implemented in pkg/core/blockchain.go)
getrawmempool (needs to be implemented on in pkg/network/server.go)
getrawtransaction (needs to be implemented in pkg/core/blockchain.go)
getstorage (lacks VM functionality)
gettxout (needs to be implemented in pkg/core/blockchain.go)
invoke (lacks VM functionality)
invokefunction (lacks VM functionality)
invokescript (lacks VM functionality)
sendrawtransaction (needs to be implemented in pkg/core/blockchain.go)
submitblock (needs to be implemented in pkg/core/blockchain.go)

Index

Package Files

client.go doc.go errors.go neoScanBalanceGetter.go neoScanTypes.go param.go params.go prometheus.go request.go rpc.go scdetails.go server.go stack_param.go txBuilder.go txTypes.go types.go

func AddInputsAndUnspentsToTx Uses

func AddInputsAndUnspentsToTx(tx *transaction.Transaction, addr string, assetID util.Uint256, amount util.Fixed8, balancer BalanceGetter) error

AddInputsAndUnspentsToTx adds inputs needed to transaction and one output with change.

func CreateDeploymentScript Uses

func CreateDeploymentScript(avm []byte, contract *ContractDetails) ([]byte, error)

CreateDeploymentScript returns a script that deploys given smart contract with its metadata.

func CreateFunctionInvocationScript Uses

func CreateFunctionInvocationScript(contract util.Uint160, params Params) ([]byte, error)

CreateFunctionInvocationScript creates a script to invoke given contract with given parameters.

func CreateInvocationScript Uses

func CreateInvocationScript(contract util.Uint160, funcParams []Param) ([]byte, error)

CreateInvocationScript creates a script to invoke given contract with given parameters. It differs from CreateFunctionInvocationScript in that it expects one array of FuncParams and expands it onto the stack as independent elements.

func CreateRawContractTransaction Uses

func CreateRawContractTransaction(params ContractTxParams) (*transaction.Transaction, error)

CreateRawContractTransaction returns contract-type Transaction built from specified parameters.

func GetInvocationScript Uses

func GetInvocationScript(tx *transaction.Transaction, wif *keys.WIF) ([]byte, error)

GetInvocationScript returns NEO VM script containing transaction signature.

func SignTx Uses

func SignTx(tx *transaction.Transaction, wif *keys.WIF) error

SignTx signs given transaction in-place using given key.

type Account Uses

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
}

Account represents details about a NEO account.

type AccountStateResponse Uses

type AccountStateResponse struct {
    Result *Account `json:"result"`
    // contains filtered or unexported fields
}

AccountStateResponse holds the getaccountstate response.

type Balance Uses

type Balance struct {
    Asset string `json:"asset"`
    Value string `json:"value"`
}

Balance represents details about a NEO account balance.

type BalanceGetter Uses

type BalanceGetter interface {
    // 		parameters
    // address: 	base58-encoded address assets would be transferred from
    // assetID: 	asset identifier
    // amount: 		an asset amount to spend
    // 		return values
    // inputs: 		UTXO's for the preparing transaction
    // total: 		summarized asset amount from all the `inputs`
    // error: 		error would be considered in the caller function
    CalculateInputs(address string, assetID util.Uint256, amount util.Fixed8) (inputs []transaction.Input, total util.Fixed8, err error)
}

BalanceGetter is an interface supporting CalculateInputs() method.

type Client Uses

type Client struct {
    // contains filtered or unexported fields
}

Client represents the middleman for executing JSON RPC calls to remote NEO RPC nodes.

func NewClient Uses

func NewClient(ctx context.Context, endpoint string, opts ClientOptions) (*Client, error)

NewClient returns a new Client ready to use.

func (*Client) Balancer Uses

func (c *Client) Balancer() BalanceGetter

Balancer is a getter for balance field.

func (*Client) CalculateInputs Uses

func (c *Client) CalculateInputs(address string, asset util.Uint256, cost util.Fixed8) ([]transaction.Input, util.Fixed8, error)

CalculateInputs creates input transactions for the specified amount of given asset belonging to specified address. This implementation uses GetUnspents JSON-RPC call internally, so make sure your RPC server suppors that.

func (*Client) Client Uses

func (c *Client) Client() *http.Client

Client is a getter for client field.

func (*Client) GetAccountState Uses

func (c *Client) GetAccountState(address string) (*AccountStateResponse, error)

GetAccountState returns detailed information about a NEO account.

func (*Client) GetUnspents Uses

func (c *Client) GetUnspents(address string) (*UnspentResponse, error)

GetUnspents returns UTXOs for the given NEO account.

func (*Client) Invoke Uses

func (c *Client) Invoke(script string, params []smartcontract.Parameter) (*InvokeScriptResponse, error)

Invoke returns the results after calling the smart contract scripthash with the given parameters.

func (*Client) InvokeFunction Uses

func (c *Client) InvokeFunction(script, operation string, params []smartcontract.Parameter) (*InvokeScriptResponse, error)

InvokeFunction returns the results after calling the smart contract scripthash with the given operation and parameters. NOTE: this is test invoke and will not affect the blockchain.

func (*Client) InvokeScript Uses

func (c *Client) InvokeScript(script string) (*InvokeScriptResponse, error)

InvokeScript returns the result of the given script after running it true the VM. NOTE: This is a test invoke and will not affect the blockchain.

func (*Client) Ping Uses

func (c *Client) Ping() error

Ping attempts to create a connection to the endpoint. and returns an error if there is one.

func (*Client) SendToAddress Uses

func (c *Client) SendToAddress(asset util.Uint256, address string, amount util.Fixed8) (*SendToAddressResponse, error)

SendToAddress sends an amount of specific asset to a given address. This call requires open wallet. (`wif` key in client struct.) If response.Result is `true` then transaction was formed correctly and was written in blockchain.

func (*Client) SetBalancer Uses

func (c *Client) SetBalancer(b BalanceGetter)

SetBalancer is a setter for balance field.

func (*Client) SetClient Uses

func (c *Client) SetClient(cli *http.Client)

SetClient is a setter for client field.

func (*Client) SetWIF Uses

func (c *Client) SetWIF(wif string) error

SetWIF decodes given WIF and adds some wallet data to client. Useful for RPC calls that require an open wallet.

func (*Client) SignAndPushInvocationTx Uses

func (c *Client) SignAndPushInvocationTx(script []byte, wif *keys.WIF, gas util.Fixed8) (util.Uint256, error)

SignAndPushInvocationTx signs and pushes given script as an invocation transaction using given wif to sign it and spending the amount of gas specified. It returns a hash of the invocation transaction and an error.

func (*Client) WIF Uses

func (c *Client) WIF() keys.WIF

WIF returns WIF structure associated with the client.

type ClientOptions Uses

type ClientOptions struct {
    Cert        string
    Key         string
    CACert      string
    DialTimeout time.Duration
    Client      *http.Client
    // 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
}

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 ContractDetails Uses

type ContractDetails struct {
    Author               string
    Email                string
    Version              string
    ProjectName          string `yaml:"name"`
    Description          string
    HasStorage           bool
    HasDynamicInvocation bool
    IsPayable            bool
    ReturnType           StackParamType
    Parameters           []StackParamType
}

ContractDetails contains contract metadata.

type ContractTxParams Uses

type ContractTxParams struct {
    // contains filtered or unexported fields
}

ContractTxParams contains parameters for tx to transfer assets; includes parameters duplication `sendtoaddress` RPC call params and also some utility data;

type Error Uses

type Error struct {
    Code     int64  `json:"code"`
    HTTPCode int    `json:"-"`
    Cause    error  `json:"-"`
    Message  string `json:"message"`
    Data     string `json:"data,omitempty"`
}

Error object for outputting JSON-RPC 2.0 errors.

func NewInternalServerError Uses

func NewInternalServerError(data string, cause error) *Error

NewInternalServerError creates a new error with code -32603.

func NewInvalidParamsError Uses

func NewInvalidParamsError(data string, cause error) *Error

NewInvalidParamsError creates a new error with code -32602.

func NewInvalidRequestError Uses

func NewInvalidRequestError(data string, cause error) *Error

NewInvalidRequestError creates a new error with code -32600.

func NewMethodNotFoundError Uses

func NewMethodNotFoundError(data string, cause error) *Error

NewMethodNotFoundError creates a new error with code -32601.

func NewParseError Uses

func NewParseError(data string, cause error) *Error

NewParseError creates a new error with code -32700.:%s

func (Error) Error Uses

func (e Error) Error() string

Error implements the error interface.

type FuncParam Uses

type FuncParam struct {
    Type  StackParamType `json:"type"`
    Value Param          `json:"value"`
}

FuncParam represents a function argument parameter used in the invokefunction RPC method.

type GetRawTxResponse Uses

type GetRawTxResponse struct {
    Error  *Error         `json:"error"`
    Result *RawTxResponse `json:"result"`
    // contains filtered or unexported fields
}

GetRawTxResponse represents verbose output of `getrawtransaction` RPC call.

type InvokeResult Uses

type InvokeResult struct {
    State       vm.State `json:"state"`
    GasConsumed string   `json:"gas_consumed"`
    Script      string   `json:"script"`
    Stack       []StackParam
}

InvokeResult represents the outcome of a script that is executed by the NEO VM.

type InvokeScriptResponse Uses

type InvokeScriptResponse struct {
    Error  *Error        `json:"error,omitempty"`
    Result *InvokeResult `json:"result,omitempty"`
    // contains filtered or unexported fields
}

InvokeScriptResponse stores response for the invoke script call.

type NeoScanBalance Uses

type NeoScanBalance struct {
    Balance []*Unspent
    Address string
}

NeoScanBalance is a struct of NeoScan response to 'get_balance' request

type NeoScanServer Uses

type NeoScanServer struct {
    URL  string // "protocol://host:port/"
    Path string // path to API endpoint without wallet address
}

NeoScanServer stores NEOSCAN URL and API path.

func (NeoScanServer) CalculateInputs Uses

func (s NeoScanServer) CalculateInputs(address string, assetIDUint util.Uint256, cost util.Fixed8) ([]transaction.Input, util.Fixed8, error)

CalculateInputs creates input transactions for the specified amount of given asset belonging to specified address.

func (NeoScanServer) GetBalance Uses

func (s NeoScanServer) GetBalance(address string) ([]*Unspent, error)

GetBalance performs a request to get balance for the address specified.

type Param Uses

type Param struct {
    Type  paramType
    Value interface{}
}

Param represents a param either passed to the server or to send to a server using the client.

func (Param) GetArray Uses

func (p Param) GetArray() ([]Param, error)

GetArray returns a slice of Params stored in the parameter.

func (Param) GetBytesHex Uses

func (p Param) GetBytesHex() ([]byte, error)

GetBytesHex returns []byte value of the parameter if it is a hex-encoded string.

func (Param) GetFuncParam Uses

func (p Param) GetFuncParam() (FuncParam, error)

GetFuncParam returns current parameter as a function call parameter.

func (Param) GetInt Uses

func (p Param) GetInt() (int, error)

GetInt returns int value of te parameter.

func (Param) GetString Uses

func (p Param) GetString() (string, error)

GetString returns string value of the parameter.

func (Param) GetUint160FromAddress Uses

func (p Param) GetUint160FromAddress() (util.Uint160, error)

GetUint160FromAddress returns Uint160 value of the parameter that was supplied as an address.

func (Param) GetUint160FromHex Uses

func (p Param) GetUint160FromHex() (util.Uint160, error)

GetUint160FromHex returns Uint160 value of the parameter encoded in hex.

func (Param) GetUint256 Uses

func (p Param) GetUint256() (util.Uint256, error)

GetUint256 returns Uint256 value of the parameter.

func (Param) String Uses

func (p Param) String() string

func (*Param) UnmarshalJSON Uses

func (p *Param) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler interface.

type Params Uses

type Params []Param

Params represents the JSON-RPC params.

func (Params) Value Uses

func (p Params) Value(index int) (*Param, bool)

Value returns the param struct for the given index if it exists.

func (Params) ValueWithType Uses

func (p Params) ValueWithType(index int, valType paramType) (*Param, bool)

ValueWithType returns the param struct at the given index if it exists and matches the given type.

type RawTxResponse Uses

type RawTxResponse struct {
    TxResponse
    BlockHash     string `json:"blockhash"`
    Confirmations uint   `json:"confirmations"`
    BlockTime     uint   `json:"blocktime"`
}

RawTxResponse stores transaction with blockchain metadata to be sent as a response.

type Request Uses

type Request struct {
    JSONRPC   string          `json:"jsonrpc"`
    Method    string          `json:"method"`
    RawParams json.RawMessage `json:"params,omitempty"`
    RawID     json.RawMessage `json:"id,omitempty"`
}

Request represents a standard JSON-RPC 2.0 request: http://www.jsonrpc.org/specification#request_object.

func NewRequest Uses

func NewRequest() *Request

NewRequest creates a new Request struct.

func (*Request) DecodeData Uses

func (r *Request) DecodeData(data io.ReadCloser) error

DecodeData decodes the given reader into the the request struct.

func (*Request) Params Uses

func (r *Request) Params() (*Params, error)

Params takes a slice of any type and attempts to bind the params to it.

type Response Uses

type Response struct {
    JSONRPC string          `json:"jsonrpc"`
    Result  interface{}     `json:"result,omitempty"`
    Error   *Error          `json:"error,omitempty"`
    ID      json.RawMessage `json:"id,omitempty"`
}

Response represents a standard JSON-RPC 2.0 response: http://www.jsonrpc.org/specification#response_object.

type SendToAddressResponse Uses

type SendToAddressResponse struct {
    Error  *Error `json:"error"`
    Result *TxResponse
    // contains filtered or unexported fields
}

SendToAddressResponse stores response for the sendtoaddress call.

type Server Uses

type Server struct {
    *http.Server
    // contains filtered or unexported fields
}

Server represents the JSON-RPC 2.0 server.

func NewServer Uses

func NewServer(chain core.Blockchainer, conf config.RPCConfig, coreServer *network.Server, log *zap.Logger) Server

NewServer creates a new Server struct.

func (*Server) Shutdown Uses

func (s *Server) Shutdown() error

Shutdown overrides the http.Server Shutdown method.

func (*Server) Start Uses

func (s *Server) Start(errChan chan error)

Start creates a new JSON-RPC server listening on the configured port.

func (*Server) WriteErrorResponse Uses

func (s *Server) WriteErrorResponse(r *Request, w http.ResponseWriter, err error)

WriteErrorResponse writes an error response to the ResponseWriter.

func (*Server) WriteResponse Uses

func (s *Server) WriteResponse(r *Request, w http.ResponseWriter, result interface{})

WriteResponse encodes the response and writes it to the ResponseWriter.

type StackParam Uses

type StackParam struct {
    Type  StackParamType `json:"type"`
    Value interface{}    `json:"value"`
}

StackParam represent a stack parameter.

func (StackParam) TryParse Uses

func (p StackParam) TryParse(dest interface{}) error

TryParse converts one StackParam into something more appropriate.

func (*StackParam) UnmarshalJSON Uses

func (p *StackParam) UnmarshalJSON(data []byte) (err error)

UnmarshalJSON implements Unmarshaler interface.

type StackParamType Uses

type StackParamType int

StackParamType represents different types of stack values.

const (
    Unknown          StackParamType = -1
    Signature        StackParamType = 0x00
    Boolean          StackParamType = 0x01
    Integer          StackParamType = 0x02
    Hash160          StackParamType = 0x03
    Hash256          StackParamType = 0x04
    ByteArray        StackParamType = 0x05
    PublicKey        StackParamType = 0x06
    String           StackParamType = 0x07
    Array            StackParamType = 0x10
    InteropInterface StackParamType = 0xf0
    Void             StackParamType = 0xff
)

All possible StackParamType values are listed here.

func StackParamTypeFromString Uses

func StackParamTypeFromString(s string) (StackParamType, error)

StackParamTypeFromString converts string into the StackParamType.

func (*StackParamType) MarshalJSON Uses

func (t *StackParamType) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (*StackParamType) MarshalYAML Uses

func (t *StackParamType) MarshalYAML() (interface{}, error)

MarshalYAML implements the YAML Marshaler interface.

func (StackParamType) String Uses

func (t StackParamType) String() string

String implements the stringer interface.

func (*StackParamType) UnmarshalJSON Uses

func (t *StackParamType) UnmarshalJSON(data []byte) (err error)

UnmarshalJSON sets StackParamType from JSON-encoded data.

func (*StackParamType) UnmarshalYAML Uses

func (t *StackParamType) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML implements the YAML Unmarshaler interface.

type StackParams Uses

type StackParams []StackParam

StackParams is an array of StackParam (TODO: drop it?).

func (StackParams) TryParseArray Uses

func (p StackParams) TryParseArray(vals ...interface{}) error

TryParseArray converts an array of StackParam into an array of more appropriate things.

type TxResponse Uses

type TxResponse struct {
    TxID       string                  `json:"txid"`
    Size       int                     `json:"size"`
    Type       string                  `json:"type"` // todo: convert to TransactionType
    Version    int                     `json:"version"`
    Attributes []transaction.Attribute `json:"attributes"`
    Vins       []Vin                   `json:"vin"`
    Vouts      []Vout                  `json:"vout"`
    SysFee     int                     `json:"sys_fee"`
    NetFee     int                     `json:"net_fee"`
    Scripts    []transaction.Witness   `json:"scripts"`
}

TxResponse stores transaction to be sent as a response.

type Unspent Uses

type Unspent struct {
    Unspent state.UnspentBalances
    Asset   string      // "NEO" / "GAS"
    Amount  util.Fixed8 // total unspent of this asset
}

Unspent stores Unspents per asset

type UnspentResponse Uses

type UnspentResponse struct {
    Error  *Error             `json:"error,omitempty"`
    Result *wrappers.Unspents `json:"result,omitempty"`
    // contains filtered or unexported fields
}

UnspentResponse represents server response to the `getunspents` command.

type Vin Uses

type Vin struct {
    TxID string `json:"txid"`
    Vout int    `json:"vout"`
}

Vin represents JSON-serializable tx input.

type Vout Uses

type Vout struct {
    N       int    `json:"n"`
    Asset   string `json:"asset"`
    Value   int    `json:"value"`
    Address string `json:"address"`
}

Vout represents JSON-serializable tx output.

Directories

PathSynopsis
result
wrappers

Package rpc imports 32 packages (graph). Updated 2020-01-23. Refresh now. Tools for package owners.