electrum

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2022 License: BlueOak-1.0.0 Imports: 20 Imported by: 0

Documentation

Overview

Package electrum provides a client for an ElectrumX server. Not all methods are implemented. For the methods and their request and response types, see https://electrumx.readthedocs.io/en/latest/protocol-methods.html.

Index

Constants

This section is empty.

Variables

View Source
var (
	// StdoutPrinter is a DebugLogger that uses fmt.Printf.
	StdoutPrinter = Printer(func(format string, params ...interface{}) {
		fmt.Printf(format+"\n", params...)
	})
	// StderrPrinter is a DebugLogger that uses fmt.Fprintf(os.Stderr, ...).
	StderrPrinter = Printer(func(format string, params ...interface{}) {
		fmt.Fprintf(os.Stderr, format+"\n", params...)
	})
)

Functions

func SSLPeerAddrs

func SSLPeerAddrs(peers []*PeersResult, includeOnion bool) (ssl, tcpOnlyOnion []string)

SSLPeerAddrs filters the peers slice and returns the addresses in a "host:port" format in separate slices for SSL-enabled servers and optionally TCP-only hidden services (.onion host names). Note that if requesting to include onion hosts, the SSL slice may include onion hosts that also use SSL.

Types

type Balance

type Balance struct {
	Confirmed   float64 // not reduced by spends until the txn is confirmed
	Unconfirmed float64 // will be negative for sends
	Immature    float64
}

Balance is the result of the balance RPC.

type ConnectOpts

type ConnectOpts struct {
	TLSConfig   *tls.Config // nil means plain
	TorProxy    string
	DebugLogger Printer
}

type GetAddressHistoryResult

type GetAddressHistoryResult struct {
	Fee    *int64 `json:"fee,omitempty"` // set when unconfirmed
	Height int64  `json:"height"`        // 0 when unconfirmed
	TxHash string `json:"tx_hash"`
}

GetAddressHistoryResult is an element of the array returned by the getaddresshistory RPC.

type GetAddressUnspentResult

type GetAddressUnspentResult struct {
	Height int64  `json:"height"`
	TxHash string `json:"tx_hash"`
	TxPos  int32  `json:"tx_pos"`
	Value  int64  `json:"value"`
}

GetAddressUnspentResult is an element of the array returned by the getaddressunspent RPC.

type GetBlockHeadersResult

type GetBlockHeadersResult struct {
	Count     uint32 `json:"count"`
	HexConcat string `json:"hex"`
	Max       uint32 `json:"max"`
}

GetBlockHeadersResult represent the result of a batch request for block headers via the BlockHeaders method. The serialized block headers are concatenated in the HexConcat field, which contains Count headers.

type GetInfoResult

type GetInfoResult struct {
	AutoConnect   bool   `json:"auto_connect"`
	SyncHeight    int64  `json:"blockchain_height"`
	Connected     bool   `json:"connected"`
	DefaultWallet string `json:"default_wallet"`
	FeePerKB      int64  `json:"fee_per_kb"`
	Path          string `json:"path"`
	Server        string `json:"server"`
	ServerHeight  int64  `json:"server_height"`
	Connections   int64  `json:"spv_nodes"`
	Version       string `json:"version"`
}

GetInfoResult is the result of the getinfo RPC.

type GetServersResult

type GetServersResult struct {
	Host    string
	Pruning string
	SSL     uint16
	TCP     uint16
	Version string
}

GetServersResult is an entry in the map returned by the getservers RPC, with the Host name included.

type GetTransactionResult

type GetTransactionResult struct {
	TxID string `json:"txid"`
	// Hash          string `json:"hash"` // ??? don't use, not always the txid! witness not stripped?
	Version       uint32 `json:"version"`
	Size          uint32 `json:"size"`
	VSize         uint32 `json:"vsize"`
	Weight        uint32 `json:"weight"`
	LockTime      uint32 `json:"locktime"`
	Hex           string `json:"hex"`
	Vin           []Vin  `json:"vin"`
	Vout          []Vout `json:"vout"`
	BlockHash     string `json:"blockhash,omitempty"`
	Confirmations int32  `json:"confirmations,omitempty"` // probably uint32 ok because it seems to be omitted, but could be -1?
	Time          int64  `json:"time,omitempty"`
	BlockTime     int64  `json:"blocktime,omitempty"` // same as Time?

}

GetTransactionResult is the data returned by a transaction request.

type ListUnspentResult

type ListUnspentResult struct {
	Address       string `json:"address"`
	Value         string `json:"value"` // BTC in a string :/
	Coinbase      bool   `json:"coinbase"`
	Height        int64  `json:"height"`
	Sequence      uint32 `json:"nsequence"`
	PrevOutHash   string `json:"prevout_hash"`
	PrevOutIdx    uint32 `json:"prevout_n"`
	RedeemScript  string `json:"redeem_script"`
	WitnessScript string `json:"witness_script"`
}

ListUnspentResult is an element of the array returned by the listunspent RPC.

type PeersResult

type PeersResult struct {
	Addr  string // IP address or .onion name
	Host  string
	Feats []string
}

PeersResult represents the results of a peers server request.

type PkScript

type PkScript struct {
	Asm       string   `json:"asm"`
	Hex       string   `json:"hex"`
	ReqSigs   uint32   `json:"reqsigs"`
	Type      string   `json:"type"`
	Addresses []string `json:"addresses,omitempty"`
}

PkScript represents the pkScript/scriptPubKey of a transaction output returned by a transaction requests.

type Printer

type Printer func(format string, params ...interface{})

Printer is a function with the signature of a logger method.

type RPCError

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

RPCError represents a JSON-RPC error object.

func (RPCError) Error

func (e RPCError) Error() string

Error satisfies the error interface.

type ServerConn

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

ServerConn represents a connection to an Electrum server e.g. ElectrumX. It is a single use type that must be replaced if the connection is lost. Use ConnectServer to construct a ServerConn and connect to the server.

func ConnectServer

func ConnectServer(ctx context.Context, addr string, opts *ConnectOpts) (*ServerConn, error)

ConnectServer connects to the electrum server at the given address. To close the connection and shutdown ServerConn, either cancel the context or use the Shutdown method, then wait on the channel from Done() to ensure a clean shutdown (connection closed and all requests handled). There is no automatic reconnection functionality, as the caller should handle dropped connections by potentially cycling to a different server.

func (*ServerConn) Banner

func (sc *ServerConn) Banner(ctx context.Context) (string, error)

Banner retrieves the server's banner, which is any announcement set by the server operator. It should be interpreted with caution as the content is untrusted.

func (*ServerConn) BlockHeader

func (sc *ServerConn) BlockHeader(ctx context.Context, height uint32) (string, error)

BlockHeader requests the block header at the given height, returning hexadecimal encoded serialized header.

func (*ServerConn) BlockHeaders

func (sc *ServerConn) BlockHeaders(ctx context.Context, startHeight, count uint32) (*GetBlockHeadersResult, error)

BlockHeaders requests a batch of block headers beginning at the given height. The sever may respond with a different number of headers, so the caller should check the Count field of the result.

func (*ServerConn) Done

func (sc *ServerConn) Done() <-chan struct{}

Done returns a channel that is closed when the ServerConn is fully shutdown.

func (*ServerConn) Features

func (sc *ServerConn) Features(ctx context.Context) (*ServerFeatures, error)

Features requests the features claimed by the server. The caller should check the Genesis hash field to ensure it is the intended network.

func (*ServerConn) GetTransaction

func (sc *ServerConn) GetTransaction(ctx context.Context, txid string) (*GetTransactionResult, error)

GetTransaction requests a transaction.

func (*ServerConn) Peers

func (sc *ServerConn) Peers(ctx context.Context) ([]*PeersResult, error)

Peers requests the known peers from a server (other servers). See SSLPeerAddrs to assist parsing useable peers.

func (*ServerConn) Ping

func (sc *ServerConn) Ping(ctx context.Context) error

Ping pings the remote server. This can be used as a connectivity test on demand, although a ServerConn started with ConnectServer will launch a pinger goroutine to keep the connection alive.

func (*ServerConn) Proto

func (sc *ServerConn) Proto() string

Proto returns the electrum protocol of the connected server. e.g. "1.4.2".

func (*ServerConn) Request

func (sc *ServerConn) Request(ctx context.Context, method string, args interface{}, result interface{}) error

Request performs a request to the remote server for the given method using the provided arguments, which may either be positional (e.g. []interface{arg1, arg2}), named (any struct), or nil if there are no arguments. args may not be any other basic type. The the response does not include an error, the result will be unmarshalled into result, unless the provided result is nil in which case the response payload will be ignored.

func (*ServerConn) Shutdown

func (sc *ServerConn) Shutdown()

Shutdown begins shutting down the connection and request handling goroutines. Receive on the channel from Done() to wait for shutdown to complete.

func (*ServerConn) SubscribeHeaders

func (sc *ServerConn) SubscribeHeaders(ctx context.Context) (*SubscribeHeadersResult, <-chan *SubscribeHeadersResult, error)

SubscribeHeaders subscribes for block header notifications. There seems to be no guarantee that we will be notified of all new blocks, such as when there are blocks in rapid succession.

type ServerFeatures

type ServerFeatures struct {
	Genesis  string                       `json:"genesis_hash"`
	Hosts    map[string]map[string]uint32 `json:"hosts"` // e.g. {"host.com": {"tcp_port": 51001, "ssl_port": 51002}}, may be unset!
	ProtoMax string                       `json:"protocol_max"`
	ProtoMin string                       `json:"protocol_min"`
	Pruning  interface{}                  `json:"pruning,omitempty"` // supposedly an integer, but maybe a string or even JSON null
	Version  string                       `json:"server_version"`    // server software version, not proto
	HashFunc string                       `json:"hash_function"`     // e.g. sha256

}

ServerFeatures represents the result of a server features requests.

type SigScript

type SigScript struct {
	Asm string `json:"asm"` // this is not the sigScript you're looking for
	Hex string `json:"hex"`
}

SigScript represents the signature script in a Vin returned by a transaction request.

type SubscribeHeadersResult

type SubscribeHeadersResult struct {
	Height int32  `json:"height"`
	Hex    string `json:"hex"`
}

SubscribeHeadersResult is the contents of a block header notification.

type Vin

type Vin struct {
	TxID      string     `json:"txid"`
	Vout      uint32     `json:"vout"`
	SigScript *SigScript `json:"scriptsig"`
	Witness   []string   `json:"txinwitness,omitempty"`
	Sequence  uint32     `json:"sequence"`
	Coinbase  string     `json:"coinbase,omitempty"`
}

Vin represents a transaction input in a requested transaction.

type Vout

type Vout struct {
	Value    float64  `json:"value"`
	N        uint32   `json:"n"`
	PkScript PkScript `json:"scriptpubkey"`
}

Vout represents a transaction output in a requested transaction.

type WalletClient

type WalletClient struct {

	// HTTPClient may be set by the user to a custom http.Client. The
	// constructor sets a vanilla client.
	HTTPClient *http.Client
	// Timeout is the timeout on http requests. A 10 second default is set by
	// the constructor.
	Timeout time.Duration
	// contains filtered or unexported fields
}

WalletClient is an Electrum wallet HTTP JSON-RPC client.

func NewWalletClient

func NewWalletClient(user, pass, endpoint string) *WalletClient

NewWalletClient constructs a new Electrum wallet RPC client with the given authorization information and endpoint. The endpoint should include the protocol, e.g. http://127.0.0.1:4567. To specify a custom http.Client or request timeout, the fields may be set after construction.

func (*WalletClient) AddLocalTx

func (wc *WalletClient) AddLocalTx(ctx context.Context, tx []byte) (string, error)

AddLocalTx is used to add a "local" transaction to the Electrum wallet DB. This does not broadcast it.

func (*WalletClient) Broadcast

func (wc *WalletClient) Broadcast(ctx context.Context, tx []byte) (string, error)

Broadcast submits the transaction to the network.

func (*WalletClient) Call

func (ec *WalletClient) Call(ctx context.Context, method string, args interface{}, result interface{}) error

Call makes a JSON-RPC request for the given method with the provided arguments. args may be a struct or slice that marshalls to JSON. If it is a slice, it represents positional arguments. If it is a struct or pointer to a struct, it represents "named" parameters in key-value format. Any arguments should have their fields appropriately tagged for JSON marshalling. The result is marshaled into result if it is non-nil, otherwise the result is discarded.

func (*WalletClient) CheckAddress

func (wc *WalletClient) CheckAddress(ctx context.Context, addr string) (valid, mine bool, err error)

CheckAddress validates the address and reports if it belongs to the wallet.

func (*WalletClient) Commands

func (wc *WalletClient) Commands(ctx context.Context) ([]string, error)

Commands gets a list of the supported wallet RPCs.

func (*WalletClient) CreateNewAddress

func (wc *WalletClient) CreateNewAddress(ctx context.Context) (string, error)

CreateNewAddress generates a new address, ignoring the gap limit. NOTE: There is no method to retrieve a change address (makes recovery difficult).

func (*WalletClient) FeeRate

func (wc *WalletClient) FeeRate(ctx context.Context, confTarget int64) (int64, error)

FeeRate gets a fee rate estimate for a block confirmation target, where 1 indicates the next block.

func (*WalletClient) FreezeUTXO

func (wc *WalletClient) FreezeUTXO(ctx context.Context, txid string, out uint32) error

FreezeUTXO freezes/locks a single UTXO. It will still be reported by listunspent while locked.

func (*WalletClient) GetAddressHistory

func (wc *WalletClient) GetAddressHistory(ctx context.Context, addr string) ([]*GetAddressHistoryResult, error)

GetAddressHistory returns the history an address. Confirmed transactions will have a nil Fee field, while unconfirmed transactions will have a Fee and a value of zero for Height.

func (*WalletClient) GetAddressUnspent

func (wc *WalletClient) GetAddressUnspent(ctx context.Context, addr string) ([]*GetAddressUnspentResult, error)

GetAddressUnspent returns the unspent outputs for an address. Unconfirmed outputs will have a value of zero for Height.

func (*WalletClient) GetBalance

func (wc *WalletClient) GetBalance(ctx context.Context) (*Balance, error)

GetBalance returns the result of the getbalance wallet RPC.

func (*WalletClient) GetInfo

func (wc *WalletClient) GetInfo(ctx context.Context) (*GetInfoResult, error)

GetInfo gets basic Electrum wallet info.

func (*WalletClient) GetPrivateKeys

func (wc *WalletClient) GetPrivateKeys(ctx context.Context, walletPass, addr string) (string, error)

GetPrivateKeys uses the getprivatekeys RPC to retrieve the keys for a given address. The returned string is WIF-encoded.

func (*WalletClient) GetRawTransaction

func (wc *WalletClient) GetRawTransaction(ctx context.Context, txid string) ([]byte, error)

GetRawTransaction retrieves the serialized transaction identified by txid.

func (*WalletClient) GetServers

func (wc *WalletClient) GetServers(ctx context.Context) ([]*GetServersResult, error)

GetServers gets the electrum servers known to the wallet. These are the possible servers to which Electrum may connect. This includes the currently connected server named in the GetInfo result.

func (*WalletClient) GetUnusedAddress

func (wc *WalletClient) GetUnusedAddress(ctx context.Context) (string, error)

GetUnusedAddress gets the next unused address from the wallet. It may have already been requested.

func (*WalletClient) GetWalletTxConfs

func (wc *WalletClient) GetWalletTxConfs(ctx context.Context, txid string) (int, error)

GetWalletTxConfs will get the confirmations on the wallet-related transaction. This function will error if it is either not a wallet transaction or not known to the wallet.

func (*WalletClient) ListUnspent

func (wc *WalletClient) ListUnspent(ctx context.Context) ([]*ListUnspentResult, error)

ListUnspent returns details on all unspent outputs for the wallet. Note that the pkScript is not included, and the user would have to retrieve it with GetRawTransaction for PrevOutHash if the output is of interest.

func (*WalletClient) PayTo

func (wc *WalletClient) PayTo(ctx context.Context, walletPass string, addr string, amtBTC float64, feeRate float64) ([]byte, error)

PayTo sends the specified amount in BTC (or the conventional unit for the assets e.g. LTC) to an address using a certain fee rate. The transaction is not broadcasted; the raw bytes of the signed transaction are returned. After the caller verifies the transaction, it may be sent with Broadcast.

func (*WalletClient) PayToFromCoinsAbsFee

func (wc *WalletClient) PayToFromCoinsAbsFee(ctx context.Context, walletPass string, fromCoins []string, addr string, amtBTC float64, absFee float64) ([]byte, error)

PayToFromAbsFee allows specifying prevouts (in txid:vout format) and an absolute fee in BTC instead of a fee rate. This combination allows specifying precisely how much will be withdrawn from the wallet (subtracting fees), unless the change is dust and omitted. The transaction is not broadcasted; the raw bytes of the signed transaction are returned. After the caller verifies the transaction, it may be sent with Broadcast.

func (*WalletClient) RemoveLocalTx

func (wc *WalletClient) RemoveLocalTx(ctx context.Context, txid string) error

RemoveLocalTx is used to remove a "local" transaction from the Electrum wallet DB. This can only be done if the tx was not broadcasted. This is required if using AddLocalTx or a payTo method that added the local transaction but either it failed to broadcast or the user no longer wants to send it after inspecting the raw transaction. Calling RemoveLocalTx with an already broadcast or non-existent txid will not generate an error.

func (*WalletClient) SignTx

func (wc *WalletClient) SignTx(ctx context.Context, walletPass string, psbtB64 string) ([]byte, error)

SignTx signs the base-64 encoded PSBT with the wallet's keys, returning the signed transaction.

func (*WalletClient) Sweep

func (wc *WalletClient) Sweep(ctx context.Context, walletPass string, addr string, feeRate float64) ([]byte, error)

Sweep sends all available funds to an address with a specified fee rate. No change output is created. The transaction is not broadcasted; the raw bytes of the signed transaction are returned. After the caller verifies the transaction, it may be sent with Broadcast.

func (*WalletClient) UnfreezeUTXO

func (wc *WalletClient) UnfreezeUTXO(ctx context.Context, txid string, out uint32) error

UnfreezeUTXO unfreezes/unlocks a single UTXO.

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

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