electrum

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Feb 13, 2019 License: MIT Imports: 10 Imported by: 0

README

go-electrum GoDoc

A pure Go Electrum JSON-RPC client library.

About

Note that Electrum daemon uses a random port number by default. In order to use a stable port number, you need to change configuration variable (and restart the daemon):

electrum setconfig rpcport 8001

Electrum will also initialize rpc username / password with a random string. To retreive the current values:

electrum getconfig rpcuser
electrum getconfig rpcpassword

ToDo

Implemented Electrum commands based on v3.2.3.

Command Implemented Notes
addrequest
addtransaction
broadcast
clearrequests
create Not yet available.
createmultisig
createnewaddress
decrypt
deserialize
encrypt
freeze
getaddressbalance
getaddresshistory
getaddressunspent
getalias
getbalance
getconfig
getfeerate
getmasterprivate
getmerkle
getmpk
getprivatekeys
getpubkeys
getrequest
getseed
getservers
gettransaction
getunusedaddress
history
importprivkey
is_synchronized
ismine
listaddresses
listcontacts
listrequests
listunspent
make_seed
notify
password
payto
paytomany
restore Not yet available.
rmrequest
searchcontacts
serialize
setconfig
setlabel
signmessage
signrequest
signtransaction
sweep
unfreeze
validateaddress
verifymessage
version

Package Tests

To run the go tests use the environment variables: RPCHOST, RPCPORT, RPCUSER, RPCPASSWORD, WALLETPATH, WALLETPASSWORD

RPCHOST=127.0.0.1 RPCPORT=7001 RPCUSER=user RPCPASSWORD=usertest go test

TODO: test coverage needs to be implemented.

Usage

See example/ for more.

License

The MIT License (MIT)

Copyright (c) 2018 konez2k

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Documentation

Overview

A pure Go Electrum (https://electrum.org/) JSON-RPC client library.

Note that Electrum daemon uses a random port by default. In order to use a stable port number, you need to change configuration variable rpcport and restart the daemon:

electrum setconfig rpcport 8001

Electrum will also initialize rpc with "user" as rpcuser and rpcpassword with a random string. To retreive the current values:

electrum getconfig rpcuser
electrum getconfig rpcpassword

Check the exmaples folder (https://github.com/konez2k/go-electrum/tree/master/examples) for additional usage examples.

To run the go tests use the environment variables: RPCHOST, RPCPORT, RPCUSER, RPCPASSWORD, WALLETPATH, WALLETPASSWORD

Index

Constants

View Source
const (

	// COIN represents 1 BTC in sats
	COIN = 100000000
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Address

type Address struct {
	Address string
	Label   string
	Balance string
}

Address represents the structure returned from listaddresses.

type AddressHistory

type AddressHistory struct {
	TxHash string `json:"tx_hash"`
	Height uint64
}

AddressHistory represents a response to getaddresshistory.

type Balance

type Balance struct {
	Unconfirmed float64
	Confirmed   float64
	Unmatured   float64
}

Balance represents a response to getbalance, getaddressbalance.

type Client

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

Client defines the JSON-RPC client structure.

func New

func New(host string, port int, username, password string, useSSL bool) (*Client, error)

New return a new JSON-RPC client.

func (*Client) AddRequest

func (c *Client) AddRequest(amount string) (err error)

AddRequest creates a payment request, using the first unused address of the wallet. The address will be considered as used after this operation. If no payment is received, the address will be considered as unused if the payment request is deleted from the wallet.

configuration variables:

(set with SetConfig/GetConfig)

requests_dir          directory where a bip70 file will be written.
ssl_privkey           Path to your SSL private key, needed to sign the
                      request.
ssl_chain             Chain of SSL certificates, needed for signed requests.
                      Put your certificate at the top and the root CA at the
                      end
url_rewrite           Parameters passed to str.replace(), in order to create
                      the r= part of bitcoin: URIs. Example:
                      "('file:///var/www/','https://electrum.org/')"

TODO: this method is not yet implemented.

func (*Client) AddTransaction

func (c *Client) AddTransaction(tx string) (err error)

AddTransaction adds a transaction to the wallet history. TODO: this method is not yet implemented.

func (*Client) Broadcast

func (c *Client) Broadcast(hex string) (txID string, err error)

Broadcast broadcasts a transaction to the network.

func (*Client) CloseWallet

func (c *Client) CloseWallet(path string) (result bool, err error)

CloseWallet closes the current open wallet.

func (*Client) CreateNewAddress

func (c *Client) CreateNewAddress() (address string, err error)

CreateNewAddress creates a new receiving address, beyond the gap limit of the wallet.

func (*Client) Deserialize

func (c *Client) Deserialize(hex string) (result DeserializedTransaction, err error)

Deserialize deserializes an hexadecimal serialized transaction.

func (*Client) GetAddressBalance

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

GetAddressBalance returns the balance of any address. Note: This is a walletless server query, results are not checked by SPV.

func (*Client) GetAddressHistory

func (c *Client) GetAddressHistory(address string) (history []AddressHistory, err error)

GetAddressHistory returns the transaction history of any address. Note: This is a walletless server query, results are not checked by SPV.

func (*Client) GetAddressUnspent

func (c *Client) GetAddressUnspent(address string) (utxo []UTXO, err error)

GetAddressUnspent returns the UTXO list of any address. Note: This is a walletless server query, results are not checked by SPV.

func (*Client) GetBalance

func (c *Client) GetBalance() (balance Balance, err error)

GetBalance returns the balance of your wallet. TODO: test

func (*Client) GetConfig

func (c *Client) GetConfig(key string) (value interface{}, err error)

GetConfig returns a configuration variable.

func (*Client) GetDaemonStatus

func (c *Client) GetDaemonStatus() (status DaemonStatus, err error)

GetDaemonStatus returns informations about running daemon.

func (*Client) GetFeeRate

func (c *Client) GetFeeRate(feeType FeeType) (fee int, err error)

GetFeeRate returns current suggested fee rate (in sat/kvByte), according to config settings or supplied parameters.

func (*Client) GetMasterPrivate

func (c *Client) GetMasterPrivate() (privKey string, err error)

GetMasterPrivate returns your wallet's master private key.

func (*Client) GetMasterPublicKey

func (c *Client) GetMasterPublicKey() (mpk string, err error)

GetMasterPublicKey returns your wallet's master public key.

func (*Client) GetMerkle

func (c *Client) GetMerkle(txID string, height uint64) (merkle Merkle, err error)

GetMerkle gets merkle branch of a transaction included in a block. Electrum uses this to verify transactions (Simple Payment Verification).

func (*Client) GetPrivateKeys

func (c *Client) GetPrivateKeys(addresses ...string) (privKeys []string, err error)

GetPrivateKeys Get private keys of addresses.

func (*Client) GetPubKeys

func (c *Client) GetPubKeys(address string) (pubkeys []string, err error)

GetPubKeys returns the public keys for a wallet address.

func (*Client) GetSeed

func (c *Client) GetSeed() (seed string, err error)

GetSeed prints the generation seed of your wallet.

func (*Client) GetServers

func (c *Client) GetServers() (servers []Server, err error)

GetServers returns the list of available servers.

func (*Client) GetTransaction

func (c *Client) GetTransaction(txID string) (transaction PayResponse, err error)

GetTransaction retrieves a transaction.

func (*Client) GetUnusedAddress

func (c *Client) GetUnusedAddress() (address string, err 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) History

func (c *Client) History(year *int, showAddresses, showFiat bool) (history History, err error)

History returns the transaction history of your wallet.

func (*Client) IsMine

func (c *Client) IsMine(address string) (result bool, err error)

IsMine checks if address is in wallet. Return true if and only address is in wallet

func (*Client) IsSynchronized

func (c *Client) IsSynchronized() (result bool, err error)

IsSynchronized returns wallet synchronization status.

func (*Client) ListAddresses

func (c *Client) ListAddresses(args ...string) (addresses []Address, err error)

ListAddresses returns a list of all addresses in your wallet. Use optional arguments to filter the results.

receiving       Show only receiving addresses
change          Show only change addresses
frozen          Show only frozen addresses
unused          Show only unused addresses
funded          Show only funded addresses
labels          Show the labels of listed addresses
balance         Show the balances of listed addresses

func (*Client) ListUnspent

func (c *Client) ListUnspent() (addresses []Unspent, err error)

ListUnspent returns a list of unspent transaction outputs in your wallet.

func (*Client) LoadWallet

func (c *Client) LoadWallet(path, password string) (result bool, err error)

LoadWallet loads a new wallet on daemon with specified password.

func (*Client) MakeSeed

func (c *Client) MakeSeed() (seed string, err error)

MakeSeed creates and returns a new seed.

func (*Client) Notify

func (c *Client) Notify(address, url string) (result bool, err error)

Notify watch an address, every time the address changes, an http POST is sent to the URL.

func (*Client) Password

func (c *Client) Password(password, newpassword string) (result bool, err error)

Password changes the wallet password.

func (*Client) PayTo

func (c *Client) PayTo(destination, amount string, args ...string) (result PayResponse, err error)

PayTo creates a transaction.

func (*Client) SetConfig

func (c *Client) SetConfig(key string, value interface{}) (result bool, err error)

SetConfig sets a configuration variable. 'value' may be a string or a Python expression.

func (*Client) SetWalletPassword

func (c *Client) SetWalletPassword(password string)

SetWalletPassword sets the password used on password required JSON-RPC calls.

func (*Client) SignMessage

func (c *Client) SignMessage(address, message string) (signature string, err error)

SignMessage signs a message with a key.

func (*Client) SignTransaction

func (c *Client) SignTransaction(hex, privkey string) (err error)

SignTransaction sign a transaction. The wallet keys will be used unless a private key is provided.

func (*Client) ValidateAddress

func (c *Client) ValidateAddress(address string) (valid bool, err error)

ValidateAddress checks that an address is valid.

func (*Client) VerifyMessage

func (c *Client) VerifyMessage(address, message, signature string) (valid bool, err error)

VerifyMessage verify a signature.

func (*Client) Version

func (c *Client) Version() (version string, err error)

Version returns current version.

type DaemonStatus

type DaemonStatus struct {
	AutoConnect      bool            `json:"auto_connect"`
	BlockchainHeight uint64          `json:"blockchain_height"`
	Connected        bool            `json:"connected"`
	CurrentWallet    string          `json:"current_wallet"`
	FeePerKb         uint64          `json:"fee_per_kb"`
	Path             string          `json:"path"`
	Server           string          `json:"server"`
	ServerHeight     uint64          `json:"server_height"`
	SpvNodes         uint64          `json:"spv_nodes"`
	Version          string          `json:"version"`
	Wallets          map[string]bool `json:"wallets"`
}

DaemonStatus represents a response to daemon status method.

type DeserializedInput added in v1.0.1

type DeserializedInput struct {
	Address     *string `json:"address"`
	NumSig      uint64  `json:"num_sig"`
	PrevoutHash string  `json:"prevout_hash"`
	PrevoutN    int     `json:"prevout_n"`
	ScriptSig   string  `json:"scriptSig"`
	Sequence    uint64  `json:"sequence"`
	Type        string  `json:"type"`
	Witness     string  `json:"witness"`
}

DeserializedInput represents the structure returned from deserialize inputs.

type DeserializedOutput added in v1.0.1

type DeserializedOutput struct {
	Address      string `json:"address"`
	PrevoutN     int    `json:"prevout_n"`
	ScriptPubKey string `json:"scriptPubKey"`
	Type         int    `json:"type"`
	// Value represented in sats
	Value uint64 `json:"value"`
}

DeserializedOutput represents the structure returned from deserialize outputs.

func (*DeserializedOutput) GetValue added in v1.0.2

func (o *DeserializedOutput) GetValue() float64

GetValue returns the output value as float64.

type DeserializedTransaction

type DeserializedTransaction struct {
	Partial   bool                 `json:"partial"`
	Version   int                  `json:"version"`
	SegwitSer bool                 `json:"segwit_ser"`
	Inputs    []DeserializedInput  `json:"inputs"`
	Outputs   []DeserializedOutput `json:"outputs"`
	LockTime  uint64               `json:"lockTime"`
}

DeserializedTransaction represents the structure returned from deserialize method.

type FeeType

type FeeType struct {
	// FeeMethod represents the estimation method to use: static, eta, mempool.
	FeeMethod string
	// FeeLevel represents a float between 0.0 and 1.0, representing fee slider position.
	FeeLevel float64 `json:"fee_level,omitempty"`
}

FeeType defines a structure for getfeerate method.

type History

type History struct {
	Summary      HistorySummary       `json:"summary"`
	Transactions []HistoryTransaction `json:"transactions"`
}

History defines a structure for history method.

type HistorySummary

type HistorySummary struct {
	CapitalGains     string    `json:"capita_gains"`
	EndBalance       string    `json:"end_balance"`
	EndDate          *JSONDate `json:"end_date"`
	EndFiatBalance   string    `json:"end_fiat_balance"`
	EndFiatValue     string    `json:"end_fiat_value"`
	Expenditures     string    `json:"expenditures"`
	FiatExpenditures string    `json:"fiat_expenditures"`
	FiatIncome       string    `json:"fiat_income"`
	Income           string    `json:"income"`
	StartBalance     string    `json:"start_balance"`
	StartDate        *JSONDate `json:"start_date"`
	StartFiatBalance string    `json:"start_fiat_balance"`
	StartFiatValue   string    `json:"start_fiat_value"`
	UnrealizedGains  string    `json:"unrealized_gains"`
}

HistorySummary defines a structure for history summary method.

type HistoryTransaction

type HistoryTransaction struct {
	Balance       string              `json:"balance"`
	Confirmations uint64              `json:"confirmations"`
	Date          *JSONDate           `json:"date"`
	FiatDefault   bool                `json:"fiat_default"`
	FiatValue     string              `json:"fiat_value"`
	Height        uint64              `json:"height"`
	Inputs        []TransactionInput  `json:"inputs"`
	Label         string              `json:"label"`
	Outputs       []TransactionOutput `json:"outputs"`
	Timestamp     uint64              `json:"timestamp"`
	TxID          string              `json:"txid"`
	Value         string              `json:"value"`
}

HistoryTransaction defines a structure for history transactions method.

type JSONDate

type JSONDate time.Time

JSONDate defines a custom time alias for json unmarshalling.

func (JSONDate) Format

func (j JSONDate) Format(s string) string

Format prints your json date

func (JSONDate) MarshalJSON

func (j JSONDate) MarshalJSON() ([]byte, error)

MarshalJSON returns a JSON version of JSONDate.

func (*JSONDate) UnmarshalJSON

func (j *JSONDate) UnmarshalJSON(b []byte) error

UnmarshalJSON implements custom unmarshal for json date.

type Merkle

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

Merkle represents a response to getmerkle.

type NotifyRequest

type NotifyRequest struct {
	Address string  `json:"address"`
	Status  *string `json:"status"`
}

NotifyRequest represents the structure used by electrum notify POST call.

type PayResponse

type PayResponse struct {
	Hex      string `json:"hex"`
	Complete bool   `json:"complete"`
	Final    bool   `json:"final"`
}

PayResponse represents the structure returned from payto, gettransaction method.

type Server

type Server struct {
	Address string `json:"address"`
	Pruning string `json:"pruning"`
	S       string `json:"s"`
	T       string `json:"t"`
	Version string `json:"version"`
}

Server represents the structure returned from getservers method.

type TransactionInput

type TransactionInput struct {
	PrevoutHash string  `json:"prevout_hash"`
	PrevoutN    int     `json:"prevout_n"`
	ScriptSig   string  `json:"scriptSig"`
	Sequence    uint64  `json:"sequence"`
	Type        string  `json:"type"`
	Address     *string `json:"address"`
	NumSig      uint64  `json:"num_sig"`
}

TransactionInput defines a structure for history transactions inputs.

type TransactionOutput

type TransactionOutput struct {
	Address      string `json:"address"`
	Value        string `json:"value"`
	Type         int    `json:"type"`
	ScriptPubKey string `json:"scriptPubKey"`
	PrevoutN     int    `json:"prevout_n"`
}

TransactionOutput defines a structure for history transactions outputs.

type UTXO

type UTXO struct {
	Value  uint64 // value in satoshis
	TxHash string `json:"tx_hash"`
	TxPos  int    `json:"tx_pos"`
	Height uint64 `json:"height"`
}

UTXO represents all unspent transaction outputs (getaddressunspent).

type Unspent

type Unspent struct {
	Address     string `json:"address"`
	Coinbase    bool   `json:"coinbase"`
	Height      uint64 `json:"height"`
	PrevoutHash string `json:"prevout_hash"`
	PrevoutN    int    `json:"prevout_n"`
	Value       string `json:"value"`
}

Unspent represents the unspent output returns from listunspent.

Jump to

Keyboard shortcuts

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