rpc

package
v0.5.0-pre Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 26, 2019 License: MIT Imports: 27 Imported by: 0

README

RPC

What

  • Structs used by JSON-RPC server and for interacting with a JSON-RPC endpoint.
  • Server for running the JSON-RPC protocol based on port in configuration.

This package is currently in alpha and is subject to change.

Reference

Client

You can create a new client and start interacting with any NEO node that exposes their JSON-RPC endpoint. See godocs for example.

Not all methods are currently supported in the client, please see table below for supported methods.

TODO
  • Merge structs so can be used by both server and client.
  • Add missing methods to client.
  • Allow client to connect using client cert.
Supported methods
Method Implemented Required to implement
getblock Yes -
getaccountstate Yes -
invokescript Yes -
invokefunction Yes -
sendrawtransaction Yes -
invoke Yes -
getrawtransaction Yes -
validateaddress No Handler and result struct
getblocksysfee No Handler and result struct
getcontractstate No Handler and result struct
getrawmempool No Handler and result struct
getstorage No Handler and result struct
submitblock No Handler and result struct
gettxout No Handler and result struct
getassetstate No Handler and result struct
getpeers No Handler and result struct
getversion No Handler and result struct
getconnectioncount No Handler and result struct
getblockhash No Handler and result struct
getblockcount No Handler and result struct
getbestblockhash No Handler and result struct

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
    }
}
Supported methods
Method Implemented Required to implement
getblock Yes -
getaccountstate Yes -
invokescript No VM
invokefunction No VM
sendrawtransaction No Needs to be implemented in pkg/core/blockchain.go
validateaddress Yes -
getblocksysfee No N/A
getcontractstate No Needs to be implemented in pkg/core/blockchain.go
getrawmempool No Needs to be implemented on in pkg/network/server.go
getrawtransaction No Needs to be implemented in pkg/core/blockchain.go
getstorage No VM
submitblock No Needs to be implemented in pkg/core/blockchain.go
gettxout No Needs to be implemented in pkg/core/blockchain.go
invoke No VM
getassetstate Yes -
getpeers Yes -
getversion Yes -
getconnectioncount Yes -
getblockhash Yes -
getblockcount Yes -
getbestblockhash Yes -

Documentation

Index

Constants

This section is empty.

Variables

View Source
var GlobalAssets = map[string]string{
	"c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b": "NEO",
	"602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7": "GAS",
}

NeoScan returns asset IDs as strings ("NEO"/"GAS"); strings might be converted to uint256 assets IDs using this map

Functions

func CreateRawContractTransaction

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

func GetInvocationScript

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

Types

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

Account represents details about a NEO account.

type AccountStateResponse

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

AccountStateResponse holds the getaccountstate response.

type Balance

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

Balance represents details about a NEO account balance.

type BalanceGetter

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

type Client

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

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

func NewClient

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

NewClient return a new Client ready to use.

func (*Client) Balancer

func (c *Client) Balancer() BalanceGetter

func (*Client) Client

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

func (*Client) GetAccountState

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

GetAccountState will return detailed information about a NEO account.

func (*Client) GetBlock

func (c *Client) GetBlock(indexOrHash interface{}, verbose bool) (*response, error)

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 (*Client) GetRawTransaction

func (c *Client) GetRawTransaction(hash string, verbose bool) (*response, error)

GetRawTransaction queries a transaction by hash.

func (*Client) Invoke

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

InvokeFunction return the results after calling a the smart contract scripthash with the given parameters.

func (*Client) InvokeFunction

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

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

func (*Client) InvokeScript

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

func (c *Client) Ping() error

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

func (*Client) SendRawTransaction

func (c *Client) SendRawTransaction(rawTX string) (*response, error)

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 (*Client) SendToAddress

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

func (c *Client) SetBalancer(b BalanceGetter)

func (*Client) SetClient

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

func (*Client) SetWIF

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) WIF

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

type ClientOptions

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 ContractTxParams

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

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

type Error

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

func NewInternalServerError(data string, cause error) *Error

NewInternalServerError creates a new error with code -32603.

func NewInvalidParamsError

func NewInvalidParamsError(data string, cause error) *Error

NewInvalidParamsError creates a new error with code -32602.

func NewInvalidRequestError

func NewInvalidRequestError(data string, cause error) *Error

NewInvalidRequestError creates a new error with code -32600.

func NewMethodNotFoundError

func NewMethodNotFoundError(data string, cause error) *Error

NewMethodNotFoundError creates a new error with code -32601.

func NewParseError

func NewParseError(data string, cause error) *Error

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

func (Error) Error

func (e Error) Error() string

Error implements the error interface.

type GetRawTxResponse

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

struct represents verbose output of `getrawtransaction` RPC call

type InvokeResult

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

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

type NeoScanBalance

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

struct of NeoScan response to 'get_balance' request

type NeoScanServer

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

func (NeoScanServer) CalculateInputs

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

func (NeoScanServer) GetBalance

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

type Param

type Param struct {
	StringVal string
	IntVal    int
	Type      string
	RawValue  interface{}
}

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

func (Param) String

func (p Param) String() string

type Params

type Params []Param

Params represent the JSON-RPC params.

func (*Params) UnmarshalJSON

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

UnmarshalJSON implements the Unmarshaller interface.

func (Params) Value

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

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

func (Params) ValueAt

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

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

func (Params) ValueAtAndType

func (p Params) ValueAtAndType(index int, valueType string) (*Param, bool)

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

func (Params) ValueWithType

func (p Params) ValueWithType(index int, valType string) (*Param, error)

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

type RawTxResponse

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

type Request

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

func NewRequest() *Request

NewRequest creates a new Request struct.

func (*Request) DecodeData

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

DecodeData decodes the given reader into the the request struct.

func (*Request) Params

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

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

func (Request) WriteErrorResponse

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

WriteErrorResponse writes an error response to the ResponseWriter.

func (Request) WriteResponse

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

WriteResponse encodes the response and writes it to the ResponseWriter.

type Response

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

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

type Server

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

Server represents the JSON-RPC 2.0 server.

func NewServer

func NewServer(chain core.Blockchainer, port uint16, coreServer *network.Server) Server

NewServer creates a new Server struct.

func (*Server) Shutdown

func (s *Server) Shutdown() error

Shutdown override the http.Server Shutdown method.

func (*Server) Start

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

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

type StackParam

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

StackParam represent a stack parameter.

func (StackParam) TryParse

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

func (*StackParam) UnmarshalJSON

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

UnmarshalJSON implements Unmarshaler interface

type StackParamType

type StackParamType int
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
)

func StackParamTypeFromString

func StackParamTypeFromString(s string) (StackParamType, error)

func (StackParamType) String

func (t StackParamType) String() string

func (*StackParamType) UnmarshalJSON

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

type StackParams

type StackParams []StackParam

func (StackParams) TryParseArray

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

type TxResponse

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

type UTXO

type UTXO struct {
	Value util.Fixed8
	TxID  util.Uint256
	N     uint16
}

type Unspent

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

unspent per asset

type Unspents

type Unspents []UTXO

func (Unspents) Len

func (us Unspents) Len() int

functions for sorting array of `Unspents`

func (Unspents) Less

func (us Unspents) Less(i, j int) bool

func (Unspents) Swap

func (us Unspents) Swap(i, j int)

type Vin

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

type Vout

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL