electrum

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2018 License: MIT Imports: 13 Imported by: 0

README

Electrum Client

Build Status GoDoc Version Software License Go Report Card

Provides a pure Go electrum protocol client implementation.

Features include:

  • Simple to use
  • Subscriptions are managed via channels and context
  • Full TCP and TSL support
  • Safe for concurrent execution

Example

// Start a new client instance
client, _ := electrum.New(&electrum.Options{
  Address:   "node.xbt.eu:50002",
  KeepAlive: true,
})

// Execute synchronous operation
version, _ := client.ServerVersion()

// Start a subscription, will terminate automatically after 30 seconds
ctx, cancel := context.WithTimeout(context.Background(), 30 * time.Second)
defer cancel()
headers, _ := client.NotifyBlockHeaders(ctx)
for header := range headers {
  // Use header
}

// Finish client execution
client.Close()

Documentation

Overview

Package electrum provides an Electrum protocol client implementation.

The client supports two kind of operations, synchronous and asynchronous; for simplicity must methods are exported as sync operations and only long running methods, i.e. subscriptions, are exported as asynchronous.

Subscriptions take a context object that allows the client to cancel/close an instance at any given time; subscriptions also returned a channel for data transfer, the channel will be automatically closed by the client instance when the subscription is terminated.

The client supports TCP and TSL connections.

Creating a Client

First start a new client instance

client, _ := electrum.New(&electrum.Options{
  Address:   "node.xbt.eu:50002",
  KeepAlive: true,
})

Synchronous Operations

Execute operations as regular methods

version, _ := client.ServerVersion()

Subscriptions

Get notifications using regular channels and context

ctx, cancel := context.WithTimeout(context.Background(), 30 * time.Second)
defer cancel()
headers, _ := client.NotifyBlockHeaders(ctx)
  for header := range headers {
  // Use header
}

Terminating a Client

When done with the client instance free-up resources and terminate network communications

client.Close();

Protocol specification is available at: http://docs.electrum.org/en/latest/protocol.html

Index

Examples

Constants

View Source
const (
	Protocol10 = "1.0"
	Protocol11 = "1.1"
	Protocol12 = "1.2"
)

Protocol tags

View Source
const Version = "0.4.1"

Version flag for the library

Variables

View Source
var (
	ErrDeprecatedMethod  = errors.New("DEPRECATED_METHOD")
	ErrUnavailableMethod = errors.New("UNAVAILABLE_METHOD")
	ErrRejectedTx        = errors.New("REJECTED_TRANSACTION")
	ErrUnreachableHost   = errors.New("UNREACHABLE_HOST")
)

Common errors

Functions

This section is empty.

Types

type Balance

type Balance struct {
	Confirmed   uint64 `json:"confirmed"`
	Unconfirmed uint64 `json:"unconfirmed"`
}

Balance show the funds available to an address, both confirmed and unconfirmed

type BlockHeader

type BlockHeader struct {
	BlockHeight   uint64 `json:"block_height"`
	PrevBlockHash string `json:"prev_block_hash"`
	Timestamp     uint64 `json:"timestamp"`
	Nonce         uint64 `json:"nonce"`
	MerkleRoot    string `json:"merkle_root"`
	UtxoRoot      string `json:"utxo_root"`
	Version       int    `json:"version"`
	Bits          uint64 `json:"bits"`
}

BlockHeader display summarized details about an existing block in the chain

type Client

type Client struct {
	// Address of the remote server to use for communication
	Address string

	// Version of the client
	Version string

	// Protocol version preferred by the client instance
	Protocol string

	sync.Mutex
	// contains filtered or unexported fields
}

Client defines the protocol client instance structure and interface

func New

func New(options *Options) (*Client, error)

New will create and start processing on a new client instance

func (*Client) AddressBalance

func (c *Client) AddressBalance(address string) (balance *Balance, err error)

AddressBalance will synchronously run a 'blockchain.address.get_balance' operation

https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain-address-get-balance

func (*Client) AddressHistory

func (c *Client) AddressHistory(address string) (list *[]Tx, err error)

AddressHistory will synchronously run a 'blockchain.address.get_history' operation

https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain-address-get-history

func (*Client) AddressListUnspent

func (c *Client) AddressListUnspent(address string) (list *[]Tx, err error)

AddressListUnspent will synchronously run a 'blockchain.address.listunspent' operation

https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain-address-listunspent

func (*Client) AddressMempool

func (c *Client) AddressMempool(address string) (list *[]Tx, err error)

AddressMempool will synchronously run a 'blockchain.address.get_mempool' operation

https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain-address-get-mempool

func (*Client) BlockChunk deprecated

func (c *Client) BlockChunk(index int) (interface{}, error)

BlockChunk will synchronously run a 'blockchain.block.get_chunk' operation https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain.block.get_chunk

Deprecated: Since protocol 1.2 https://electrumx.readthedocs.io/en/latest/protocol-changes.html#version-1-2

func (*Client) BlockHeader

func (c *Client) BlockHeader(index int) (header *BlockHeader, err error)

BlockHeader will synchronously run a 'blockchain.block.get_header' operation

https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain-block-get-header

func (*Client) BroadcastTransaction

func (c *Client) BroadcastTransaction(hex string) (string, error)

BroadcastTransaction will synchronously run a 'blockchain.transaction.broadcast' operation

https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain-transaction-broadcast

func (*Client) Close

func (c *Client) Close()

Close will finish execution and properly terminate the underlying network transport

func (*Client) EstimateFee

func (c *Client) EstimateFee(blocks int) (float64, error)

EstimateFee will synchronously run a 'blockchain.estimatefee' operation

https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain-estimatefee

func (*Client) GetTransaction

func (c *Client) GetTransaction(hash string) (string, error)

GetTransaction will synchronously run a 'blockchain.transaction.get' operation

https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain.transaction.get

func (*Client) NotifyAddressTransactions

func (c *Client) NotifyAddressTransactions(ctx context.Context, address string) (<-chan string, error)

NotifyAddressTransactions will setup a subscription for the method 'blockchain.address.subscribe'

https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain-address-subscribe

func (*Client) NotifyBlockHeaders

func (c *Client) NotifyBlockHeaders(ctx context.Context) (<-chan *BlockHeader, error)

NotifyBlockHeaders will setup a subscription for the method 'blockchain.headers.subscribe'

https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain-headers-subscribe

func (*Client) NotifyBlockNums deprecated

func (c *Client) NotifyBlockNums(ctx context.Context) (<-chan int, error)

NotifyBlockNums will setup a subscription for the method 'blockchain.numblocks.subscribe' https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain.numblocks.subscribe

Deprecated: Since protocol 1.0 https://electrumx.readthedocs.io/en/latest/protocol-changes.html#deprecated-methods

func (*Client) ServerBanner

func (c *Client) ServerBanner() (string, error)

ServerBanner will synchronously run a 'server.banner' operation

https://electrumx.readthedocs.io/en/latest/protocol-methods.html#server-banner

func (*Client) ServerDonationAddress

func (c *Client) ServerDonationAddress() (string, error)

ServerDonationAddress will synchronously run a 'server.donation_address' operation

https://electrumx.readthedocs.io/en/latest/protocol-methods.html#server-donation-address

Example
client, _ := New(&Options{
	Address: "electrum.villocq.com:50002",
	TLS: &tls.Config{
		InsecureSkipVerify: true,
	},
})
defer client.Close()
addr, _ := client.ServerDonationAddress()
fmt.Println(addr)
Output:

bc1q3jc48stsmulrvsyulpgyekfggfapxrpc3ertgk

func (*Client) ServerFeatures added in v0.3.0

func (c *Client) ServerFeatures() (*ServerInfo, error)

ServerFeatures returns a list of features and services supported by the server

https://electrumx.readthedocs.io/en/latest/protocol-methods.html#server-donation-address

func (*Client) ServerPeers added in v0.3.0

func (c *Client) ServerPeers() (peers []*Peer, err error)

ServerPeers returns a list of peer servers

https://electrumx.readthedocs.io/en/latest/protocol-methods.html#server-peers-subscribe

func (*Client) ServerPing added in v0.3.0

func (c *Client) ServerPing() error

ServerPing will send a ping message to the server to ensure it is responding, and to keep the session alive. The server may disconnect clients that have sent no requests for roughly 10 minutes.

https://electrumx.readthedocs.io/en/latest/protocol-methods.html#server-ping

func (*Client) ServerVersion

func (c *Client) ServerVersion() (*VersionInfo, error)

ServerVersion will synchronously run a 'server.version' operation

https://electrumx.readthedocs.io/en/latest/protocol-methods.html#server-version

Example
client, _ := New(&Options{
	Address: "electrum.villocq.com:50002",
	TLS: &tls.Config{
		InsecureSkipVerify: true,
	},
})
defer client.Close()
version, _ := client.ServerVersion()
fmt.Println(version.Software)
Output:

ElectrumX 1.8.5

func (*Client) TransactionMerkle

func (c *Client) TransactionMerkle(tx string, height int) (tm *TxMerkle, err error)

TransactionMerkle will synchronously run a 'blockchain.transaction.get_merkle' operation

https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain-transaction-get-merkle

func (*Client) UTXOAddress deprecated

func (c *Client) UTXOAddress(utxo string) (string, error)

UTXOAddress will synchronously run a 'blockchain.utxo.get_address' operation https://electrumx.readthedocs.io/en/latest/protocol-methods.html#blockchain.utxo.get_address

Deprecated: Since protocol 1.0 https://electrumx.readthedocs.io/en/latest/protocol-changes.html#deprecated-methods

type ConnectionState added in v0.4.0

type ConnectionState string

ConnectionState represents known connection state values

const (
	Ready        ConnectionState = "READY"
	Disconnected ConnectionState = "DISCONNECTED"
	Reconnecting ConnectionState = "RECONNECTING"
	Reconnected  ConnectionState = "RECONNECTED"
	Closed       ConnectionState = "CLOSED"
)

Connection state flags

type Host added in v0.3.0

type Host struct {
	SSLPort uint `json:"ssl_port"`
	TCPPort uint `json:"tcp_port"`
}

Host provides available endpoints for a given server

type Options

type Options struct {
	// Address of the server to use for network communications
	Address string

	// Version advertised by the client instance
	Version string

	// Protocol version preferred by the client instance
	Protocol string

	// If set to true, will enable the client to continuously dispatch
	// a 'server.version' operation every 60 seconds
	KeepAlive bool

	// Agent identifier that will be transmitted to the server when required;
	// will be concatenated with the client version
	Agent string

	// If provided, will be used to setup a secure network connection with the server
	TLS *tls.Config

	// If provided, will be used as logging sink
	Log *log.Logger
}

Options define the available configuration options

type Peer added in v0.3.0

type Peer struct {
	Address  string   `json:"address"`
	Name     string   `json:"name"`
	Features []string `json:"features"`
}

Peer provides details of a known server node

type ServerInfo added in v0.3.0

type ServerInfo struct {
	// A dictionary of endpoints that this server can be reached at. Normally this will only have a
	// single entry; other entries can be used in case there are other connection routes
	Hosts map[string]*Host `json:"hosts"`

	// The hash of the genesis block, can be used to detect if a peer is connected to one serving a different network
	GenesisHash string `json:"genesis_hash"`

	// The hash function the server uses for script hashing. The client must use this function to hash
	// pay-to-scripts to produce script hashes to send to the server
	HashFunction string `json:"hash_function"`

	// A string that identifies the server software
	ServerVersion string `json:"server_version"`

	// Max supported version of the protocol
	ProtocolMax string `json:"protocol_max"`

	// Min supported version of the protocol
	ProtocolMin string `json:"protocol_min"`
}

ServerInfo provides general information about the state and capabilities of the server

type Tx

type Tx struct {
	Hash   string `json:"tx_hash"`
	Pos    uint64 `json:"tx_pos"`
	Height uint64 `json:"height"`
	Value  uint64 `json:"value"`
}

Tx represents a transaction entry on the blockchain

type TxMerkle added in v0.3.0

type TxMerkle struct {
	BlockHeight uint64   `json:"block_height"`
	Pos         uint64   `json:"pos"`
	Merkle      []string `json:"merkle"`
}

TxMerkle provides the merkle branch of a given transaction

type VersionInfo added in v0.3.0

type VersionInfo struct {
	Software string `json:"software"`
	Protocol string `json:"protocol"`
}

VersionInfo contains the version information returned by the server

Jump to

Keyboard shortcuts

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