electrumx

package
v0.0.0-...-7df67f7 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2024 License: MIT Imports: 19 Imported by: 2

README

Package electrumx

Basic ElectrumX connection(s) and RPC methods.

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 ...any) {
		fmt.Printf(format+"\n", params...)
	})
	// StderrPrinter is a DebugLogger that uses fmt.Fprintf(os.Stderr, ...).
	StderrPrinter = Printer(func(format string, params ...any) {
		fmt.Fprintf(os.Stderr, format+"\n", params...)
	})
)
View Source
var DebugMode bool

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 ConnectOpts

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

type ElectrumXNode

type ElectrumXNode interface {
	Start(ctx context.Context) error
	RegisterNetworkRestart() <-chan *NetworkRestart
	Stop()
	GetHeadersNotify() (<-chan *HeadersNotifyResult, error)
	SubscribeHeaders(ctx context.Context) (*HeadersNotifyResult, error)
	GetScripthashNotify() (<-chan *ScripthashStatusResult, error)
	SubscribeScripthashNotify(ctx context.Context, scripthash string) (*ScripthashStatusResult, error)
	UnsubscribeScripthashNotify(ctx context.Context, scripthash string)

	BlockHeaders(ctx context.Context, startHeight int64, blockCount int) (*GetBlockHeadersResult, error)
	GetHistory(ctx context.Context, scripthash string) (HistoryResult, error)
	GetListUnspent(ctx context.Context, scripthash string) (ListUnspentResult, error)
	GetTransaction(ctx context.Context, txid string) (*GetTransactionResult, error)
	GetRawTransaction(ctx context.Context, txid string) (string, error)
	//
	EstimateFeeRate(ctx context.Context, confTarget int64) (int64, error)
	Broadcast(ctx context.Context, rawTx string) (string, error)
}

type GetBlockHeadersResult

type GetBlockHeadersResult struct {
	Count     int    `json:"count"`
	HexConcat string `json:"hex"`
	Max       int64  `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 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 HeadersNotifyResult

type HeadersNotifyResult struct {
	Height int64  `json:"height"`
	Hex    string `json:"hex"`
}

HeadersNotifyResult is the contents of a block header notification.

type History

type History struct {
	Height int64  `json:"height"`
	TxHash string `json:"tx_hash"`
	Fee    int    `json:"fee,omitempty"` // satoshis; iff in mempool
}

type HistoryResult

type HistoryResult []History

type ListUnspent

type ListUnspent struct {
	Height int64  `json:"height"`
	TxPos  int64  `json:"tx_pos"`
	TxHash string `json:"tx_hash"`
	Value  int64  `json:"value"` // satoshis
}

type ListUnspentResult

type ListUnspentResult []ListUnspent

type Network

type Network string
var Mainnet Network = "mainnet"
var Regtest Network = "regtest"
var Testnet Network = "testnet"

type NetworkRestart

type NetworkRestart struct {
	Time time.Time
}

type NodeConfig

type NodeConfig struct {
	// The blockchain, Bitcoin, Dash, etc
	Chain wallet.CoinType

	// Network parameters. Set mainnet, testnet using this.
	Params *chaincfg.Params

	// The user-agent that shall be visible to the network
	UserAgent string

	// Location of the data directory
	DataDir string

	// If you wish to connect to a single trusted electrumX peer set this.
	TrustedPeer net.Addr

	// A Tor proxy can be set here causing the wallet will use Tor. TODO:
	Proxy proxy.Dialer

	// If not testing do not overwrite existing wallet files
	Testing bool
}

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 ...any)

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.

func (*RPCError) UnmarshalJSON

func (e *RPCError) UnmarshalJSON(b []byte) error

Not all servers return correct RPCError struct json. At least one tested: 'blockstream.info' returns just a string "verbose transactions are currently unsupported" for some requests on both mainnet and testnet.

type ScripthashStatusResult

type ScripthashStatusResult struct {
	Scripthash string // 32 byte scripthash - the id of the watched address
	Status     string // 32 byte sha256 hash of entire history to date or null
}

ScripthashStatusResult is the contents of a scripthash notification. Raw bytes with no json key names or json [] {} delimiters

type ServerAddr

type ServerAddr struct {
	Net, Addr string
}

func (ServerAddr) Network

func (a ServerAddr) Network() string

func (ServerAddr) String

func (a ServerAddr) String() string

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 int64, count int) (*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) Broadcast

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

Broadcast broadcasts a raw tx as a hexadecimal string to the network. The tx hash is returned as a hexadecimal string.

func (*ServerConn) Done

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

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

func (*ServerConn) EstimateFee

func (sc *ServerConn) EstimateFee(ctx context.Context, confTarget int64) (int64, error)

estimated transaction fee in coin units per kilobyte, as a floating point number string. If the daemon does not have enough information to make an estimate, the integer -1 is returned.

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

func (sc *ServerConn) GetHeadersNotify() <-chan *HeadersNotifyResult

GetHeadersNotify returns this connection owned recv channel for headers tip change notifications. This connection will close the channel.

func (*ServerConn) GetHistory

func (sc *ServerConn) GetHistory(ctx context.Context, scripthash string) (HistoryResult, error)

GetHistory gets a list of [{height, txid and fee},...] for the scripthash of an address of interest to the client

func (*ServerConn) GetListUnspent

func (sc *ServerConn) GetListUnspent(ctx context.Context, scripthash string) (ListUnspentResult, error)

GetListUnspent gets a list of [{height, txid tx_pos and value},...] for the scripthash of an address of interest to the client

func (*ServerConn) GetRawTransaction

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

GetTransaction requests a transaction as raw byte.

func (*ServerConn) GetScripthashNotify

func (sc *ServerConn) GetScripthashNotify() <-chan *ScripthashStatusResult

GetScripthashNotify returns this connection owned recv channel for scripthash status change notifications. This connection will close the channel.

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 any, result any) 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) (*HeadersNotifyResult, 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.

func (*ServerConn) SubscribeScripthash

func (sc *ServerConn) SubscribeScripthash(ctx context.Context, scripthash string) (*ScripthashStatusResult, error)

SubscribeScripthash subscribes for notifications of changes for an address in our wallet. We send the electrum 'scripthash' of the address rather than the base58 encoded string. See also client_wallet.go.

func (*ServerConn) UnsubscribeScripthash

func (sc *ServerConn) UnsubscribeScripthash(ctx context.Context, scripthash string)

Unsubscribe from a script hash, preventing future status change notifications.

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  any                          `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 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.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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