rpc

package
v1.1.3 Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2023 License: Apache-2.0 Imports: 11 Imported by: 2

README

RPC

Package rpc provides access to the exported methods of RPC Client and data structures where serialized response.

The Client implements RPC methods according to spec. Client unites implementation of ClientInformational interface related to spec and ClientPOS interface related to spec.

Usage

The configuration is flexible, and caller can provide custom configurations, the most common usage is to create NewClient which depends on Handler interface.

    handler := rpc.NewHttpHandler("<<NODE_RPC_API_URL>>", http.DefaultClient)
    client := rpc.NewClient(handler)
    deployResult, err := client.GetDeploy(context.Background(), deployHash)

For more examples check the examples

Architecture

Client interface unites ClientInformational and ClientPOS interfaces.

The motivation for separating interfaces correlates with requirements from specification. Following this document, the different clients have different responsibilities, which could mean different patterns of usage.

client struct that implements interface Client depends on Handler

The motivation for separating this logic is splitting responsibilities.

In this case, client knows nothing about the underlying network protocol used for communication with a remote server. It is responsible to builds RpcRequest corresponding to function name and params and serializes RpcResponse to the corresponding data structures.

From the other side, the httpHandler that implements interface Handler takes on responsibilities to operate with an external RPC server through HTTP. It builds and processes the request, reads a response and handles errors. All logic with HTTP interaction is isolated here and can be replaced with other (more efficient) protocols.

Same time it knows nothing about ended data structure in which should be serialized RpcResponse.Result and don't care how to parameters for the RpcRequest were built. The interface supposes to use the Handler wider (not bounded by Client implementation).

In the summary, the separating of interfaces supposes to extend current functionality without code modification. For examples of how to do it check the examples

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrParamsUnmarshalHandler  = errors.New("failed to marshal rpc request's params")
	ErrBuildHttpRequestHandler = errors.New("failed to build http request")
	ErrProcessHttpRequest      = errors.New("failed to sent http request")
	ErrReadHttpResponseBody    = errors.New("failed to read http response body")
	ErrRpcResponseUnmarshal    = errors.New("failed to unmarshal rpc response")
)
View Source
var ApiVersion = "2.0"
View Source
var ErrResultUnmarshal = errors.New("failed to unmarshal rpc result")

Functions

func GetReqIdCtx

func GetReqIdCtx(ctx context.Context) int

func NewParamStateDictionaryItem

func NewParamStateDictionaryItem(stateRootHash, uref, key string) map[string]interface{}

func WithRequestId

func WithRequestId(ctx context.Context, requestID int) context.Context

Types

type ActivationPoint

type ActivationPoint struct {
	EraID     uint32    `json:"era_id"`
	Timestamp time.Time `json:"timestamp"`
}

ActivationPoint is the first era to which the associated protocol version applies.

type BlockIdentifier

type BlockIdentifier struct {
	Hash   string `json:"Hash,omitempty"`
	Height uint64 `json:"Height,omitempty"`
}

type ChainGetBlockResult

type ChainGetBlockResult struct {
	Version string      `json:"version"`
	Block   types.Block `json:"block"`
}

type ChainGetBlockTransfersResult

type ChainGetBlockTransfersResult struct {
	Version   string           `json:"api_version"`
	BlockHash string           `json:"block_hash"`
	Transfers []types.Transfer `json:"transfers"`
}

type ChainGetEraInfoResult

type ChainGetEraInfoResult struct {
	Version    string           `json:"api_version"`
	EraSummary types.EraSummary `json:"era_summary"`
}

type ChainGetEraSummaryResult added in v1.0.0

type ChainGetEraSummaryResult struct {
	Version    string           `json:"api_version"`
	EraSummary types.EraSummary `json:"era_summary"`
}

type ChainGetStateRootHashResult

type ChainGetStateRootHashResult struct {
	Version       string   `json:"api_version"`
	StateRootHash key.Hash `json:"state_root_hash"`
}

type Client

Client interface represent full RPC client that includes all possible queries.

func NewClient

func NewClient(handler Handler) Client

NewClient is a constructor for client that suppose to configure Handler examples of usage can be found here [Test_ConfigurableClient_GetDeploy]

type ClientInformational

type ClientInformational interface {
	// GetAccountBalance returns a purse's balance from a network.
	// The request takes in the formatted representation of a purse URef as a parameter.
	// If the param stateRootHash is nil, the client will make an additional RPC call to retrieve the latest stateRootHash.
	GetAccountBalance(ctx context.Context, stateRootHash *string, purseURef string) (StateGetBalanceResult, error)
	// GetDeploy retrieves a Deploy from a network. It requires a deploy_hash to query the Deploy.
	GetDeploy(ctx context.Context, hash string) (InfoGetDeployResult, error)
	// GetDictionaryItem returns an item from a Dictionary.
	// Every dictionary has a seed URef, findable by using a dictionary_identifier.
	// The address of a stored value is the blake2b hash of the seed URef and the byte representation of the dictionary key.
	// If the param stateRootHash is nil, the client will make an additional RPC call to retrieve the latest stateRootHash.
	GetDictionaryItem(ctx context.Context, stateRootHash *string, uref, key string) (StateGetDictionaryResult, error)
	// GetStateItem allows to get item from the global state
	// If the param stateRootHash is nil, the client will make an additional RPC call to retrieve the latest stateRootHash.
	// Deprecated: use QueryGlobalStateByStateHash instead
	GetStateItem(ctx context.Context, stateRootHash *string, key string, path []string) (StateGetItemResult, error)

	// QueryGlobalStateByBlockHash allows for you to query for a value stored under certain keys in global state.
	QueryGlobalStateByBlockHash(ctx context.Context, blockHash, key string, path []string) (QueryGlobalStateResult, error)
	// QueryGlobalStateByStateHash allows for you to query for a value stored under certain keys in global state.
	// If the param stateRootHash is nil, the client will make an additional RPC call to retrieve the latest stateRootHash.
	QueryGlobalStateByStateHash(ctx context.Context, stateRootHash *string, key string, path []string) (QueryGlobalStateResult, error)

	// GetAccountInfoByBlochHash returns a JSON representation of an Account from the network.
	// The blockHash must refer to a  Block after the Account's creation, or the method will return an empty response.
	GetAccountInfoByBlochHash(ctx context.Context, blockHash string, pub keypair.PublicKey) (StateGetAccountInfo, error)
	// GetAccountInfoByBlochHeight returns a JSON representation of an Account from the network.
	// The blockHeight must refer to a Block after the Account's creation, or the method will return an empty response.
	GetAccountInfoByBlochHeight(ctx context.Context, blockHeight uint64, pub keypair.PublicKey) (StateGetAccountInfo, error)

	// GetBlockLatest returns the latest types.Block from the network.
	GetBlockLatest(ctx context.Context) (ChainGetBlockResult, error)
	// GetBlockByHash returns the types.Block from the network the requested block hash.
	GetBlockByHash(ctx context.Context, hash string) (ChainGetBlockResult, error)
	// GetBlockByHeight returns the types.Block from the network the requested block height.
	GetBlockByHeight(ctx context.Context, height uint64) (ChainGetBlockResult, error)

	// GetBlockTransfersLatest returns all native transfers within a lasted Block from a network.
	GetBlockTransfersLatest(ctx context.Context) (ChainGetBlockTransfersResult, error)
	// GetBlockTransfersByHash returns all native transfers within a given Block from a network the requested block hash.
	GetBlockTransfersByHash(ctx context.Context, blockHash string) (ChainGetBlockTransfersResult, error)
	// GetBlockTransfersByHeight returns all native transfers within a given Block from a network the requested block height.
	GetBlockTransfersByHeight(ctx context.Context, height uint64) (ChainGetBlockTransfersResult, error)

	// GetEraSummaryLatest returns the era summary at a latest Block.
	GetEraSummaryLatest(ctx context.Context) (ChainGetEraSummaryResult, error)
	// GetEraSummaryByHash returns the era summary at a Block by hash.
	GetEraSummaryByHash(ctx context.Context, blockHash string) (ChainGetEraSummaryResult, error)
	// GetEraSummaryByHeight returns the era summary at a Block by height.
	GetEraSummaryByHeight(ctx context.Context, height uint64) (ChainGetEraSummaryResult, error)

	// GetStateRootHashLatest returns a state root hash of the latest Block.
	GetStateRootHashLatest(ctx context.Context) (ChainGetStateRootHashResult, error)
	// GetStateRootHashByHash returns a state root hash of the latest Block the requested block hash.
	GetStateRootHashByHash(ctx context.Context, blockHash string) (ChainGetStateRootHashResult, error)
	// GetStateRootHashByHeight returns a state root hash of the latest Block the requested block height.
	GetStateRootHashByHeight(ctx context.Context, height uint64) (ChainGetStateRootHashResult, error)

	// GetStatus return the current status of a node on a Casper network.
	// The responses return information specific to the queried node, and as such, will vary.
	GetStatus(ctx context.Context) (InfoGetStatusResult, error)
	// GetPeers return a list of peers connected to the node on a Casper network.
	// The responses return information specific to the queried node, and as such, will vary.
	GetPeers(ctx context.Context) (InfoGetPeerResult, error)
}

ClientInformational contains methods that return information from a node on a Casper network. The response should be identical, regardless of the node queried, as the information in question is objective and common to all nodes within a network.

type ClientPOS

type ClientPOS interface {
	// GetAuctionInfoLatest returns the types.ValidatorBid and types.EraValidators from the most recent Block.
	GetAuctionInfoLatest(ctx context.Context) (StateGetAuctionInfoResult, error)
	// GetAuctionInfoByHash returns the types.ValidatorBid and types.EraValidators of either a specific Block by hash
	GetAuctionInfoByHash(ctx context.Context, blockHash string) (StateGetAuctionInfoResult, error)
	// GetAuctionInfoByHeight returns the types.ValidatorBid and types.EraValidators of either a specific Block by height
	GetAuctionInfoByHeight(ctx context.Context, height uint64) (StateGetAuctionInfoResult, error)

	// GetEraInfoLatest returns an EraInfo from the network.
	// Only the last Block in an era, known as a switch block, will contain an era_summary.
	// This method return information about the latest block in the chain, it may not be the last block in the era.
	GetEraInfoLatest(ctx context.Context) (ChainGetEraInfoResult, error)
	// GetEraInfoByBlockHeight returns an EraInfo from the network.
	// Only the last Block in an era, known as a switch block, will contain an era_summary.
	// Querying by block height.
	GetEraInfoByBlockHeight(ctx context.Context, height uint64) (ChainGetEraInfoResult, error)
	// GetEraInfoByBlockHash returns an EraInfo from the network.
	// Only the last Block in an era, known as a switch block, will contain an era_summary.
	// Querying by block hash.
	GetEraInfoByBlockHash(ctx context.Context, hash string) (ChainGetEraInfoResult, error)

	// GetValidatorChangesInfo returns status changes of active validators. Listed changes occurred during the EraId
	// contained within the response itself. A validator may show more than one change in a single era.
	GetValidatorChangesInfo(ctx context.Context) (InfoGetValidatorChangesResult, error)
}

ClientPOS contains methods pertain to the Proof-of-Stake functionality of a Casper network. They return information related to auctions, bids and validators. This information is necessary for users involved with node operations and validation.

type ClientTransactional

type ClientTransactional interface {
	PutDeploy(ctx context.Context, deploy types.Deploy) (PutDeployResult, error)
}

ClientTransactional contains the description of account_put_deploy, the only means by which users can send their compiled Wasm (as part of a Deploy) to a node on a Casper network.

type CtxRequestID

type CtxRequestID string
const RequestIDKey CtxRequestID = "RequestID"

type Handler

type Handler interface {
	ProcessCall(ctx context.Context, params RpcRequest) (RpcResponse, error)
}

Handler is responsible to implement interaction with underlying protocol.

func NewHttpHandler

func NewHttpHandler(endpoint string, client *http.Client) Handler

NewHttpHandler is a constructor for httpHandler that suppose to configure http.Client examples of usage can be found here [Test_ConfigurableClient_GetDeploy]

type HttpError

type HttpError struct {
	SourceErr  error
	StatusCode int
}

func (*HttpError) Error

func (h *HttpError) Error() string

func (*HttpError) IsNotFound

func (h *HttpError) IsNotFound() bool

func (*HttpError) Unwrap

func (h *HttpError) Unwrap() error

type InfoGetDeployResult

type InfoGetDeployResult struct {
	ApiVersion       string                        `json:"api_version"`
	Deploy           types.Deploy                  `json:"deploy"`
	ExecutionResults []types.DeployExecutionResult `json:"execution_results"`
}

type InfoGetPeerResult

type InfoGetPeerResult struct {
	ApiVersion string     `json:"api_version"`
	Peers      []NodePeer `json:"peers"`
}

type InfoGetStatusResult

type InfoGetStatusResult struct {
	// The RPC API version.
	APIVersion string `json:"api_version"`
	// The compiled node version.
	BuildVersion string `json:"build_version"`
	// The chainspec name, used to identify the currently connected network.
	ChainSpecName string `json:"chainspec_name"`
	// The minimal info of the last block from the linear chain.
	LastAddedBlockInfo types.MinimalBlockInfo `json:"last_added_block_info"`
	// Information about the next scheduled upgrade.
	NextUpgrade NodeNextUpgrade `json:"next_upgrade,omitempty"`
	// Node public signing key.
	OutPublicSigningKey string `json:"our_public_signing_key"`
	// The list of node ID and network address of each connected peer.
	Peers []NodePeer `json:"peers"`
	// The next round length if this node is a validator.
	RoundLength string `json:"round_length"`
	// The state root hash used at the start of the current session.
	StartingStateRootHash string `json:"starting_state_root_hash"`
	// Time that passed since the node has started. format "2months 20days 22h 3m 21s 512ms"
	Uptime string `json:"uptime"`
}

type InfoGetValidatorChangesResult added in v1.0.0

type InfoGetValidatorChangesResult struct {
	APIVersion string             `json:"api_version"`
	Changes    []ValidatorChanges `json:"changes"`
}

type Method

type Method string

Method is represented a name of the RPC endpoint

const (
	MethodGetDeploy           Method = "info_get_deploy"
	MethodGetStateItem        Method = "state_get_item"
	MethodQueryGlobalState    Method = "query_global_state"
	MethodGetDictionaryItem   Method = "state_get_dictionary_item"
	MethodGetStateBalance     Method = "state_get_balance"
	MethodGetStateAccount     Method = "state_get_account_info"
	MethodGetEraInfo          Method = "chain_get_era_info_by_switch_block"
	MethodGetBlock            Method = "chain_get_block"
	MethodGetBlockTransfers   Method = "chain_get_block_transfers"
	MethodGetEraSummary       Method = "chain_get_era_summary"
	MethodGetAuctionInfo      Method = "state_get_auction_info"
	MethodGetValidatorChanges Method = "info_get_validator_changes"
	MethodGetStateRootHash    Method = "chain_get_state_root_hash"
	MethodGetStatus           Method = "info_get_status"
	MethodGetPeers            Method = "info_get_peers"
	MethodPutDeploy           Method = "account_put_deploy"
)

type NodeNextUpgrade

type NodeNextUpgrade struct {
	//The first era to which the associated protocol version applies.
	ActivationPoint ActivationPoint `json:"activation_point"`
	// The protocol version of the next upgrade
	ProtocolVersion string `json:"protocol_version"`
}

NodeNextUpgrade contains the information about the next protocol upgrade.

type NodePeer

type NodePeer struct {
	NodeID  string `json:"node_id"`
	Address string `json:"address"`
}

type ParamBlockIdentifier

type ParamBlockIdentifier struct {
	BlockIdentifier BlockIdentifier `json:"block_identifier"`
}

func NewParamBlockByHash

func NewParamBlockByHash(hash string) ParamBlockIdentifier

func NewParamBlockByHeight

func NewParamBlockByHeight(height uint64) ParamBlockIdentifier

type ParamGetAccountInfoBalance added in v1.1.1

type ParamGetAccountInfoBalance struct {
	PublicKey keypair.PublicKey `json:"public_key"`
	ParamBlockIdentifier
}

type ParamQueryGlobalState added in v1.1.1

type ParamQueryGlobalState struct {
	StateIdentifier ParamQueryGlobalStateID `json:"state_identifier"`
	Key             string                  `json:"key"`
	Path            []string                `json:"path,omitempty"`
}

func NewQueryGlobalStateParam added in v1.0.0

func NewQueryGlobalStateParam(key string, path []string, id ParamQueryGlobalStateID) ParamQueryGlobalState

type ParamQueryGlobalStateID added in v1.0.0

type ParamQueryGlobalStateID struct {
	StateRootHash string `json:"StateRootHash,omitempty"`
	BlockHash     string `json:"BlockHash,omitempty"`
}

type ParamStateRootHash

type ParamStateRootHash struct {
	StateRootHash string   `json:"state_root_hash"`
	Key           string   `json:"key"`
	Path          []string `json:"path,omitempty"`
}

type PutDeployRequest

type PutDeployRequest struct {
	Deploy types.Deploy `json:"deploy"`
}

type PutDeployResult

type PutDeployResult struct {
	ApiVersion string   `json:"api_version"`
	DeployHash key.Hash `json:"deploy_hash"`
}

type QueryGlobalStateResult added in v1.0.0

type QueryGlobalStateResult struct {
	ApiVersion  string            `json:"api_version"`
	BlockHeader types.BlockHeader `json:"block_header,omitempty"`
	StoredValue types.StoredValue `json:"stored_value"`
	//MerkleProof is a construction created using a merkle trie that allows verification of the associated hashes.
	MerkleProof json.RawMessage `json:"merkle_proof"`
}

type RpcError

type RpcError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

func (*RpcError) Error

func (h *RpcError) Error() string

type RpcRequest

type RpcRequest struct {
	// Version of the RPC protocol in use
	Version string `json:"jsonrpc"`
	// Id of the RPC request that can be correlated with the equivalent Id in the RPC response
	//TODO: ID doesn't work from the Node side (always return 1 in response)
	ID     int         `json:"id"`
	Method Method      `json:"method"`
	Params interface{} `json:"params"`
}

RpcRequest is a wrapper struct for an RPC call method that can be serialized to JSON.

func DefaultRpcRequest

func DefaultRpcRequest(method Method, params interface{}) RpcRequest

type RpcResponse

type RpcResponse struct {
	Version string          `json:"jsonrpc"`
	Id      int             `json:"id"`
	Result  json.RawMessage `json:"result"`
	Error   *RpcError       `json:"error,omitempty"`
}

RpcResponse is a wrapper struct for an RPC Response. For a successful response the Result property contains the returned data as a JSON object. If an error occurs Error property contains a description of an error.

type StateGetAccountInfo added in v1.0.0

type StateGetAccountInfo struct {
	ApiVersion string        `json:"api_version"`
	Account    types.Account `json:"account"`
}

type StateGetAuctionInfoResult

type StateGetAuctionInfoResult struct {
	Version      string             `json:"api_version"`
	AuctionState types.AuctionState `json:"auction_state"`
}

type StateGetBalanceResult

type StateGetBalanceResult struct {
	ApiVersion   string `json:"api_version"`
	BalanceValue uint64 `json:"balance_value,string"`
}

type StateGetDictionaryResult added in v1.0.0

type StateGetDictionaryResult struct {
	ApiVersion    string            `json:"api_version"`
	DictionaryKey string            `json:"dictionary_key"`
	StoredValue   types.StoredValue `json:"stored_value"`
	MerkleProof   json.RawMessage   `json:"merkle_proof"`
}

type StateGetItemResult

type StateGetItemResult struct {
	StoredValue types.StoredValue `json:"stored_value"`
	//MerkleProof is a construction created using a merkle trie that allows verification of the associated hashes.
	MerkleProof json.RawMessage `json:"merkle_proof"`
}

type StatusChanges added in v1.0.0

type StatusChanges struct {
	EraID          uint64         `json:"era_id"`
	ValidatorState ValidatorState `json:"validator_change"`
}

type ValidatorChanges added in v1.0.0

type ValidatorChanges struct {
	PublicKey     keypair.PublicKey `json:"public_key"`
	StatusChanges []StatusChanges   `json:"status_changes"`
}

type ValidatorState added in v1.0.0

type ValidatorState string
const (
	// ValidatorStateAdded means that the validator has been added to the set.
	ValidatorStateAdded ValidatorState = "Added"
	// ValidatorStateRemoved means that the validator has been removed from the set.
	ValidatorStateRemoved ValidatorState = "Removed"
	// ValidatorStateBanned means that the validator has been banned in the current era.
	ValidatorStateBanned ValidatorState = "Banned"
	// ValidatorStateCannotPropose means that the validator cannot propose a Block.
	ValidatorStateCannotPropose ValidatorState = "CannotPropose"
	// ValidatorStateSeenAsFaulty means that the validator has performed questionable activity.
	ValidatorStateSeenAsFaulty ValidatorState = "SeenAsFaulty"
)

Jump to

Keyboard shortcuts

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