rpcclient

package
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2018 License: ISC Imports: 21 Imported by: 1

Documentation

Overview

Package rpcclient provides an easy to use client for interfacing with an electrum wallet that runs a JSON-RPC daemon Based on https://github.com/btcsuite/btcd/tree/master/rpcclient

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrClientShutdown is an error to describe the condition where the
	// client is either already shutdown, or in the process of shutting
	// down.  Any outstanding futures when a client shutdown occurs will
	// return this error as will any new requests.
	ErrClientShutdown = errors.New("the client has been shutdown")
)

Functions

func CmdMethod

func CmdMethod(cmd interface{}) (method string, named bool, err error)

CmdMethod returns the method for the passed command. The provided command type must be a registered type. All commands provided by this package are registered by default.

func DisableLog

func DisableLog()

DisableLog disables all library log output. Logging output is disabled by default until UseLogger is called.

func IsValidIDType

func IsValidIDType(id interface{}) bool

IsValidIDType checks that the ID field (which can go in any of the JSON-RPC requests, responses, or notifications) is valid. JSON-RPC 1.0 allows any valid JSON type. JSON-RPC 2.0 (which bitcoind follows for some parts) only allows string, number, or null, so this function restricts the allowed types to that list. This function is only provided in case the caller is manually marshalling for some reason. The functions which accept an ID in this package already call this function to ensure the provided id is valid.

func MarshalCmd

func MarshalCmd(id interface{}, cmd interface{}) ([]byte, error)

MarshalCmd marshals the passed command to a JSON-RPC request byte slice that is suitable for transmission to an RPC server. The provided command type must be a registered type. All commands provided by this package are registered by default.

func RegisterCmd

func RegisterCmd(method string, cmd interface{}, namedParameters bool) error

RegisterCmd registers a new command that will automatically marshal to and from JSON-RPC with full type checking and positional parameter support. It also accepts usage flags which identify the circumstances under which the command can be used.

This package automatically registers all of the exported commands by default using this function, however it is also exported so callers can easily register custom types.

The type format is very strict since it needs to be able to automatically marshal to and from JSON-RPC 1.0. The following enumerates the requirements:

  • The provided command must be a single pointer to a struct
  • All fields must be exported
  • The order of the positional parameters in the marshalled JSON will be in the same order as declared in the struct definition
  • Struct embedding is not supported
  • Struct fields may NOT be channels, functions, complex, or interface
  • A field in the provided struct with a pointer is treated as optional
  • Multiple indirections (i.e **int) are not supported
  • Once the first optional field (pointer) is encountered, the remaining fields must also be optional fields (pointers) as required by positional params
  • A field that has a 'jsonrpcdefault' struct tag must be an optional field (pointer)

NOTE: This function only needs to be able to examine the structure of the passed struct, so it does not need to be an actual instance. Therefore, it is recommended to simply pass a nil pointer cast to the appropriate type. For example, (*FooCmd)(nil).

func UseLogger

func UseLogger(logger btclog.Logger)

UseLogger uses a specified Logger to output package logging info.

Types

type BroadcastCmd

type BroadcastCmd struct {
	SerializedTransaction string
}

BroadcastCmd defines the broadcast RPC command.

func NewBroadcastCmd

func NewBroadcastCmd(tx *wire.MsgTx) (cmd *BroadcastCmd)

NewBroadcastCmd returns a new instance which can be used to issue a broadcast JSON-RPC command.

type Client

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

Client represents an Electrum RPC client which allows easy access to the various RPC methods available on a Electrum RPC server. Each of the wrapper functions handle the details of converting the passed and return types to and from the underlying JSON types which are required for the JSON-RPC invocations

func New

func New(config *ConnConfig) (*Client, error)

New creates a new RPC client based on the provided connection configuration details.

func (*Client) Broadcast

func (c *Client) Broadcast(tx *wire.MsgTx) (*chainhash.Hash, error)

Broadcast a transaction to the network by issuing a broadcast JSON-RPC command

func (*Client) BroadcastAsync

func (c *Client) BroadcastAsync(tx *wire.MsgTx) FutureBroadcastResult

BroadcastAsync returns an instance of a type that can be used to get the result of the RPC at some future time by invoking the Receive function on the returned instance.

See Broadcast for the blocking version and more details.

func (*Client) DumpPrivKey

func (c *Client) DumpPrivKey(address btcutil.Address) (*btcutil.WIF, error)

DumpPrivKey gets the private key corresponding to the passed address encoded in the wallet import format (WIF).

func (*Client) DumpPrivKeyAsync

func (c *Client) DumpPrivKeyAsync(address btcutil.Address) FutureDumpPrivKeyResult

DumpPrivKeyAsync returns an instance of a type that can be used to get the result of the RPC at some future time by invoking the Receive function on the returned instance.

See DumpPrivKey for the blocking version and more details.

func (*Client) GetFeeRate

func (c *Client) GetFeeRate() (btcutil.Amount, error)

GetFeeRate Returns the current optimal fee rate per kilobyte, according to config settings(static/dynamic)returns the first unused address of the wallet,

func (*Client) GetFeeRateAsync

func (c *Client) GetFeeRateAsync() FutureGetFeeRateResult

GetFeeRateAsync returns an instance of a type that can be used to get the result of the RPC at some future time by invoking the Receive function on the returned instance.

See GetUnusedAddress for the blocking version and more details.

func (*Client) GetUnusedAddress

func (c *Client) GetUnusedAddress() (btcutil.Address, error)

GetUnusedAddress returns the first unused address of the wallet, or None if all addresses are used. An address is considered as used if it has received a transaction, or if it is used in a payment request.

func (*Client) GetUnusedAddressAsync

func (c *Client) GetUnusedAddressAsync() FutureGetUnusedAddressResult

GetUnusedAddressAsync returns an instance of a type that can be used to get the result of the RPC at some future time by invoking the Receive function on the returned instance.

See GetUnusedAddress for the blocking version and more details.

func (*Client) ListUnspent

func (c *Client) ListUnspent() ([]*UnspentOutput, error)

ListUnspent returns the list of unspent transaction outputs in the wallet by issuing a listunspent JSON-RPC command.

func (*Client) ListUnspentAsync

func (c *Client) ListUnspentAsync() FutureListUnspentResult

ListUnspentAsync returns an instance of a type that can be used to get the result of the RPC at some future time by invoking the Receive function on the returned instance.

See ListUnspent for the blocking version and more details.

func (*Client) NextID

func (c *Client) NextID() uint64

NextID returns the next id to be used when sending a JSON-RPC message. This ID allows responses to be associated with particular requests per the JSON-RPC specification. Typically the consumer of the client does not need to call this function, however, if a custom request is being created and used this function should be used to ensure the ID is unique amongst all requests being made.

func (*Client) PayTo

func (c *Client) PayTo(destination btcutil.Address, amount btcutil.Amount, unsigned bool) (tx *wire.MsgTx, complete bool, err error)

PayTo returns a funded transaction

func (*Client) PayToAsync

func (c *Client) PayToAsync(destination btcutil.Address, amount btcutil.Amount, unsigned bool) FuturePayToResult

PayToAsync returns an instance of a type that can be used to get the result of the RPC at some future time by invoking the Receive function on the returned instance.

See PayTo for the blocking version and more details.

func (*Client) SendRawTransaction

func (c *Client) SendRawTransaction(tx *wire.MsgTx, allowHighFees bool) (*chainhash.Hash, error)

SendRawTransaction submits the encoded transaction to the server which will then relay it to the network. The allowHighFees parameter is ignored.

func (*Client) Shutdown

func (c *Client) Shutdown()

Shutdown shuts down the client by disconnecting any connections associated with the client and, when automatic reconnect is enabled, preventing future attempts to reconnect. It also stops all goroutines.

func (*Client) SignRawTransaction

func (c *Client) SignRawTransaction(tx *wire.MsgTx) (*wire.MsgTx, bool, error)

SignRawTransaction signs inputs for the passed transaction and returns the signed transaction as well as whether or not all inputs are now signed.

This function assumes the RPC server already knows the input transactions and private keys for the passed transaction which needs to be signed and uses the default signature hash type. Use one of the SignRawTransaction# variants to specify that information if needed.

func (*Client) WaitForShutdown

func (c *Client) WaitForShutdown()

WaitForShutdown blocks until the client goroutines are stopped and the connection is closed.

type ConnConfig

type ConnConfig struct {
	// Host is the IP address and port of the RPC server you want to connect
	// to.
	Host string

	// User is the username to use to authenticate to the RPC server.
	User string

	// Pass is the passphrase to use to authenticate to the RPC server.
	Pass string

	// DisableTLS specifies whether transport layer security should be
	// disabled.  It is recommended to always use TLS if the RPC server
	// supports it as otherwise your username and password is sent across
	// the wire in cleartext.
	DisableTLS bool

	// Certificates are the bytes for a PEM-encoded certificate chain used
	// for the TLS connection.  It has no effect if the DisableTLS parameter
	// is true.
	Certificates []byte

	// Proxy specifies to connect through a SOCKS 5 proxy server.  It may
	// be an empty string if a proxy is not required.
	Proxy string

	// ProxyUser is an optional username to use for the proxy server if it
	// requires authentication.  It has no effect if the Proxy parameter
	// is not set.
	ProxyUser string

	// ProxyPass is an optional password to use for the proxy server if it
	// requires authentication.  It has no effect if the Proxy parameter
	// is not set.
	ProxyPass string

	// HTTPPostMode instructs the client to run using multiple independent
	// connections issuing HTTP POST requests instead of using the default
	// of websockets.  Websockets are generally preferred as some of the
	// features of the client such notifications only work with websockets,
	// however, not all servers support the websocket extensions, so this
	// flag can be set to true to use basic HTTP POST requests instead.
	//This flag is only here for compatibility with btcsuite's ConnConfig,
	//Http post is the only supportedmode
	HTTPPostMode bool
}

ConnConfig describes the connection configuration parameters for the client. This

type FutureBroadcastResult

type FutureBroadcastResult chan *response

FutureBroadcastResult is a future promise to deliver the result of a broadcast RPC invocation (or an applicable error).

func (FutureBroadcastResult) Receive

func (r FutureBroadcastResult) Receive() (*chainhash.Hash, error)

Receive waits for the response promised by the future and returns a the feerate.

type FutureDumpPrivKeyResult

type FutureDumpPrivKeyResult chan *response

FutureDumpPrivKeyResult is a future promise to deliver the result of a DumpPrivKeyAsync RPC invocation (or an applicable error).

func (FutureDumpPrivKeyResult) Receive

func (r FutureDumpPrivKeyResult) Receive() (*btcutil.WIF, error)

Receive waits for the response promised by the future and returns the private key corresponding to the passed address encoded in the wallet import format (WIF)

type FutureGetFeeRateResult

type FutureGetFeeRateResult chan *response

FutureGetFeeRateResult is a future promise to deliver the result of a GetFeeRateAsync RPC invocation (or an applicable error).

func (FutureGetFeeRateResult) Receive

func (r FutureGetFeeRateResult) Receive() (feerate btcutil.Amount, err error)

Receive waits for the response promised by the future and returns a the feerate.

type FutureGetUnusedAddressResult

type FutureGetUnusedAddressResult chan *response

FutureGetUnusedAddressResult is a future promise to deliver the result of a GetUnusedAddressAsync RPC invocation (or an applicable error).

func (FutureGetUnusedAddressResult) Receive

Receive waits for the response promised by the future and returns a new address.

type FutureListUnspentResult

type FutureListUnspentResult chan *response

FutureListUnspentResult is a future promise to deliver the result of a listunspent RPC invocation (or an applicable error).

func (FutureListUnspentResult) Receive

func (r FutureListUnspentResult) Receive() (utxos []*UnspentOutput, err error)

Receive waits for the response promised by the future and returns the decode unspent outputs.

type FuturePayToResult

type FuturePayToResult chan *response

FuturePayToResult is a future promise to deliver the result of a payto RPC invocation (or an applicable error).

func (FuturePayToResult) Receive

func (r FuturePayToResult) Receive() (tx *wire.MsgTx, complete bool, err error)

Receive waits for the response promised by the future and returns the transaction and wether or not it is complete ( signed).

type GetFeeRateCmd

type GetFeeRateCmd struct {
}

GetFeeRateCmd defines the getfeerate RPC command.

func NewGetFeeRateCmd

func NewGetFeeRateCmd() *GetFeeRateCmd

NewGetFeeRateCmd returns a new instance which can be used to issue a getfeerate JSON-RPC command.

type GetPrivateKeysCmd

type GetPrivateKeysCmd struct {
	Address string
}

GetPrivateKeysCmd defines the getprivatekeys JSON-RPC command.

func NewGetPrivateKeysCmd

func NewGetPrivateKeysCmd(addresses ...string) (cmd *GetPrivateKeysCmd)

NewGetPrivateKeysCmd returns a new instance which can be used to issue a getprivatekeys JSON-RPC command.

type GetUnusedAddressCmd

type GetUnusedAddressCmd struct {
}

GetUnusedAddressCmd defines the getunusedaddress JSON-RPC command.

func NewGetUnusedAddressCmd

func NewGetUnusedAddressCmd() *GetUnusedAddressCmd

NewGetUnusedAddressCmd returns a new instance which can be used to issue a getunusedaddress JSON-RPC command.

type ListUnspentCmd

type ListUnspentCmd struct {
}

ListUnspentCmd defines the listunspent RPC command.

func NewListUnspentCmd

func NewListUnspentCmd() *ListUnspentCmd

NewListUnspentCmd returns a new instance which can be used to issue a getfeerate JSON-RPC command.

type PayToCmd

type PayToCmd struct {
	Destination string  `json:"destination"`
	Amount      float64 `json:"amount"`
	UnSigned    bool    `json:"unsigned"`
}

PayToCmd defines the payto RPC command.

func NewPayToCmd

func NewPayToCmd(destination btcutil.Address, amount btcutil.Amount, unsigned bool) *PayToCmd

NewPayToCmd returns a new instance which can be used to issue a payto JSON-RPC command.

type RPCError

type RPCError struct {
	Code    RPCErrorCode `json:"code,omitempty"`
	Message string       `json:"message,omitempty"`
}

RPCError represents an error that is used as a part of a JSON-RPC Response object.

func (RPCError) Error

func (e RPCError) Error() string

Error returns a string describing the RPC error. This satisifies the builtin error interface.

type RPCErrorCode

type RPCErrorCode int

RPCErrorCode represents an error code to be used as a part of an RPCError which is in turn used in a JSON-RPC Response object.

A specific type is used to help ensure the wrong errors aren't used.

type Request

type Request struct {
	Jsonrpc string      `json:"jsonrpc"`
	Method  string      `json:"method"`
	Params  interface{} `json:"params"`
	ID      interface{} `json:"id"`
}

Request is a type for raw JSON-RPC 1.0 requests. The Method field identifies the specific command type which in turns leads to different parameters. Callers typically will not use this directly since this package provides a statically typed command infrastructure which handles creation of these requests, however this struct it being exported in case the caller wants to construct raw requests for some reason.

func NewRequestWithNamedParameters

func NewRequestWithNamedParameters(id interface{}, method string, params interface{}) (*Request, error)

NewRequestWithNamedParameters should be merged with NewRequestWithPositionalParameters

func NewRequestWithPositionalParameters

func NewRequestWithPositionalParameters(id interface{}, method string, params []interface{}) (*Request, error)

NewRequestWithPositionalParameters returns a new JSON-RPC 1.0 request object given the provided id, method, and parameters. The parameters are marshalled into a json.RawMessage for the Params field of the returned request object. This function is only provided in case the caller wants to construct raw requests for some reason.

Typically callers will instead want to create a registered concrete command type with the NewCmd or New<Foo>Cmd functions and call the MarshalCmd function with that command to generate the marshalled JSON-RPC request.

type UnspentOutput

type UnspentOutput struct {
	Address  btcutil.Address
	Value    btcutil.Amount
	OutPoint *wire.OutPoint
	Height   int64
}

UnspentOutput represents an unspent output

Jump to

Keyboard shortcuts

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