rpc

package
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Jun 22, 2022 License: Apache-2.0 Imports: 9 Imported by: 4

README

Go Chia RPC

Library for interacting with Chia RPC. Supports both HTTP and Websocket communications.

Usage

When creating a new client, chia configuration will automatically be read from CHIA_ROOT. If chia is installed for the same user go-chia-rpc is running as, the config should be automatically discovered if it is in the default location. If the config is in a non-standard location, ensure CHIA_ROOT environment variable is set to the same value that is used for chia-blockchain.

HTTP Mode

To use HTTP mode, create a new client and specify ConnectionModeHTTP:

package main

import (
	"github.com/chia-network/go-chia-libs/pkg/rpc"
)

func main() {
	client, err := rpc.NewClient(rpc.ConnectionModeHTTP)
	if err != nil {
		// error happened
	}
}
Websocket Mode

To use Websocket mode, specify ConnectionModeWebsocket when creating the client:

package main

import (
	"github.com/chia-network/go-chia-libs/pkg/rpc"
)

func main() {
	client, err := rpc.NewClient(rpc.ConnectionModeWebsocket)
	if err != nil {
		// error happened
	}
}

Websockets function asynchronously and as such, there are a few implementation differences compared to using the simpler HTTP request/response pattern. You must define a handler function to process responses received over the websocket connection, and you must also specifically subscribe to the events the handler should receive.

Handler Function

Handler functions must use the following signature: func handlerFunc(data *types.WebsocketResponse, err error). The function will be passed the data that was received from the websocket and an error.

Initializing a client, and defining and registering a handler function looks like the following:

package main

import (
	"log"
	"github.com/chia-network/go-chia-libs/pkg/rpc"
	"github.com/chia-network/go-chia-libs/pkg/types"
)

func main() {
	client, err := rpc.NewClient(rpc.ConnectionModeWebsocket)
	if err != nil {
		log.Fatalln(err.Error())
	}

	client.AddHandler(gotResponse)

	// Other application logic here
}

func gotResponse(data *types.WebsocketResponse, err error) {
	log.Printf("Received a `%s` command response\n", data.Command)
}

You may also use a blocking/synchronous handler function, if listening to websocket responses is all your main process is doing:

package main

import (
	"log"

	"github.com/chia-network/go-chia-libs/pkg/rpc"
	"github.com/chia-network/go-chia-libs/pkg/types"
)

func main() {
	client, err := rpc.NewClient(rpc.ConnectionModeWebsocket)
	if err != nil {
		log.Fatalln(err.Error())
	}

	client.ListenSync(gotResponse)

	// Other application logic here
}

func gotResponse(data *types.WebsocketResponse, err error) {
	log.Printf("Received a `%s` command response\n", data.Command)
}
Subscribing to Events

There are two helper functions to subscribe to events that come over the websocket.

client.SubscribeSelf() - Calling this method subscribes to response events for any requests made from this client

client.Subscribe(service) - Calling this method, with an appropriate service, subscribes to any events that chia may generate that are not necessarily in responses to requests made from this client (for instance, metrics events fire when relevant updates are available that may impact metrics services)

Get Transactions
HTTP Mode
client, err := rpc.NewClient(rpc.ConnectionModeHTTP)
if err != nil {
	log.Fatal(err)
}

transactions, _, err := client.WalletService.GetTransactions(
	&rpc.GetWalletTransactionsOptions{
		WalletID: 1,
	},
)
if err != nil {
	log.Fatal(err)
}

for _, transaction := range transactions.Transactions {
	log.Println(transaction.Name)
}
Websocket Mode
func main() {
	client, err := rpc.NewClient(rpc.ConnectionModeWebsocket)
	if err != nil {
		log.Fatalln(err.Error())
	}

	err = client.SubscribeSelf()
	if err != nil {
		log.Fatalln(err.Error())
	}

	client.AddHandler(gotResponse)

	client.WalletService.GetTransactions(
		&rpc.GetWalletTransactionsOptions{
			WalletID: 1,
		},
	)
}

func gotResponse(data *types.WebsocketResponse, err error) {
	log.Printf("Received a `%s` command response\n", data.Command)

	if data.Command == "get_transactions" {
		txns := &rpc.GetWalletTransactionsResponse{}
		err = json.Unmarshal(data.Data, txns)
		if err != nil {
			log.Fatalln(err.Error())
		}

		log.Printf("%+v", txns)
	}
}
Get Full Node Status
state, _, err := client.FullNodeService.GetBlockchainState()
if err != nil {
	log.Fatal(err)
}

log.Println(state.BlockchainState.Difficulty)
Get Estimated Network Space

Gets the estimated network space and formats it to a readable version using FormatBytes utility function

//import (
//    "log"
//
//    "github.com/chia-network/go-chia-libs/pkg/rpc"
//    "github.com/chia-network/go-chia-libs/pkg/util"
//)

state, _, err := client.FullNodeService.GetBlockchainState()
if err != nil {
	log.Fatal(err)
}

log.Println(util.FormatBytes(state.BlockchainState.Space))
Request Cache

When using HTTP mode, there is an optional request cache that can be enabled with a configurable cache duration. To use the cache, initialize the client with the rpc.WithCache() option like the following example:

client, err := rpc.NewClient(rpc.ConnectionModeHTTP, rpc.WithCache(60 * time.Second))
if err != nil {
	// error happened
}

This example sets the cache time to 60 seconds. Any identical requests within the 60 seconds will be served from the local cache rather than making another RPC call.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func WithBaseURL

func WithBaseURL(url *url.URL) rpcinterface.ClientOptionFunc

WithBaseURL sets the host for RPC requests

func WithCache

func WithCache(validTime time.Duration) rpcinterface.ClientOptionFunc

WithCache specify a duration http requests should be cached for If unset, cache will not be used

Types

type CatSpendOptions added in v0.0.4

type CatSpendOptions struct {
	WalletID uint32 `json:"wallet_id"`
	Amount   uint64 `json:"amount"`
	Address  string `json:"inner_address"`
	Fee      uint64 `json:"fee"`
}

CatSpendOptions represents the options for cat_spend

type CatSpendResponse added in v0.0.4

type CatSpendResponse struct {
	Success       bool                    `json:"success"`
	TransactionID string                  `json:"transaction_id"`
	Transaction   types.TransactionRecord `json:"transaction"`
}

CatSpendResponse represents the response from cat_spend

type Client

type Client struct {

	// Services for the different chia services
	FullNodeService  *FullNodeService
	WalletService    *WalletService
	HarvesterService *HarvesterService
	CrawlerService   *CrawlerService
	// contains filtered or unexported fields
}

Client is the RPC client

func NewClient

func NewClient(connectionMode ConnectionMode, options ...rpcinterface.ClientOptionFunc) (*Client, error)

NewClient returns a new RPC Client

func (*Client) AddDisconnectHandler

func (c *Client) AddDisconnectHandler(onDisconnect rpcinterface.DisconnectHandler)

AddDisconnectHandler the function to call when the client is disconnected

func (*Client) AddHandler

func (c *Client) AddHandler(handler rpcinterface.WebsocketResponseHandler) error

AddHandler adds a handler function to call when a message is received over the websocket This is expected to NOT be used in conjunction with ListenSync This will run in the background, and allow other things to happen in the foreground while ListenSync will take over the foreground process

func (*Client) Do

func (c *Client) Do(req *rpcinterface.Request, v interface{}) (*http.Response, error)

Do is a helper that wraps the activeClient's Do method

func (*Client) ListenSync

func (c *Client) ListenSync(handler rpcinterface.WebsocketResponseHandler) error

ListenSync Listens for async responses over the connection in a synchronous fashion, blocking anything else

func (*Client) NewRequest

func (c *Client) NewRequest(service rpcinterface.ServiceType, rpcEndpoint rpcinterface.Endpoint, opt interface{}) (*rpcinterface.Request, error)

NewRequest is a helper that wraps the activeClient's NewRequest method

func (*Client) Subscribe

func (c *Client) Subscribe(service string) error

Subscribe adds a subscription to events from a particular service This is currently only useful for websocket mode

func (*Client) SubscribeSelf

func (c *Client) SubscribeSelf() error

SubscribeSelf subscribes to responses to requests from this service This is currently only useful for websocket mode

type ConnectionMode

type ConnectionMode uint8

ConnectionMode specifies the method used to connect to the server (HTTP or Websocket)

const (
	// ConnectionModeHTTP uses HTTP for requests to the RPC server
	ConnectionModeHTTP ConnectionMode = iota

	// ConnectionModeWebsocket uses websockets for requests to the RPC server
	ConnectionModeWebsocket
)

type CrawlerService

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

CrawlerService encapsulates crawler RPC methods

func (*CrawlerService) Do

func (s *CrawlerService) Do(req *rpcinterface.Request, v interface{}) (*http.Response, error)

Do is just a shortcut to the client's Do method

func (*CrawlerService) GetIPsAfterTimestamp

GetIPsAfterTimestamp Returns IP addresses seen by the network after a particular timestamp

func (*CrawlerService) GetPeerCounts

func (s *CrawlerService) GetPeerCounts() (*GetPeerCountsResponse, *http.Response, error)

GetPeerCounts crawler rpc -> get_peer_counts

func (*CrawlerService) NewRequest

func (s *CrawlerService) NewRequest(rpcEndpoint rpcinterface.Endpoint, opt interface{}) (*rpcinterface.Request, error)

NewRequest returns a new request specific to the crawler service

type FullNodeService

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

FullNodeService encapsulates full node RPC methods

func (*FullNodeService) Do

func (s *FullNodeService) Do(req *rpcinterface.Request, v interface{}) (*http.Response, error)

Do is just a shortcut to the client's Do method

func (*FullNodeService) GetBlock

GetBlock full_node->get_block RPC method

func (*FullNodeService) GetBlockByHeight

GetBlockByHeight helper function to get a full block by height, calls full_node->get_block_record_by_height RPC method then full_node->get_block RPC method

func (*FullNodeService) GetBlockCountMetrics

func (s *FullNodeService) GetBlockCountMetrics() (*GetBlockCountMetricsResponse, *http.Response, error)

GetBlockCountMetrics gets metrics about blocks

func (*FullNodeService) GetBlockRecordByHeight

func (s *FullNodeService) GetBlockRecordByHeight(opts *GetBlockByHeightOptions) (*GetBlockRecordResponse, *http.Response, error)

GetBlockRecordByHeight full_node->get_block_record_by_height RPC method

func (*FullNodeService) GetBlockchainState

func (s *FullNodeService) GetBlockchainState() (*GetBlockchainStateResponse, *http.Response, error)

GetBlockchainState returns blockchain state

func (*FullNodeService) GetBlocks

GetBlocks full_node->get_blocks RPC method

func (*FullNodeService) GetConnections

GetConnections returns connections

func (*FullNodeService) NewRequest

func (s *FullNodeService) NewRequest(rpcEndpoint rpcinterface.Endpoint, opt interface{}) (*rpcinterface.Request, error)

NewRequest returns a new request specific to the wallet service

type GetBlockByHeightOptions

type GetBlockByHeightOptions struct {
	BlockHeight int `json:"height"`
}

GetBlockByHeightOptions options for get_block_record_by_height and get_block rpc call

type GetBlockCountMetricsResponse

type GetBlockCountMetricsResponse struct {
	Success bool                     `json:"success"`
	Metrics *types.BlockCountMetrics `json:"metrics"`
}

GetBlockCountMetricsResponse response for get_block_count_metrics rpc call

type GetBlockOptions

type GetBlockOptions struct {
	HeaderHash string `json:"header_hash"`
}

GetBlockOptions options for get_block rpc call

type GetBlockRecordResponse

type GetBlockRecordResponse struct {
	Success     bool               `json:"success"`
	BlockRecord *types.BlockRecord `json:"block_record"`
}

GetBlockRecordResponse response from get_block_record_by_height

type GetBlockResponse

type GetBlockResponse struct {
	Success bool             `json:"success"`
	Block   *types.FullBlock `json:"block"`
}

GetBlockResponse response for get_block rpc call

type GetBlockchainStateResponse

type GetBlockchainStateResponse struct {
	Success         bool                   `json:"success"`
	BlockchainState *types.BlockchainState `json:"blockchain_state"`
}

GetBlockchainStateResponse is the blockchain state RPC response

type GetBlocksOptions

type GetBlocksOptions struct {
	Start int `json:"start"`
	End   int `json:"end"`
}

GetBlocksOptions options for get_blocks rpc call

type GetBlocksResponse

type GetBlocksResponse struct {
	Success bool               `json:"success"`
	Blocks  []*types.FullBlock `json:"blocks"`
}

GetBlocksResponse response for get_blocks rpc call

type GetConnectionsOptions

type GetConnectionsOptions struct {
	NodeType types.NodeType `json:"node_type,omitempty"`
}

GetConnectionsOptions options to filter get_connections

type GetConnectionsResponse

type GetConnectionsResponse struct {
	Success     bool                `json:"success"`
	Connections []*types.Connection `json:"connections"`
}

GetConnectionsResponse get_connections response format

type GetIPsAfterTimestampOptions

type GetIPsAfterTimestampOptions struct {
	After  int64 `json:"after"`
	Offset uint  `json:"offset"`
	Limit  uint  `json:"limit"`
}

GetIPsAfterTimestampOptions Options for the get_ips_after_timestamp RPC call

type GetIPsAfterTimestampResponse

type GetIPsAfterTimestampResponse struct {
	Success bool     `json:"success"`
	IPs     []string `json:"ips"`
	Total   int      `json:"total"`
}

GetIPsAfterTimestampResponse Response for get_ips_after_timestamp

type GetPeerCountsResponse

type GetPeerCountsResponse struct {
	Success    bool                     `json:"success"`
	PeerCounts *types.CrawlerPeerCounts `json:"peer_counts"`
}

GetPeerCountsResponse Response for get_get_peer_counts on crawler

type GetWalletBalanceOptions

type GetWalletBalanceOptions struct {
	WalletID uint32 `json:"wallet_id"`
}

GetWalletBalanceOptions request options for get_wallet_balance

type GetWalletBalanceResponse

type GetWalletBalanceResponse struct {
	Success bool                 `json:"success"`
	Balance *types.WalletBalance `json:"wallet_balance"`
}

GetWalletBalanceResponse is the wallet balance RPC response

type GetWalletHeightInfoResponse

type GetWalletHeightInfoResponse struct {
	Success bool   `json:"success"`
	Height  uint32 `json:"height"`
}

GetWalletHeightInfoResponse response for get_height_info on wallet

type GetWalletNetworkInfoResponse

type GetWalletNetworkInfoResponse struct {
	Success       bool   `json:"success"`
	NetworkName   string `json:"network_name"`
	NetworkPrefix string `json:"network_prefix"`
}

GetWalletNetworkInfoResponse response for get_height_info on wallet

type GetWalletSyncStatusResponse

type GetWalletSyncStatusResponse struct {
	Success            bool `json:"success"`
	GenesisInitialized bool `json:"genesis_initialized"`
	Synced             bool `json:"synced"`
	Syncing            bool `json:"syncing"`
}

GetWalletSyncStatusResponse Response for get_sync_status on wallet

type GetWalletTransactionCountOptions

type GetWalletTransactionCountOptions struct {
	WalletID uint32 `json:"wallet_id"`
}

GetWalletTransactionCountOptions options for get transaction count

type GetWalletTransactionCountResponse

type GetWalletTransactionCountResponse struct {
	Success  bool   `json:"success"`
	WalletID uint32 `json:"wallet_id"`
	Count    int    `json:"count"`
}

GetWalletTransactionCountResponse response for get_transaction_count

type GetWalletTransactionOptions

type GetWalletTransactionOptions struct {
	WalletID      uint32 `json:"wallet_id"`
	TransactionID string `json:"transaction_id"`
}

GetWalletTransactionOptions options for getting a single wallet transaction

type GetWalletTransactionResponse

type GetWalletTransactionResponse struct {
	Success       bool                     `json:"success"`
	Transaction   *types.TransactionRecord `json:"transaction"`
	TransactionID string                   `json:"transaction_id"`
}

GetWalletTransactionResponse response for get_wallet_transactions

type GetWalletTransactionsOptions

type GetWalletTransactionsOptions struct {
	WalletID  uint32 `json:"wallet_id"`
	Start     *int   `json:"start,omitempty"`
	End       *int   `json:"end,omitempty"`
	ToAddress string `json:"to_address,omitempty"`
}

GetWalletTransactionsOptions options for get wallet transactions

type GetWalletTransactionsResponse

type GetWalletTransactionsResponse struct {
	Success      bool                       `json:"success"`
	WalletID     uint32                     `json:"wallet_id"`
	Transactions []*types.TransactionRecord `json:"transactions"`
}

GetWalletTransactionsResponse response for get_wallet_transactions

type GetWalletsResponse

type GetWalletsResponse struct {
	Success bool                `json:"success"`
	Wallets []*types.WalletInfo `json:"wallets"`
}

GetWalletsResponse wallet rpc -> get_wallets

type HarvesterGetPlotsResponse added in v0.0.6

type HarvesterGetPlotsResponse struct {
	Success               bool              `json:"success"`
	Plots                 []*types.PlotInfo `json:"plots"`
	FailedToOpenFilenames []string          `json:"failed_to_open_filenames"`
	NotFoundFilenames     []string          `json:"not_found_filenames"`
}

HarvesterGetPlotsResponse get_plots response format

type HarvesterService added in v0.0.6

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

HarvesterService encapsulates harvester RPC methods

func (*HarvesterService) Do added in v0.0.6

func (s *HarvesterService) Do(req *rpcinterface.Request, v interface{}) (*http.Response, error)

Do is just a shortcut to the client's Do method

func (*HarvesterService) GetPlots added in v0.0.6

GetPlots returns connections

func (*HarvesterService) NewRequest added in v0.0.6

func (s *HarvesterService) NewRequest(rpcEndpoint rpcinterface.Endpoint, opt interface{}) (*rpcinterface.Request, error)

NewRequest returns a new request specific to the wallet service

type SendTransactionOptions

type SendTransactionOptions struct {
	WalletID uint32 `json:"wallet_id"`
	Amount   uint64 `json:"amount"`
	Address  string `json:"address"`
	Fee      uint64 `json:"fee"`
}

SendTransactionOptions represents the options for send_transaction

type SendTransactionResponse

type SendTransactionResponse struct {
	Success       bool                    `json:"success"`
	TransactionID string                  `json:"transaction_id"`
	Transaction   types.TransactionRecord `json:"transaction"`
}

SendTransactionResponse represents the response from send_transaction

type WalletService

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

WalletService encapsulates wallet RPC methods

func (*WalletService) CatSpend added in v0.0.4

CatSpend sends a transaction

func (*WalletService) Do

func (s *WalletService) Do(req *rpcinterface.Request, v interface{}) (*http.Response, error)

Do is just a shortcut to the client's Do method

func (*WalletService) GetHeightInfo

func (s *WalletService) GetHeightInfo() (*GetWalletHeightInfoResponse, *http.Response, error)

GetHeightInfo wallet rpc -> get_height_info

func (*WalletService) GetNetworkInfo

func (s *WalletService) GetNetworkInfo() (*GetWalletNetworkInfoResponse, *http.Response, error)

GetNetworkInfo wallet rpc -> get_network_info

func (*WalletService) GetSyncStatus

func (s *WalletService) GetSyncStatus() (*GetWalletSyncStatusResponse, *http.Response, error)

GetSyncStatus wallet rpc -> get_sync_status

func (*WalletService) GetTransaction

GetTransaction returns a single transaction record

func (*WalletService) GetTransactionCount

GetTransactionCount returns the total count of transactions for the specific wallet ID

func (*WalletService) GetTransactions

GetTransactions wallet rpc -> get_transactions

func (*WalletService) GetWalletBalance

GetWalletBalance returns wallet balance

func (*WalletService) GetWallets

func (s *WalletService) GetWallets() (*GetWalletsResponse, *http.Response, error)

GetWallets wallet rpc -> get_wallets

func (*WalletService) NewRequest

func (s *WalletService) NewRequest(rpcEndpoint rpcinterface.Endpoint, opt interface{}) (*rpcinterface.Request, error)

NewRequest returns a new request specific to the wallet service

func (*WalletService) SendTransaction

SendTransaction sends a transaction

Jump to

Keyboard shortcuts

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