chain

package
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Mar 20, 2024 License: MIT Imports: 28 Imported by: 0

Documentation

Index

Constants

View Source
const (

	// DefaultGetRawTxBatchSize specifies the default number of requests to
	// be batched before sending them to the bitcoind client.
	DefaultGetRawTxBatchSize = 1000

	// DefaultBatchWaitInterval defines the default time to sleep between
	// each batched calls.
	DefaultBatchWaitInterval = 1 * time.Second
)

Variables

View Source
var (
	// ErrBitcoindClientShuttingDown is an error returned when we attempt
	// to receive a notification for a specific item and the bitcoind client
	// is in the middle of shutting down.
	ErrBitcoindClientShuttingDown = errors.New("client is shutting down")
)
View Source
var ErrBitcoindStartTimeout = errors.New("bitcoind start timeout")

ErrBitcoindStartTimeout is returned when the bitcoind daemon fails to load and verify blocks under 30s during startup.

Functions

func BackEnds

func BackEnds() []string

BackEnds returns a list of the available back ends. TODO: Refactor each into a driver and use dynamic registration.

Types

type BitcoindClient

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

BitcoindClient represents a persistent client connection to a bitcoind server for information regarding the current best block chain.

func (*BitcoindClient) BackEnd

func (c *BitcoindClient) BackEnd() string

BackEnd returns the name of the driver.

func (*BitcoindClient) BlockStamp

func (c *BitcoindClient) BlockStamp() (*waddrmgr.BlockStamp, error)

BlockStamp returns the latest block notified by the client, or an error if the client has been shut down.

func (*BitcoindClient) FilterBlocks

FilterBlocks scans the blocks contained in the FilterBlocksRequest for any addresses of interest. Each block will be fetched and filtered sequentially, returning a FilterBlocksReponse for the first block containing a matching address. If no matches are found in the range of blocks requested, the returned response will be nil.

NOTE: This is part of the chain.Interface interface.

func (*BitcoindClient) GetBestBlock

func (c *BitcoindClient) GetBestBlock() (*chainhash.Hash, int32, error)

GetBestBlock returns the highest block known to bitcoind.

func (*BitcoindClient) GetBlock

func (c *BitcoindClient) GetBlock(hash *chainhash.Hash) (*wire.MsgBlock, error)

GetBlock returns a block from the hash.

func (*BitcoindClient) GetBlockHash

func (c *BitcoindClient) GetBlockHash(height int64) (*chainhash.Hash, error)

GetBlockHash returns a block hash from the height.

func (*BitcoindClient) GetBlockHeader

func (c *BitcoindClient) GetBlockHeader(
	hash *chainhash.Hash) (*wire.BlockHeader, error)

GetBlockHeader returns a block header from the hash.

func (*BitcoindClient) GetBlockHeaderVerbose

func (c *BitcoindClient) GetBlockHeaderVerbose(
	hash *chainhash.Hash) (*btcjson.GetBlockHeaderVerboseResult, error)

GetBlockHeaderVerbose returns a block header from the hash.

func (*BitcoindClient) GetBlockHeight

func (c *BitcoindClient) GetBlockHeight(hash *chainhash.Hash) (int32, error)

GetBlockHeight returns the height for the hash, if known, or returns an error.

func (*BitcoindClient) GetBlockVerbose

func (c *BitcoindClient) GetBlockVerbose(
	hash *chainhash.Hash) (*btcjson.GetBlockVerboseResult, error)

GetBlockVerbose returns a verbose block from the hash.

func (*BitcoindClient) GetRawMempool

func (c *BitcoindClient) GetRawMempool() ([]*chainhash.Hash, error)

GetRawMempool returns the raw mempool.

func (*BitcoindClient) GetRawTransaction

func (c *BitcoindClient) GetRawTransaction(
	hash *chainhash.Hash) (*btcutil.Tx, error)

GetRawTransaction returns a `btcutil.Tx` from the tx hash.

func (*BitcoindClient) GetRawTransactionVerbose

func (c *BitcoindClient) GetRawTransactionVerbose(
	hash *chainhash.Hash) (*btcjson.TxRawResult, error)

GetRawTransactionVerbose returns a TxRawResult from the tx hash.

func (*BitcoindClient) GetTxOut

func (c *BitcoindClient) GetTxOut(txHash *chainhash.Hash, index uint32,
	mempool bool) (*btcjson.GetTxOutResult, error)

GetTxOut returns a txout from the outpoint info provided.

func (*BitcoindClient) IsCurrent

func (c *BitcoindClient) IsCurrent() bool

IsCurrent returns whether the chain backend considers its view of the network as "current".

func (*BitcoindClient) LoadTxFilter

func (c *BitcoindClient) LoadTxFilter(reset bool, filters ...interface{}) error

LoadTxFilter uses the given filters to what we should match transactions against to determine if they are relevant to the client. The reset argument is used to reset the current filters.

The current filters supported are of the following types:

[]btcutil.Address
[]wire.OutPoint
[]*wire.OutPoint
map[wire.OutPoint]btcutil.Address
[]chainhash.Hash
[]*chainhash.Hash

func (*BitcoindClient) Notifications

func (c *BitcoindClient) Notifications() <-chan interface{}

Notifications returns a channel to retrieve notifications from.

NOTE: This is part of the chain.Interface interface.

func (*BitcoindClient) NotifyBlocks

func (c *BitcoindClient) NotifyBlocks() error

NotifyBlocks allows the chain backend to notify the caller whenever a block is connected or disconnected.

NOTE: This is part of the chain.Interface interface.

func (*BitcoindClient) NotifyReceived

func (c *BitcoindClient) NotifyReceived(addrs []btcutil.Address) error

NotifyReceived allows the chain backend to notify the caller whenever a transaction pays to any of the given addresses.

NOTE: This is part of the chain.Interface interface.

func (*BitcoindClient) NotifySpent

func (c *BitcoindClient) NotifySpent(outPoints []*wire.OutPoint) error

NotifySpent allows the chain backend to notify the caller whenever a transaction spends any of the given outpoints.

func (*BitcoindClient) NotifyTx

func (c *BitcoindClient) NotifyTx(txids []chainhash.Hash) error

NotifyTx allows the chain backend to notify the caller whenever any of the given transactions confirm within the chain.

func (*BitcoindClient) RawRequest added in v0.0.4

func (c *BitcoindClient) RawRequest(method string, params []json.RawMessage) (json.RawMessage, error)

RawRequest allows the caller to send a raw or custom request to the server. This method may be used to send and receive requests and responses for requests that are not handled by this client package, or to proxy partially unmarshaled requests to another JSON-RPC server if a request cannot be handled directly.

func (*BitcoindClient) RawRequestAsync added in v0.0.4

func (c *BitcoindClient) RawRequestAsync(method string, params []json.RawMessage) rpcclient.FutureRawResult

func (*BitcoindClient) Rescan

func (c *BitcoindClient) Rescan(blockHash *chainhash.Hash,
	addresses []btcutil.Address, outPoints map[wire.OutPoint]btcutil.Address) error

Rescan rescans from the block with the given hash until the current block, after adding the passed addresses and outpoints to the client's watch list.

func (*BitcoindClient) RescanBlocks

func (c *BitcoindClient) RescanBlocks(
	blockHashes []chainhash.Hash) ([]btcjson.RescannedBlock, error)

RescanBlocks rescans any blocks passed, returning only the blocks that matched as []btcjson.BlockDetails.

func (*BitcoindClient) SendRawTransaction

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

SendRawTransaction sends a raw transaction via bitcoind.

func (*BitcoindClient) SetBirthday

func (c *BitcoindClient) SetBirthday(t time.Time)

SetBirthday sets the birthday of the bitcoind rescan client.

NOTE: This should be done before the client has been started in order for it to properly carry its duties.

func (*BitcoindClient) Start

func (c *BitcoindClient) Start() error

Start initializes the bitcoind rescan client using the backing bitcoind connection and starts all goroutines necessary in order to process rescans and ZMQ notifications.

NOTE: This is part of the chain.Interface interface.

func (*BitcoindClient) Stop

func (c *BitcoindClient) Stop()

Stop stops the bitcoind rescan client from processing rescans and ZMQ notifications.

NOTE: This is part of the chain.Interface interface.

func (*BitcoindClient) TestMempoolAccept

func (c *BitcoindClient) TestMempoolAccept(txns []*wire.MsgTx,
	maxFeeRate float64) ([]*btcjson.TestMempoolAcceptResult, error)

TestMempoolAcceptCmd returns result of mempool acceptance tests indicating if raw transaction(s) would be accepted by mempool.

NOTE: This is part of the chain.Interface interface.

func (*BitcoindClient) WaitForShutdown

func (c *BitcoindClient) WaitForShutdown()

WaitForShutdown blocks until the client has finished disconnecting and all handlers have exited.

NOTE: This is part of the chain.Interface interface.

type BitcoindConfig

type BitcoindConfig struct {
	// ChainParams are the chain parameters the bitcoind server is running
	// on.
	ChainParams *chaincfg.Params

	// Host is the IP address and port of the bitcoind's RPC server.
	Host string

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

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

	// ZMQConfig holds the configuration settings required for setting up
	// zmq connections to bitcoind.
	ZMQConfig *ZMQConfig

	// PollingConfig holds the configuration settings required for using
	// RPC polling for block and transaction notifications instead of the
	// ZMQ interface.
	PollingConfig *PollingConfig

	// Dialer is a closure we'll use to dial Bitcoin peers. If the chain
	// backend is running over Tor, this must support dialing peers over Tor
	// as well.
	Dialer Dialer

	// PrunedModeMaxPeers is the maximum number of peers we'll attempt to
	// retrieve pruned blocks from.
	//
	// NOTE: This only applies for pruned bitcoind nodes.
	PrunedModeMaxPeers int
}

BitcoindConfig contains all of the parameters required to establish a connection to a bitcoind's RPC.

type BitcoindConn

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

BitcoindConn represents a persistent client connection to a bitcoind node that listens for events read from a ZMQ connection.

func NewBitcoindConn

func NewBitcoindConn(cfg *BitcoindConfig) (*BitcoindConn, error)

NewBitcoindConn creates a client connection to the node described by the host string. The ZMQ connections are established immediately to ensure liveness. If the remote node does not operate on the same bitcoin network as described by the passed chain parameters, the connection will be disconnected.

func (*BitcoindConn) AddClient

func (c *BitcoindConn) AddClient(client *BitcoindClient)

AddClient adds a client to the set of active rescan clients of the current chain connection. This allows the connection to include the specified client in its notification delivery.

NOTE: This function is safe for concurrent access.

func (*BitcoindConn) GetBlock

func (c *BitcoindConn) GetBlock(hash *chainhash.Hash) (*wire.MsgBlock, error)

GetBlock returns a raw block from the server given its hash. If the server has already pruned the block, it will be retrieved from one of its peers.

func (*BitcoindConn) NewBitcoindClient

func (c *BitcoindConn) NewBitcoindClient() *BitcoindClient

NewBitcoindClient returns a bitcoind client using the current bitcoind connection. This allows us to share the same connection using multiple clients.

func (*BitcoindConn) RemoveClient

func (c *BitcoindConn) RemoveClient(id uint64)

RemoveClient removes the client with the given ID from the set of active rescan clients. Once removed, the client will no longer receive block and transaction notifications from the chain connection.

NOTE: This function is safe for concurrent access.

func (*BitcoindConn) Start

func (c *BitcoindConn) Start() error

Start attempts to establish a RPC and ZMQ connection to a bitcoind node. If successful, a goroutine is spawned to read events from the ZMQ connection. It's possible for this function to fail due to a limited number of connection attempts. This is done to prevent waiting forever on the connection to be established in the case that the node is down.

func (*BitcoindConn) Stop

func (c *BitcoindConn) Stop()

Stop terminates the RPC and ZMQ connection to a bitcoind node and removes any active rescan clients.

type BitcoindEvents

type BitcoindEvents interface {
	// TxNotifications will return a channel which will deliver new
	// transactions.
	TxNotifications() <-chan *wire.MsgTx

	// BlockNotifications will return a channel which will deliver new
	// blocks.
	BlockNotifications() <-chan *wire.MsgBlock

	// LookupInputSpend will return the transaction found in mempool that
	// spends the given input.
	LookupInputSpend(op wire.OutPoint) (chainhash.Hash, bool)

	// Start will kick off any goroutines required for operation.
	Start() error

	// Stop will clean up any resources and goroutines.
	Stop() error
}

BitcoindEvents is the interface that must be satisfied by any type that serves bitcoind block and transactions events.

func NewBitcoindEventSubscriber

func NewBitcoindEventSubscriber(cfg *BitcoindConfig, client *rpcclient.Client,
	bClient batchClient) (BitcoindEvents, error)

NewBitcoindEventSubscriber initialises a new BitcoinEvents object impl depending on the config passed.

type BlockConnected

type BlockConnected wtxmgr.BlockMeta

BlockConnected is a notification for a newly-attached block to the best chain.

type BlockDisconnected

type BlockDisconnected wtxmgr.BlockMeta

BlockDisconnected is a notifcation that the block described by the BlockStamp was reorganized out of the best chain.

type ClientConnected

type ClientConnected struct{}

ClientConnected is a notification for when a client connection is opened or reestablished to the chain server.

type Dialer

type Dialer = func(string) (net.Conn, error)

Dialer represents a way to dial Bitcoin peers. If the chain backend is running over Tor, this must support dialing peers over Tor as well.

type FilterBlocksRequest

type FilterBlocksRequest struct {
	Blocks           []wtxmgr.BlockMeta
	ExternalAddrs    map[waddrmgr.ScopedIndex]btcutil.Address
	InternalAddrs    map[waddrmgr.ScopedIndex]btcutil.Address
	WatchedOutPoints map[wire.OutPoint]btcutil.Address
}

FilterBlocksRequest specifies a range of blocks and the set of internal and external addresses of interest, indexed by corresponding scoped-index of the child address. A global set of watched outpoints is also included to monitor for spends.

type FilterBlocksResponse

type FilterBlocksResponse struct {
	BatchIndex         uint32
	BlockMeta          wtxmgr.BlockMeta
	FoundExternalAddrs map[waddrmgr.KeyScope]map[uint32]struct{}
	FoundInternalAddrs map[waddrmgr.KeyScope]map[uint32]struct{}
	FoundOutPoints     map[wire.OutPoint]btcutil.Address
	RelevantTxns       []*wire.MsgTx
}

FilterBlocksResponse reports the set of all internal and external addresses found in response to a FilterBlockRequest, any outpoints found that correspond to those addresses, as well as the relevant transactions that can modify the wallet's balance. The index of the block within the FilterBlocksRequest is returned, such that the caller can reinitiate a request for the subsequent block after updating the addresses of interest.

type FilteredBlockConnected

type FilteredBlockConnected struct {
	Block       *wtxmgr.BlockMeta
	RelevantTxs []*wtxmgr.TxRecord
}

FilteredBlockConnected is an alternate notification that contains both block and relevant transaction information in one struct, which allows atomic updates.

type PollingConfig

type PollingConfig struct {
	// BlockPollingInterval is the interval that will be used to poll
	// bitcoind for new blocks.
	BlockPollingInterval time.Duration

	// TxPollingInterval is the interval that will be used to poll bitcoind
	// for new transactions. If a jitter factor is configed, it will be
	// applied to this value to provide randomness in the range,
	// - max: TxPollingInterval * (1 + TxPollingIntervalJitter)
	// - min: TxPollingInterval * (1 - TxPollingIntervalJitter)
	TxPollingInterval time.Duration

	// TxPollingIntervalScale defines a factor that's used to simulates
	// jitter by scaling TxPollingInterval with it. This value must be no
	// less than 0. Default to 0, meaning no jitter will be applied.
	TxPollingIntervalJitter float64

	// RPCBatchSize defines the number of RPC requests to be batches before
	// sending them to the bitcoind node.
	RPCBatchSize uint32

	// RPCBatchInterval defines the time to wait before attempting the next
	// batch when the current one finishes.
	RPCBatchInterval time.Duration
}

PollingConfig holds all the config options used for setting up bitcoindRPCPollingEvents.

type RelevantTx

type RelevantTx struct {
	TxRecord *wtxmgr.TxRecord
	Block    *wtxmgr.BlockMeta // nil if unmined
}

RelevantTx is a notification for a transaction which spends wallet inputs or pays to a watched address.

type RescanFinished

type RescanFinished struct {
	Hash   *chainhash.Hash
	Height int32
	Time   time.Time
}

RescanFinished is a notification that a previous rescan request has finished.

type RescanProgress

type RescanProgress struct {
	Hash   chainhash.Hash
	Height int32
	Time   time.Time
}

RescanProgress is a notification describing the current status of an in-progress rescan.

type ZMQConfig

type ZMQConfig struct {
	// ZMQBlockHost is the IP address and port of the bitcoind's rawblock
	// listener.
	ZMQBlockHost string

	// ZMQTxHost is the IP address and port of the bitcoind's rawtx
	// listener.
	ZMQTxHost string

	// ZMQReadDeadline represents the read deadline we'll apply when reading
	// ZMQ messages from either subscription.
	ZMQReadDeadline time.Duration

	// MempoolPollingInterval is the interval that will be used to poll
	// bitcoind to update the local mempool. If a jitter factor is
	// configed, it will be
	// applied to this value to provide randomness in the range,
	// - max: MempoolPollingInterval * (1 + PollingIntervalJitter)
	// - min: MempoolPollingInterval * (1 - PollingIntervalJitter)
	//
	// TODO(yy): replace this temp config with SEQUENCE check.
	MempoolPollingInterval time.Duration

	// PollingIntervalJitter a factor that's used to simulates jitter by
	// scaling MempoolPollingInterval with it. This value must be no less
	// than 0. Default to 0, meaning no jitter will be applied.
	//
	// TODO(yy): replace this temp config with SEQUENCE check.
	PollingIntervalJitter float64

	// RPCBatchSize defines the number of RPC requests to be batches before
	// sending them to the bitcoind node.
	RPCBatchSize uint32

	// RPCBatchInterval defines the time to wait before attempting the next
	// batch when the current one finishes.
	RPCBatchInterval time.Duration
}

ZMQConfig holds all the config values needed to set up a ZMQ connection to bitcoind.

Jump to

Keyboard shortcuts

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