lndclient

package module
v1.0.1-0...-04a9e7f Latest Latest
Warning

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

Go to latest
Published: Aug 15, 2021 License: MIT Imports: 50 Imported by: 0

README

Golang client library for lnd

lndclient is a golang native wrapper for lnd's gRPC interface.

Compatibility matrix

This library depends heavily on lnd for obvious reasons. To support backward compatibility with older versions of lnd, we use different branches for different versions. There are two "levels" of depending on a version of lnd:

  • Code level dependency: This is the version of lnd that is pulled in when compiling lndclient. It is defined in go.mod. This usually is the latest released version of lnd, because its RPC definitions are kept backward compatible. This means that a new field added in the latest version of lnd might already be available in lndclient's code, but whether or not that field will actually be set at run time is dependent on the actual version of lnd that's being connected to.
  • RPC level dependency: This is defined in minimalCompatibleVersion in lnd_services.go. When connecting to lnd, the version returned by its version service is checked and if it doesn't meet the minimal required version defined in lnd_services.go, an error will be returned. Users of lndclient can also overwrite this minimum required version when creating a new client.

The current compatibility matrix reads as follows:

lndclient git tag lnd version in go.mod minimum required lnd version
v0.12.0-0 1efef51268d6 v0.11.1-beta
master / v0.11.1-5 v0.11.1-beta v0.11.1-beta

By default, lndclient requires (and enforces) the following RPC subservers to be active in lnd:

  • signrpc
  • walletrpc
  • chainrpc
  • invoicesrpc

Branch strategy

We follow the following strategy to maintain different versions of this library that have different lnd compatibilities:

  1. The master is always backward compatible with the last major version.
  2. We create branches for all minor versions and future major versions and merge PRs to those branches, if the features require that version to work.
  3. We rebase the branches if needed and use tags to track versions that we depend on in other projects.
  4. Once a new major version of lnd is final, all branches of minor versions lower than that are merged into master.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoRouteFound is returned if we can't find a path with the passed
	// parameters.
	ErrNoRouteFound = errors.New("no route found")

	// PaymentResultUnknownPaymentHash is the string result returned by
	// SendPayment when the final node indicates the hash is unknown.
	PaymentResultUnknownPaymentHash = "UnknownPaymentHash"

	// PaymentResultSuccess is the string result returned by SendPayment
	// when the payment was successful.
	PaymentResultSuccess = ""

	// PaymentResultAlreadyPaid is the string result returned by SendPayment
	// when the payment was already completed in a previous SendPayment
	// call.
	PaymentResultAlreadyPaid = channeldb.ErrAlreadyPaid.Error()

	// PaymentResultInFlight is the string result returned by SendPayment
	// when the payment was initiated in a previous SendPayment call and
	// still in flight.
	PaymentResultInFlight = channeldb.ErrPaymentInFlight.Error()
)
View Source
var (

	// ErrVersionCheckNotImplemented is the error that is returned if the
	// version RPC is not implemented in lnd. This means the version of lnd
	// is lower than v0.10.0-beta.
	ErrVersionCheckNotImplemented = errors.New("version check not " +
		"implemented, need minimum lnd version of v0.10.0-beta")

	// ErrVersionIncompatible is the error that is returned if the connected
	// lnd instance is not supported.
	ErrVersionIncompatible = errors.New("version incompatible")

	// ErrBuildTagsMissing is the error that is returned if the
	// connected lnd instance does not have all built tags activated that
	// are required.
	ErrBuildTagsMissing = errors.New("build tags missing")

	// DefaultBuildTags is the list of all subserver build tags that are
	// required for lndclient to work.
	DefaultBuildTags = []string{
		"signrpc", "walletrpc", "chainrpc", "invoicesrpc",
	}
)

Functions

func IsUnlockError

func IsUnlockError(err error) bool

IsUnlockError returns true if the given error is one that lnd returns when its wallet is locked, either before version 0.13 or after.

func NewBasicClient

func NewBasicClient(lndHost, tlsPath, macDir, network string,
	basicOptions ...BasicClientOption) (

	lnrpc.LightningClient, error)

NewBasicClient creates a new basic gRPC client to lnd. We call this client "basic" as it falls back to expected defaults if the arguments aren't provided.

func NewBasicConn

func NewBasicConn(lndHost, tlsPath, macDir, network string,
	basicOptions ...BasicClientOption) (

	*grpc.ClientConn, error)

NewBasicConn creates a new basic gRPC connection to lnd. We call this connection "basic" as it falls back to expected defaults if the arguments aren't provided.

func NewOutpointFromStr

func NewOutpointFromStr(outpoint string) (*wire.OutPoint, error)

NewOutpointFromStr creates an outpoint from a string with the format txid:index.

func UseLogger

func UseLogger(logger btclog.Logger)

UseLogger uses a specified Logger to output package logging info. This should be used in preference to SetLogWriter if the caller is also using btclog.

func VersionString

func VersionString(version *verrpc.Version) string

VersionString returns a nice, human readable string of a version returned by the VersionerClient, including all build tags.

func VersionStringShort

func VersionStringShort(version *verrpc.Version) string

VersionStringShort returns a nice, human readable string of a version returned by the VersionerClient.

Types

type BasicClientOption

type BasicClientOption func(*basicClientOptions)

BasicClientOption is a functional option argument that allows adding arbitrary lnd basic client configuration overrides, without forcing existing users of NewBasicClient to update their invocation. These are always processed in order, with later options overriding earlier ones.

func MacFilename

func MacFilename(macFilename string) BasicClientOption

MacFilename is a basic client option that sets the name of the macaroon file to use.

type ChainNotifierClient

type ChainNotifierClient interface {
	RegisterBlockEpochNtfn(ctx context.Context) (
		chan int32, chan error, error)

	RegisterConfirmationsNtfn(ctx context.Context, txid *chainhash.Hash,
		pkScript []byte, numConfs, heightHint int32) (
		chan *chainntnfs.TxConfirmation, chan error, error)

	RegisterSpendNtfn(ctx context.Context,
		outpoint *wire.OutPoint, pkScript []byte, heightHint int32) (
		chan *chainntnfs.SpendDetail, chan error, error)
}

ChainNotifierClient exposes base lightning functionality.

type ChannelBalance

type ChannelBalance struct {
	// Balance is the sum of all open channels balances denominated.
	Balance btcutil.Amount

	// PendingBalance is the sum of all pending channel balances.
	PendingBalance btcutil.Amount
}

ChannelBalance contains information about our channel balances.

type ChannelCloseUpdate

type ChannelCloseUpdate struct {
	// ChannelID is the short channel id of the closed channel.
	ChannelID lnwire.ShortChannelID

	// ChannelPoint is the funding channel point of the closed channel.
	ChannelPoint wire.OutPoint

	// Capacity is the capacity of the closed channel.
	Capacity btcutil.Amount

	// ClosedHeight is the block height when the channel was closed.
	ClosedHeight uint32
}

ChannelCloseUpdate holds a channel close graph topology update.

type ChannelClosedUpdate

type ChannelClosedUpdate struct {
	// CloseTx is the closing transaction id.
	CloseTx chainhash.Hash
}

ChannelClosedUpdate indicates that our channel close has confirmed on chain.

func (*ChannelClosedUpdate) CloseTxid

func (p *ChannelClosedUpdate) CloseTxid() chainhash.Hash

CloseTxid returns the closing txid of the channel.

type ChannelConstraints

type ChannelConstraints struct {
	// CsvDelay is the relative CSV delay expressed in blocks.
	CsvDelay uint32

	// Reserve is the minimum balance that the node must maintain.
	Reserve btcutil.Amount

	// DustLimit is the dust limit for the channel commitment.
	DustLimit btcutil.Amount

	// MaxPendingAmt is the maximum amount that may be pending on the
	// channel.
	MaxPendingAmt lnwire.MilliSatoshi

	// MinHtlc is the minimum htlc size that will be accepted on the
	// channel.
	MinHtlc lnwire.MilliSatoshi

	// MaxAcceptedHtlcs is the maximum number of htlcs that the node will
	// accept from its peer.
	MaxAcceptedHtlcs uint32
}

ChannelConstraints contains information about the restraints place on a channel commit for a particular node.

type ChannelEdge

type ChannelEdge struct {
	// ChannelID is the unique channel ID for the channel. The first 3 bytes
	// are the block height, the next 3 the index within the block, and the
	// last 2 bytes are the output index for the channel.
	ChannelID uint64

	// ChannelPoint is the funding outpoint of the channel.
	ChannelPoint string

	// Capacity is the total channel capacity.
	Capacity btcutil.Amount

	// Node1 holds the vertex of the first node.
	Node1 route.Vertex

	// Node2 holds the vertex of the second node.
	Node2 route.Vertex

	// Node1Policy holds the edge policy for the Node1 -> Node2 edge.
	Node1Policy *RoutingPolicy

	// Node2Policy holds the edge policy for the Node2 -> Node1 edge.
	Node2Policy *RoutingPolicy
}

ChannelEdge holds the channel edge information and routing policies.

type ChannelEdgeUpdate

type ChannelEdgeUpdate struct {
	// ChannelID is the short channel id.
	ChannelID lnwire.ShortChannelID

	// ChannelPoint is the funding channel point.
	ChannelPoint wire.OutPoint

	// Capacity is the channel capacity.
	Capacity btcutil.Amount

	// RoutingPolicy is the actual routing policy for the channel.
	RoutingPolicy RoutingPolicy

	// AdvertisingNode is the node who announced the update.
	AdvertisingNode route.Vertex

	// ConnectingNode is the other end of the channel.
	ConnectingNode route.Vertex
}

ChannelEdgeUpdate holds a channel edge graph topology update.

type ChannelEventUpdate

type ChannelEventUpdate struct {
	// UpdateType encodes the update type. Depending on the type other
	// members may be nil.
	UpdateType ChannelUpdateType

	// ChannelPoints holds the channel point for the updated channel.
	ChannelPoint *wire.OutPoint

	// OpenedChannelInfo holds the channel info for a newly opened channel.
	OpenedChannelInfo *ChannelInfo

	// ClosedChannelInfo holds the channel info for a newly closed channel.
	ClosedChannelInfo *ClosedChannel
}

ChannelEventUpdate holds the data fields and type for a particular channel update event.

type ChannelInfo

type ChannelInfo struct {
	// ChannelPoint is the funding outpoint of the channel.
	ChannelPoint string

	// Active indicates whether the channel is active.
	Active bool

	// ChannelID holds the unique channel ID for the channel. The first 3 bytes
	// are the block height, the next 3 the index within the block, and the last
	// 2 bytes are the /output index for the channel.
	ChannelID uint64

	// PubKeyBytes is the raw bytes of the public key of the remote node.
	PubKeyBytes route.Vertex

	// Capacity is the total amount of funds held in this channel.
	Capacity btcutil.Amount

	// LocalBalance is the current balance of this node in this channel.
	LocalBalance btcutil.Amount

	// RemoteBalance is the counterparty's current balance in this channel.
	RemoteBalance btcutil.Amount

	// UnsettledBalance is the total amount on this channel that is
	// unsettled.
	UnsettledBalance btcutil.Amount

	// Initiator indicates whether we opened the channel or not.
	Initiator bool

	// Private indicates that the channel is private.
	Private bool

	// LifeTime is the total amount of time we have monitored the peer's
	// online status for.
	LifeTime time.Duration

	// Uptime is the total amount of time the peer has been observed as
	// online over its lifetime.
	Uptime time.Duration

	// TotalSent is the total amount sent over this channel for our own
	// payments.
	TotalSent btcutil.Amount

	// TotalReceived is the total amount received over this channel for our
	// own receipts.
	TotalReceived btcutil.Amount

	// NumUpdates is the number of updates we have had on this channel.
	NumUpdates uint64

	// NumPendingHtlcs is the count of pending htlcs on this channel.
	NumPendingHtlcs int

	// PendingHtlcs stores the pending HTLCs (amount and direction).
	PendingHtlcs []PendingHtlc

	// CSVDelay is the csv delay for our funds.
	CSVDelay uint64

	// FeePerKw is the current fee per kweight of the commit fee.
	FeePerKw chainfee.SatPerKWeight

	// CommitWeight is the weight of the commit.
	CommitWeight int64

	// CommitFee is the current commitment's fee.
	CommitFee btcutil.Amount

	// LocalConstraints is the set of constraints for the local node.
	LocalConstraints *ChannelConstraints

	// RemoteConstraints is the set of constraints for the remote node.
	RemoteConstraints *ChannelConstraints

	// CloseAddr is the optional upfront shutdown address set for a
	// channel.
	CloseAddr btcutil.Address
}

ChannelInfo stores unpacked per-channel info.

type ChannelUpdateType

type ChannelUpdateType uint8

ChannelUpdateType encodes the type of update for a channel update event.

const (
	// PendingOpenChannelUpdate indicates that the channel event holds
	// information about a recently opened channel still in pending state.
	PendingOpenChannelUpdate ChannelUpdateType = iota

	// OpenChannelUpdate indicates that the channel event holds information
	// about a channel that has been opened.
	OpenChannelUpdate

	// ClosedChannelUpdate indicates that the channel event holds
	// information about a closed channel.
	ClosedChannelUpdate

	// ActiveChannelUpdate indicates that the channel event holds
	// information about a channel that became active.
	ActiveChannelUpdate

	// InactiveChannelUpdate indicates that the channel event holds
	// information about a channel that became inactive.
	InactiveChannelUpdate
)

type CloseChannelUpdate

type CloseChannelUpdate interface {
	// CloseTxid returns the closing txid of the channel.
	CloseTxid() chainhash.Hash
}

CloseChannelUpdate is an interface implemented by channel close updates.

type CloseType

type CloseType uint8

CloseType is an enum which represents the types of closes our channels may have. This type maps to the rpc value.

const (
	// CloseTypeCooperative represents cooperative closes.
	CloseTypeCooperative CloseType = iota

	// CloseTypeLocalForce represents force closes that we initiated.
	CloseTypeLocalForce

	// CloseTypeRemoteForce represents force closes that our peer initiated.
	CloseTypeRemoteForce

	// CloseTypeBreach represents breach closes from our peer.
	CloseTypeBreach

	// CloseTypeFundingCancelled represents channels which were never
	// created because their funding transaction was cancelled.
	CloseTypeFundingCancelled

	// CloseTypeAbandoned represents a channel that was abandoned.
	CloseTypeAbandoned
)

func (CloseType) String

func (c CloseType) String() string

String returns the string representation of a close type.

type ClosedChannel

type ClosedChannel struct {
	// ChannelPoint is the funding outpoint of the channel.
	ChannelPoint string

	// ChannelID holds the unique channel ID for the channel. The first 3
	// bytes are the block height, the next 3 the index within the block,
	// and the last 2 bytes are the output index for the channel.
	ChannelID uint64

	// ClosingTxHash is the tx hash of the close transaction for the channel.
	ClosingTxHash string

	// CloseType is the type of channel closure.
	CloseType CloseType

	// CloseHeight is the height that the channel was closed at.
	CloseHeight uint32

	// OpenInitiator is true if we opened the channel. This value is not
	// always available (older channels do not have it).
	OpenInitiator Initiator

	// Initiator indicates which party initiated the channel close. Since
	// this value is not always set in the rpc response, we also make a best
	// effort attempt to set it based on CloseType.
	CloseInitiator Initiator

	// PubKeyBytes is the raw bytes of the public key of the remote node.
	PubKeyBytes route.Vertex

	// Capacity is the total amount of funds held in this channel.
	Capacity btcutil.Amount

	// SettledBalance is the amount we were paid out directly in this
	// channel close. Note that this does not include cases where we need to
	// sweep our commitment or htlcs.
	SettledBalance btcutil.Amount
}

ClosedChannel represents a channel that has been closed.

type DialerFunc

type DialerFunc func(context.Context, string) (net.Conn, error)

DialerFunc is a function that is used as grpc.WithContextDialer().

type ForceCloseChannel

type ForceCloseChannel struct {
	// PendingChannel contains information about the channel.
	PendingChannel

	// CloseTxid is the close transaction that confirmed on chain.
	CloseTxid chainhash.Hash
}

ForceCloseChannel describes a channel that pending force close.

type ForwardingEvent

type ForwardingEvent struct {
	// Timestamp is the time that we processed the forwarding event.
	Timestamp time.Time

	// ChannelIn is the id of the channel the htlc arrived at our node on.
	ChannelIn uint64

	// ChannelOut is the id of the channel the htlc left our node on.
	ChannelOut uint64

	// AmountMsatIn is the amount that was forwarded into our node in
	// millisatoshis.
	AmountMsatIn lnwire.MilliSatoshi

	// AmountMsatOut is the amount that was forwarded out of our node in
	// millisatoshis.
	AmountMsatOut lnwire.MilliSatoshi

	// FeeMsat is the amount of fees earned in millisatoshis,
	FeeMsat lnwire.MilliSatoshi
}

ForwardingEvent represents a htlc that was forwarded through our node.

type ForwardingHistoryRequest

type ForwardingHistoryRequest struct {
	// StartTime is the beginning of the query period.
	StartTime time.Time

	// EndTime is the end of the query period.
	EndTime time.Time

	// MaxEvents is the maximum number of events to return.
	MaxEvents uint32

	// Offset is the index from which to start querying.
	Offset uint32
}

ForwardingHistoryRequest contains the request parameters for a paginated forwarding history call.

type ForwardingHistoryResponse

type ForwardingHistoryResponse struct {
	// LastIndexOffset is the index offset of the last item in our set.
	LastIndexOffset uint32

	// Events is the set of events that were found in the interval queried.
	Events []ForwardingEvent
}

ForwardingHistoryResponse contains the response to a forwarding history query, including last index offset required for paginated queries.

type Graph

type Graph struct {
	// Nodes is the set of nodes in the channel graph.
	Nodes []Node

	// Edges is the set of edges in the channel graph.
	Edges []ChannelEdge
}

Graph describes our view of the graph.

type GraphTopologyUpdate

type GraphTopologyUpdate struct {
	// NodeUpdates holds the node announcements.
	NodeUpdates []NodeUpdate

	// ChannelEdgeUpdates holds the channel announcements.
	ChannelEdgeUpdates []ChannelEdgeUpdate

	// ChannelCloseUpdates holds the closed channel announcements.
	ChannelCloseUpdates []ChannelCloseUpdate
}

GraphTopologyUpdate encapsulates a streamed graph update.

type GrpcLndServices

type GrpcLndServices struct {
	LndServices
	// contains filtered or unexported fields
}

GrpcLndServices constitutes a set of required RPC services.

func NewLndServices

func NewLndServices(cfg *LndServicesConfig) (*GrpcLndServices, error)

NewLndServices creates creates a connection to the given lnd instance and creates a set of required RPC services.

func (*GrpcLndServices) Close

func (s *GrpcLndServices) Close()

Close closes the lnd connection and waits for all sub server clients to finish their goroutines.

type Hop

type Hop struct {
	// ChannelID is the short channel ID of the forwarding channel.
	ChannelID uint64

	// Capacity is the channel capacity.
	Capacity btcutil.Amount

	// Expiry is the timelock value.
	Expiry uint32

	// AmtToForwardMsat is the forwarded amount for this hop.
	AmtToForwardMsat lnwire.MilliSatoshi

	// FeeMsat is the forwarding fee for this hop.
	FeeMsat lnwire.MilliSatoshi

	// PubKey is an optional public key of the hop. If the public key is
	// given, the payment can be executed without relying on a copy of the
	// channel graph.
	PubKey *route.Vertex
}

Hop holds details about a single hop along a route.

type HtlcAttempt

type HtlcAttempt struct {
	// The status of the HTLC.
	Status lnrpc.HTLCAttempt_HTLCStatus

	// The route taken by this HTLC.
	Route *lnrpc.Route

	// AttemptTime is the time that the htlc was dispatched.
	AttemptTime time.Time

	// ResolveTime is the time the htlc was settled or failed.
	ResolveTime time.Time

	// Failure will be non-nil if the htlc failed, and provides more
	// information about the payment failure.
	Failure *HtlcFailure

	// Preimage is the preimage that was used to settle the payment.
	Preimage lntypes.Preimage
}

HtlcAttempt provides information about a htlc sent as part of a payment.

func NewHtlcAttempt

func NewHtlcAttempt(rpcAttempt *lnrpc.HTLCAttempt) (*HtlcAttempt, error)

NewHtlcAttempt creates a htlc attempt from its rpc counterpart.

func (*HtlcAttempt) AmountInFlight

func (h *HtlcAttempt) AmountInFlight() lnwire.MilliSatoshi

AmountInFlight returns the amount in flight for this htlc attempt that contributes to paying the final recipient, if any.

func (*HtlcAttempt) String

func (h *HtlcAttempt) String() string

String returns a string representation of a htlc attempt.

type HtlcFailure

type HtlcFailure struct {
	// Code is the failure code as defined in the lightning spec.
	Code lnrpc.Failure_FailureCode

	// FailureSourceIndex is the position in the path of the intermediate
	// or final node that generated the failure message. A value of 0
	// indicates that the failure occurred at the sender.
	FailureSourceIndex uint32
}

HtlcFailure provides information about a htlc attempt failure.

func NewHtlcFailure

func NewHtlcFailure(rpcFailure *lnrpc.Failure) *HtlcFailure

NewHtlcFailure creates a htlc failure from its rpc counterpart.

func (*HtlcFailure) String

func (h *HtlcFailure) String() string

String returns a string representation of a htlc failure.

type Info

type Info struct {
	// Version is the version that lnd is running.
	Version string

	// BlockHeight is the best block height that lnd has knowledge of.
	BlockHeight uint32

	// IdentityPubkey is our node's pubkey.
	IdentityPubkey [33]byte

	// Alias is our node's alias.
	Alias string

	// Network is the network we are currently operating on.
	Network string

	// Uris is the set of our node's advertised uris.
	Uris []string

	// SyncedToChain is true if the wallet's view is synced to the main
	// chain.
	SyncedToChain bool

	// SyncedToGraph is true if we consider ourselves to be synced with the
	// public channel graph.
	SyncedToGraph bool

	// BestHeaderTimeStamp is the best block timestamp known to the wallet.
	BestHeaderTimeStamp time.Time

	// ActiveChannels is the number of active channels we have.
	ActiveChannels uint32

	// InactiveChannels is the number of inactive channels we have.
	InactiveChannels uint32

	// PendingChannels is the number of pending channels we have.
	PendingChannels uint32
}

Info contains info about the connected lnd node.

type Initiator

type Initiator uint8

Initiator indicates the party that opened or closed a channel. This enum is used for cases where we may not have a full set of initiator information available over rpc (this is the case for older channels).

const (
	// InitiatorUnrecorded is set when we do not know the open/close
	// initiator for a channel, this is the case when the channel was
	// closed before lnd started tracking initiators.
	InitiatorUnrecorded Initiator = iota

	// InitiatorLocal is set when we initiated a channel open or close.
	InitiatorLocal

	// InitiatorRemote is set when the remote party initiated a chanel open
	// or close.
	InitiatorRemote

	// InitiatorBoth is set in the case where both parties initiated a
	// cooperative close (this is possible with multiple rounds of
	// negotiation).
	InitiatorBoth
)

func (Initiator) String

func (c Initiator) String() string

String provides the string represenetation of a close initiator.

type Invoice

type Invoice struct {
	// Preimage is the invoice's preimage, which is set if the invoice
	// is settled.
	Preimage *lntypes.Preimage

	// Hash is the invoice hash.
	Hash lntypes.Hash

	// Memo is an optional memo field for hte invoice.
	Memo string

	// PaymentRequest is the invoice's payment request.
	PaymentRequest string

	// Amount is the amount of the invoice in millisatoshis.
	Amount lnwire.MilliSatoshi

	// AmountPaid is the amount that was paid for the invoice. This field
	// will only be set if the invoice is settled.
	AmountPaid lnwire.MilliSatoshi

	// CreationDate is the time the invoice was created.
	CreationDate time.Time

	// SettleDate is the time the invoice was settled.
	SettleDate time.Time

	// State is the invoice's current state.
	State channeldb.ContractState

	// IsKeysend indicates whether the invoice was a spontaneous payment.
	IsKeysend bool

	// Htlcs is the set of htlcs that the invoice was settled with.
	Htlcs []InvoiceHtlc

	// AddIndex is the index at which the invoice was added.
	AddIndex uint64

	// SettleIndex is the index at which the invoice was settled.
	SettleIndex uint64
}

Invoice represents an invoice in lnd.

type InvoiceHtlc

type InvoiceHtlc struct {
	// ChannelID is the short channel ID of the incoming channel that the
	// htlc arrived on.
	ChannelID lnwire.ShortChannelID

	// Amount is the amount in millisatoshis that was paid with this htlc.
	// Note that this may not be the full amount because invoices can be
	// paid with multiple hltcs.
	Amount lnwire.MilliSatoshi

	// AcceptTime is the time that the htlc arrived at our node.
	AcceptTime time.Time

	// ResolveTime is the time that the htlc was resolved (settled or failed
	// back).
	ResolveTime time.Time

	// CustomRecords is list of the custom tlv records.
	CustomRecords map[uint64][]byte
}

InvoiceHtlc represents a htlc that was used to pay an invoice.

type InvoiceSubscriptionRequest

type InvoiceSubscriptionRequest struct {
	// If specified (non-zero), then we'll first start by sending out
	// notifications for all added indexes with an add_index greater than this
	// value. This allows callers to catch up on any events they missed while they
	// weren't connected to the streaming RPC.
	AddIndex uint64

	// If specified (non-zero), then we'll first start by sending out
	// notifications for all settled indexes with an settle_index greater than
	// this value. This allows callers to catch up on any events they missed while
	// they weren't connected to the streaming RPC.
	SettleIndex uint64
}

InvoiceSubscriptionRequest holds the parameters to specify from which update to start streaming.

type InvoiceUpdate

type InvoiceUpdate struct {
	State   channeldb.ContractState
	AmtPaid btcutil.Amount
}

InvoiceUpdate contains a state update for an invoice.

type InvoicesClient

type InvoicesClient interface {
	SubscribeSingleInvoice(ctx context.Context, hash lntypes.Hash) (
		<-chan InvoiceUpdate, <-chan error, error)

	SettleInvoice(ctx context.Context, preimage lntypes.Preimage) error

	CancelInvoice(ctx context.Context, hash lntypes.Hash) error

	AddHoldInvoice(ctx context.Context, in *invoicesrpc.AddInvoiceData) (
		string, error)
}

InvoicesClient exposes invoice functionality.

type LightningClient

type LightningClient interface {
	PayInvoice(ctx context.Context, invoice string,
		maxFee btcutil.Amount,
		outgoingChannel *uint64) chan PaymentResult

	GetInfo(ctx context.Context) (*Info, error)

	EstimateFeeToP2WSH(ctx context.Context, amt btcutil.Amount,
		confTarget int32) (btcutil.Amount, error)

	// WalletBalance returns a summary of the node's wallet balance.
	WalletBalance(ctx context.Context) (*WalletBalance, error)

	AddInvoice(ctx context.Context, in *invoicesrpc.AddInvoiceData) (
		lntypes.Hash, string, error)

	// LookupInvoice looks up an invoice by hash.
	LookupInvoice(ctx context.Context, hash lntypes.Hash) (*Invoice, error)

	// ListTransactions returns all known transactions of the backing lnd
	// node. It takes a start and end block height which can be used to
	// limit the block range that we query over. These values can be left
	// as zero to include all blocks. To include unconfirmed transactions
	// in the query, endHeight must be set to -1.
	ListTransactions(ctx context.Context, startHeight,
		endHeight int32) ([]Transaction, error)

	// ListChannels retrieves all channels of the backing lnd node.
	ListChannels(ctx context.Context) ([]ChannelInfo, error)

	// PendingChannels returns a list of lnd's pending channels.
	PendingChannels(ctx context.Context) (*PendingChannels, error)

	// ClosedChannels returns all closed channels of the backing lnd node.
	ClosedChannels(ctx context.Context) ([]ClosedChannel, error)

	// ForwardingHistory makes a paginated call to our forwarding history
	// endpoint.
	ForwardingHistory(ctx context.Context,
		req ForwardingHistoryRequest) (*ForwardingHistoryResponse, error)

	// ListInvoices makes a paginated call to our list invoices endpoint.
	ListInvoices(ctx context.Context, req ListInvoicesRequest) (
		*ListInvoicesResponse, error)

	// ListPayments makes a paginated call to our list payments endpoint.
	ListPayments(ctx context.Context,
		req ListPaymentsRequest) (*ListPaymentsResponse, error)

	// ChannelBackup retrieves the backup for a particular channel. The
	// backup is returned as an encrypted chanbackup.Single payload.
	ChannelBackup(context.Context, wire.OutPoint) ([]byte, error)

	// ChannelBackups retrieves backups for all existing pending open and
	// open channels. The backups are returned as an encrypted
	// chanbackup.Multi payload.
	ChannelBackups(ctx context.Context) ([]byte, error)

	// SubscribeChannelBackups allows a client to subscribe to the
	// most up to date information concerning the state of all channel
	// backups.
	SubscribeChannelBackups(ctx context.Context) (
		<-chan lnrpc.ChanBackupSnapshot, <-chan error, error)

	// SubscribeChannelEvents allows a client to subscribe to updates
	// relevant to the state of channels. Events include new active
	// channels, inactive channels, and closed channels.
	SubscribeChannelEvents(ctx context.Context) (
		<-chan *ChannelEventUpdate, <-chan error, error)

	// DecodePaymentRequest decodes a payment request.
	DecodePaymentRequest(ctx context.Context,
		payReq string) (*PaymentRequest, error)

	// OpenChannel opens a channel to the peer provided with the amounts
	// specified.
	OpenChannel(ctx context.Context, peer route.Vertex,
		localSat, pushSat btcutil.Amount, private bool) (
		*wire.OutPoint, error)

	// CloseChannel closes the channel provided.
	CloseChannel(ctx context.Context, channel *wire.OutPoint,
		force bool, confTarget int32, deliveryAddr btcutil.Address) (
		chan CloseChannelUpdate, chan error, error)

	// UpdateChanPolicy updates the channel policy for the passed chanPoint.
	// If the chanPoint is nil, then the policy is applied for all existing
	// channels.
	UpdateChanPolicy(ctx context.Context, req PolicyUpdateRequest,
		chanPoint *wire.OutPoint) error

	// GetChanInfo returns the channel info for the passed channel,
	// including the routing policy for both end.
	GetChanInfo(ctx context.Context, chanID uint64) (*ChannelEdge, error)

	// ListPeers gets a list the peers we are currently connected to.
	ListPeers(ctx context.Context) ([]Peer, error)

	// Connect attempts to connect to a peer at the host specified. If
	// permanent is true then we'll attempt to connect to the peer
	// permanently, meaning that the connection is maintained even if no
	// channels exist between us and the peer.
	Connect(ctx context.Context, peer route.Vertex, host string,
		permanent bool) error

	// SendCoins sends the passed amount of (or all) coins to the passed
	// address. Either amount or sendAll must be specified, while
	// confTarget, satsPerByte are optional and may be set to zero in which
	// case automatic conf target and fee will be used. Returns the tx id
	// upon success.
	SendCoins(ctx context.Context, addr btcutil.Address,
		amount btcutil.Amount, sendAll bool, confTarget int32,
		satsPerByte int64, label string) (string, error)

	// ChannelBalance returns a summary of our channel balances.
	ChannelBalance(ctx context.Context) (*ChannelBalance, error)

	// GetNodeInfo looks up information for a specific node.
	GetNodeInfo(ctx context.Context, pubkey route.Vertex,
		includeChannels bool) (*NodeInfo, error)

	// DescribeGraph returns our view of the graph.
	DescribeGraph(ctx context.Context, includeUnannounced bool) (*Graph, error)

	// SubscribeGraph allows a client to subscribe to gaph topology updates.
	SubscribeGraph(ctx context.Context) (<-chan *GraphTopologyUpdate,
		<-chan error, error)

	// NetworkInfo returns stats regarding our view of the network.
	NetworkInfo(ctx context.Context) (*NetworkInfo, error)

	// SubscribeInvoices allows a client to subscribe to updates
	// of newly added/settled invoices.
	SubscribeInvoices(ctx context.Context, req InvoiceSubscriptionRequest) (
		<-chan *Invoice, <-chan error, error)

	// ListPermissions returns a list of all RPC method URIs and the
	// macaroon permissions that are required to access them.
	ListPermissions(ctx context.Context) (map[string][]MacaroonPermission,
		error)

	// QueryRoutes can query LND to return a route (with fees) between two
	// vertices.
	QueryRoutes(ctx context.Context, req QueryRoutesRequest) (
		*QueryRoutesResponse, error)
}

LightningClient exposes base lightning functionality.

type ListInvoicesRequest

type ListInvoicesRequest struct {
	// MaxInvoices is the maximum number of invoices to return.
	MaxInvoices uint64

	// Offset is the index from which to start querying.
	Offset uint64

	// Reversed is set to query our invoices backwards.
	Reversed bool

	// PendingOnly is set if we only want pending invoices.
	PendingOnly bool
}

ListInvoicesRequest contains the request parameters for a paginated list invoices call.

type ListInvoicesResponse

type ListInvoicesResponse struct {
	// FirstIndexOffset is the index offset of the first item in our set.
	FirstIndexOffset uint64

	// LastIndexOffset is the index offset of the last item in our set.
	LastIndexOffset uint64

	// Invoices is the set of invoices that were returned.
	Invoices []Invoice
}

ListInvoicesResponse contains the response to a list invoices query, including the index offsets required for paginated queries.

type ListPaymentsRequest

type ListPaymentsRequest struct {
	// MaxPayments is the maximum number of payments to return.
	MaxPayments uint64

	// Offset is the index from which to start querying.
	Offset uint64

	// Reversed is set to query our payments backwards.
	Reversed bool

	// IncludeIncomplete is set if we want to include incomplete payments.
	IncludeIncomplete bool
}

ListPaymentsRequest contains the request parameters for a paginated list payments call.

type ListPaymentsResponse

type ListPaymentsResponse struct {
	// FirstIndexOffset is the index offset of the first item in our set.
	FirstIndexOffset uint64

	// LastIndexOffset is the index offset of the last item in our set.
	LastIndexOffset uint64

	// Payments is the set of invoices that were returned.
	Payments []Payment
}

ListPaymentsResponse contains the response to a list payments query, including the index offsets required for paginated queries.

type LndServices

type LndServices struct {
	Client        LightningClient
	WalletKit     WalletKitClient
	ChainNotifier ChainNotifierClient
	Signer        SignerClient
	Invoices      InvoicesClient
	Router        RouterClient
	Versioner     VersionerClient

	ChainParams *chaincfg.Params
	NodeAlias   string
	NodePubkey  route.Vertex
	Version     *verrpc.Version
	// contains filtered or unexported fields
}

LndServices constitutes a set of required services.

type LndServicesConfig

type LndServicesConfig struct {
	// LndAddress is the network address (host:port) of the lnd node to
	// connect to.
	LndAddress string

	// Network is the bitcoin network we expect the lnd node to operate on.
	Network Network

	// MacaroonDir is the directory where all lnd macaroons can be found.
	// Either this or CustomMacaroonPath can be specified but not both.
	MacaroonDir string

	// CustomMacaroonPath is the full path to a custom macaroon file. Either
	// this or MacaroonDir can be specified but not both.
	CustomMacaroonPath string

	// TLSPath is the path to lnd's TLS certificate file.
	TLSPath string

	// CheckVersion is the minimum version the connected lnd node needs to
	// be in order to be compatible. The node will be checked against this
	// when connecting. If no version is supplied, the default minimum
	// version will be used.
	CheckVersion *verrpc.Version

	// Dialer is an optional dial function that can be passed in if the
	// default lncfg.ClientAddressDialer should not be used.
	Dialer DialerFunc

	// BlockUntilChainSynced denotes that the NewLndServices function should
	// block until the lnd node is fully synced to its chain backend. This
	// can take a long time if lnd was offline for a while or if the initial
	// block download is still in progress.
	BlockUntilChainSynced bool

	// BlockUntilUnlocked denotes that the NewLndServices function should
	// block until lnd is unlocked.
	BlockUntilUnlocked bool

	// UnlockInterval sets the interval at which we will query lnd to
	// determine whether lnd is unlocked when BlockUntilUnlocked is true.
	// This value is optional, and will be replaced with a default if it is
	// zero.
	UnlockInterval time.Duration

	// CallerCtx is an optional context that can be passed if the caller
	// would like to be able to cancel the long waits involved in starting
	// up the client, such as waiting for chain sync to complete when
	// BlockUntilChainSynced is set to true, or waiting for lnd to be
	// unlocked when BlockUntilUnlocked is set to true. If a context is
	// passed in and its Done() channel sends a message, these waits will
	// be aborted. This allows a client to still be shut down properly.
	CallerCtx context.Context

	// RPCTimeout is an optional custom timeout that will be used for rpc
	// calls to lnd. If this value is not set, it will default to 30
	// seconds.
	RPCTimeout time.Duration
}

LndServicesConfig holds all configuration settings that are needed to connect to an lnd node.

type MacaroonPermission

type MacaroonPermission struct {
	// Entity is the entity a permission grants access to.
	Entity string

	// Action is the action that is granted by a permission.
	Action string
}

MacaroonPermission is a struct that holds a permission entry, consisting of an entity and an action.

func MacaroonRecipe

func MacaroonRecipe(c LightningClient, packages []string) ([]MacaroonPermission,
	error)

MacaroonRecipe returns a list of macaroon permissions that is required to use the full feature set of the given list of RPC package names.

func (*MacaroonPermission) String

func (p *MacaroonPermission) String() string

String returns the human readable representation of a permission.

type Network

type Network string

Network defines the chain that we operate on.

const (
	// NetworkMainnet is bitcoin mainnet.
	NetworkMainnet Network = "mainnet"

	// NetworkTestnet is bitcoin testnet.
	NetworkTestnet Network = "testnet"

	// NetworkRegtest is bitcoin regtest.
	NetworkRegtest Network = "regtest"

	// NetworkSimnet is bitcoin simnet.
	NetworkSimnet Network = "simnet"
)

func (Network) ChainParams

func (n Network) ChainParams() (*chaincfg.Params, error)

ChainParams returns chain parameters based on a network name.

type NetworkInfo

type NetworkInfo struct {
	// GraphDiameter is the diameter of the graph.
	GraphDiameter uint32

	// AvgOutDegree is the average out degree in the graph.
	AvgOutDegree float64

	// MaxOutDegree is the largest out degree in the graph.
	MaxOutDegree uint32

	// NumNodes is the number of nodes in our view of the network.
	NumNodes uint32

	// NumChannels is the number of channels in our view of the network.
	NumChannels uint32

	// TotalNetworkCapacity is the total amount of funds in public channels.
	TotalNetworkCapacity btcutil.Amount

	// AvgChannelSize is the average public channel size.
	AvgChannelSize btcutil.Amount

	// MinChannelSize is the size of the smallest public channel in the graph.
	MinChannelSize btcutil.Amount

	// MaxChannelSize is the size of the largest public channel in the graph.
	MaxChannelSize btcutil.Amount

	// MedianChannelSize is the median public channel size.
	MedianChannelSize btcutil.Amount

	// NumZombieChans is the number of channels that have been marked as
	// zombies.
	NumZombieChans uint64
}

NetworkInfo describes the structure of our view of the graph.

type Node

type Node struct {
	// PubKey is the node's pubkey.
	PubKey route.Vertex

	// LastUpdate is the last update time for the node.
	LastUpdate time.Time

	// Alias is the node's chosen alias.
	Alias string

	// Color is the node's chosen color.
	Color string

	// Features is the set of features the node supports.
	Features []lnwire.FeatureBit

	// Addresses holds the network addresses of the node.
	Addresses []string
}

Node describes a node in the network.

type NodeInfo

type NodeInfo struct {
	// Node contains information about the node itself.
	*Node

	// ChannelCount is the total number of public channels the node has
	// announced.
	ChannelCount int

	// TotalCapacity is the node's total public channel capacity.
	TotalCapacity btcutil.Amount

	// Channels contains all of the node's channels, only set if GetNode
	// was queried with include channels set to true.
	Channels []ChannelEdge
}

NodeInfo contains information about a node and its channels.

type NodeUpdate

type NodeUpdate struct {
	// Addresses holds the announced node addresses.
	Addresses []string

	// IdentityKey holds the node's pub key.
	IdentityKey route.Vertex

	// GlobalFeatures holds the node's advertised features.
	GlobalFeatures lnwire.FeatureVector

	// Alias is the node's alias name.
	Alias string

	// Color is the node's color in hex.
	Color string
}

NodeUpdate holds a node announcement graph topology update.

type Payment

type Payment struct {
	// Hash is the payment hash used.
	Hash lntypes.Hash

	// Preimage is the preimage of the payment. It will have a non-nil value
	// if the payment is settled.
	Preimage *lntypes.Preimage

	// PaymentRequest is the payment request for this payment. This value
	// will not be set for keysend payments and for payments that manually
	// specify their destination and amount.
	PaymentRequest string

	// Amount is the amount in millisatoshis of the payment.
	Amount lnwire.MilliSatoshi

	// Fee is the amount in millisatoshis that was paid in fees.
	Fee lnwire.MilliSatoshi

	// Status describes the state of a payment.
	Status *PaymentStatus

	// Htlcs is the set of htlc attempts made by the payment.
	Htlcs []*lnrpc.HTLCAttempt

	// SequenceNumber is a unique id for each payment.
	SequenceNumber uint64
}

Payment represents a payment made by our node.

type PaymentRequest

type PaymentRequest struct {
	// Destination is the node that this payment request pays to .
	Destination route.Vertex

	// Hash is the payment hash associated with this payment
	Hash lntypes.Hash

	// Value is the value of the payment request in millisatoshis.
	Value lnwire.MilliSatoshi

	/// Timestamp of the payment request.
	Timestamp time.Time

	// Expiry is the time at which the payment request expires.
	Expiry time.Time

	// Description is a description attached to the payment request.
	Description string

	// PaymentAddress is the payment address associated with the invoice,
	// set if the receiver supports mpp.
	PaymentAddress [32]byte
}

PaymentRequest represents a request for payment from a node.

type PaymentResult

type PaymentResult struct {
	Err      error
	Preimage lntypes.Preimage
	PaidFee  btcutil.Amount
	PaidAmt  btcutil.Amount
}

PaymentResult signals the result of a payment.

type PaymentStatus

type PaymentStatus struct {
	State lnrpc.Payment_PaymentStatus

	// FailureReason is the reason why the payment failed. Only set when
	// State is Failed.
	FailureReason lnrpc.PaymentFailureReason

	Preimage      lntypes.Preimage
	Fee           lnwire.MilliSatoshi
	Value         lnwire.MilliSatoshi
	InFlightAmt   lnwire.MilliSatoshi
	InFlightHtlcs int

	Htlcs []*HtlcAttempt
}

PaymentStatus describe the state of a payment.

func (PaymentStatus) String

func (p PaymentStatus) String() string

type Peer

type Peer struct {
	// Pubkey is the peer's pubkey.
	Pubkey route.Vertex

	// Address is the host:port of the peer.
	Address string

	// BytesSent is the total number of bytes we have sent the peer.
	BytesSent uint64

	// BytesReceived is the total number of bytes we have received from
	// the peer.
	BytesReceived uint64

	// Inbound indicates whether the remote peer initiated the connection.
	Inbound bool

	// PingTime is the estimated round trip time to this peer.
	PingTime time.Duration

	// Sent is the total amount we have sent to this peer.
	Sent btcutil.Amount

	// Received is the total amount we have received from this peer.
	Received btcutil.Amount
}

Peer contains information about a peer we are connected to.

type PendingChannel

type PendingChannel struct {
	// ChannelPoint is the outpoint of the channel.
	ChannelPoint *wire.OutPoint

	// PubKeyBytes is the raw bytes of the public key of the remote node.
	PubKeyBytes route.Vertex

	// Capacity is the total amount of funds held in this channel.
	Capacity btcutil.Amount

	// ChannelInitiator indicates which party opened the channel.
	ChannelInitiator Initiator
}

PendingChannel contains the information common to all pending channels.

func NewPendingChannel

func NewPendingChannel(channel *lnrpc.PendingChannelsResponse_PendingChannel) (
	*PendingChannel, error)

NewPendingChannel creates a pending channel from the rpc struct.

type PendingChannels

type PendingChannels struct {
	// PendingForceClose contains our channels that have been force closed,
	// and are awaiting full on chain resolution.
	PendingForceClose []ForceCloseChannel

	// PendingOpen contains channels that we are waiting to confirm on chain
	// so that they can be marked as fully open.
	PendingOpen []PendingChannel

	// WaitingClose contains channels that are waiting for their close tx
	// to confirm.
	WaitingClose []WaitingCloseChannel
}

PendingChannels contains lnd's channels that are pending open and close.

type PendingCloseUpdate

type PendingCloseUpdate struct {
	// CloseTx is the closing transaction id.
	CloseTx chainhash.Hash
}

PendingCloseUpdate indicates that our closing transaction has been broadcast.

func (*PendingCloseUpdate) CloseTxid

func (p *PendingCloseUpdate) CloseTxid() chainhash.Hash

CloseTxid returns the closing txid of the channel.

type PendingHtlc

type PendingHtlc struct {
	// Incoming is true if the HTLC is incoming.
	Incoming bool

	// Amount is the amount in satoshis that this HTLC represents.
	Amount btcutil.Amount
}

PendingHtlc represents a HTLC that is currently pending on some channel.

type PolicyUpdateRequest

type PolicyUpdateRequest struct {
	// BaseFeeMsat is the base fee charged regardless of the number of
	// milli-satoshis sent.
	BaseFeeMsat int64

	// FeeRate is the effective fee rate in milli-satoshis. The precision of
	// this value goes up to 6 decimal places, so 1e-6.
	FeeRate float64

	// TimeLockDelta is the required timelock delta for HTLCs forwarded over
	// the channel.
	TimeLockDelta uint32

	// MaxHtlcMsat if set (non zero), holds the maximum HTLC size in
	// milli-satoshis. If unset, the maximum HTLC will be unchanged.
	MaxHtlcMsat uint64

	// MinHtlcMsat is the minimum HTLC size in milli-satoshis. Only applied
	// if MinHtlcMsatSpecified is true.
	MinHtlcMsat uint64

	// MinHtlcMsatSpecified if true, MinHtlcMsat is applied.
	MinHtlcMsatSpecified bool
}

PolicyUpdateRequest holds UpdateChanPolicy request data.

type QueryRoutesRequest

type QueryRoutesRequest struct {
	// Source is the optional source vertex of the route.
	Source *route.Vertex

	// PubKey is the destination vertex.
	PubKey route.Vertex

	// LastHop is the optional last hop before the destination.
	LastHop *route.Vertex

	// RouteHints represents the different routing hints that can be used to
	// assist the router. These hints will act as optional intermediate hops
	// along the route.
	RouteHints [][]zpay32.HopHint

	// MaxCltv when set is used the the CLTV limit.
	MaxCltv *uint32

	// UseMissionControl if set to true, edge probabilities from mission
	// control will be used to get the optimal route.
	UseMissionControl bool

	// AmtMsat is the amount we'd like to send along the route in
	// millisatoshis.
	AmtMsat lnwire.MilliSatoshi

	// FeeLimitMsat is the fee limit to use in millisatoshis.
	FeeLimitMsat lnwire.MilliSatoshi
}

QueryRoutesRequest is the request of a QueryRoutes call.

type QueryRoutesResponse

type QueryRoutesResponse struct {
	// TotalTimeLock is the cumulative (final) time lock across the entire
	// route. This is the CLTV value that should be extended to the first
	// hop in the route. All other hops will decrement the time-lock as
	// advertised, leaving enough time for all hops to wait for or present
	// the payment preimage to complete the payment.
	TotalTimeLock uint32

	// Hops contains details concerning the specific forwarding details at
	// each hop.
	Hops []*Hop

	// TotalFeesMsat is the total fees in millisatoshis.
	TotalFeesMsat lnwire.MilliSatoshi

	// TotalAmtMsat is the total amount in millisatoshis.
	TotalAmtMsat lnwire.MilliSatoshi
}

QueryRoutesResponse is the response of a QueryRoutes call.

type RouterClient

type RouterClient interface {
	// SendPayment attempts to route a payment to the final destination. The
	// call returns a payment update stream and an error stream.
	SendPayment(ctx context.Context, request SendPaymentRequest) (
		chan PaymentStatus, chan error, error)

	// TrackPayment picks up a previously started payment and returns a
	// payment update stream and an error stream.
	TrackPayment(ctx context.Context, hash lntypes.Hash) (
		chan PaymentStatus, chan error, error)

	// EstimateRouteFee uses the channel router's internal state to estimate
	// the routing cost of the given amount to the destination node.
	EstimateRouteFee(ctx context.Context, dest route.Vertex,
		amt btcutil.Amount) (lnwire.MilliSatoshi, error)

	// SubscribeHtlcEvents subscribes to a stream of htlc events from the
	// router.
	SubscribeHtlcEvents(ctx context.Context) (<-chan *routerrpc.HtlcEvent,
		<-chan error, error)
}

RouterClient exposes payment functionality.

type RoutingPolicy

type RoutingPolicy struct {
	// TimeLockDelta is the required timelock delta for HTLCs forwarded
	// over the channel.
	TimeLockDelta uint32

	// MinHtlcMsat is the minimum HTLC size in milli-satoshis.
	MinHtlcMsat int64

	// MaxHtlcMsat the maximum HTLC size in milli-satoshis.
	MaxHtlcMsat uint64

	// FeeBaseMsat is the base fee charged regardless of the number of
	// milli-satoshis sent.
	FeeBaseMsat int64

	// FeeRateMilliMsat is the rate that the node will charge for
	// HTLCs for each millionth of a satoshi forwarded, in milli-satoshis.
	FeeRateMilliMsat int64

	// Disabled is true if the edge is disabled.
	Disabled bool

	// LastUpdate is the last update time for the edge policy.
	LastUpdate time.Time
}

RoutingPolicy holds the edge routing policy for a channel edge.

type SendPaymentRequest

type SendPaymentRequest struct {
	// Invoice is an encoded payment request. The individual payment
	// parameters Target, Amount, PaymentHash, FinalCLTVDelta and RouteHints
	// are only processed when the Invoice field is empty.
	Invoice string

	// MaxFee is the fee limit for this payment.
	MaxFee btcutil.Amount

	// MaxFeeMsat is the fee limit for this payment in millisatoshis.
	// MaxFee and MaxFeeMsat are mutually exclusive.
	MaxFeeMsat lnwire.MilliSatoshi

	// MaxCltv is the maximum timelock for this payment. If nil, there is no
	// maximum.
	MaxCltv *int32

	// OutgoingChanIds is a restriction on the set of possible outgoing
	// channels. If nil or empty, there is no restriction.
	OutgoingChanIds []uint64

	// Timeout is the payment loop timeout. After this time, no new payment
	// attempts will be started.
	Timeout time.Duration

	// Target is the node in which the payment should be routed towards.
	Target route.Vertex

	// Amount is the value of the payment to send through the network in
	// satoshis.
	Amount btcutil.Amount

	// PaymentHash is the r-hash value to use within the HTLC extended to
	// the first hop.
	PaymentHash *lntypes.Hash

	// FinalCLTVDelta is the CTLV expiry delta to use for the _final_ hop
	// in the route. This means that the final hop will have a CLTV delta
	// of at least: currentHeight + FinalCLTVDelta.
	FinalCLTVDelta uint16

	// RouteHints represents the different routing hints that can be used to
	// assist a payment in reaching its destination successfully. These
	// hints will act as intermediate hops along the route.
	//
	// NOTE: This is optional unless required by the payment. When providing
	// multiple routes, ensure the hop hints within each route are chained
	// together and sorted in forward order in order to reach the
	// destination successfully.
	RouteHints [][]zpay32.HopHint

	// LastHopPubkey is the pubkey of the last hop of the route taken
	// for this payment. If empty, any hop may be used.
	LastHopPubkey *route.Vertex

	// MaxParts is the maximum number of partial payments that may be used
	// to complete the full amount.
	MaxParts uint32

	// KeySend is set to true if the tlv payload will include the preimage.
	KeySend bool

	// CustomRecords holds the custom TLV records that will be added to the
	// payment.
	CustomRecords map[uint64][]byte

	// If set, circular payments to self are permitted.
	AllowSelfPayment bool
}

SendPaymentRequest defines the payment parameters for a new payment.

type SignDescriptor

type SignDescriptor struct {
	// KeyDesc is a descriptor that precisely describes *which* key to use
	// for signing. This may provide the raw public key directly, or
	// require the Signer to re-derive the key according to the populated
	// derivation path.
	KeyDesc keychain.KeyDescriptor

	// SingleTweak is a scalar value that will be added to the private key
	// corresponding to the above public key to obtain the private key to
	// be used to sign this input. This value is typically derived via the
	// following computation:
	//
	//  * derivedKey = privkey + sha256(perCommitmentPoint || pubKey) mod N
	//
	// NOTE: If this value is nil, then the input can be signed using only
	// the above public key. Either a SingleTweak should be set or a
	// DoubleTweak, not both.
	SingleTweak []byte

	// DoubleTweak is a private key that will be used in combination with
	// its corresponding private key to derive the private key that is to
	// be used to sign the target input. Within the Lightning protocol,
	// this value is typically the commitment secret from a previously
	// revoked commitment transaction. This value is in combination with
	// two hash values, and the original private key to derive the private
	// key to be used when signing.
	//
	//  * k = (privKey*sha256(pubKey || tweakPub) +
	//        tweakPriv*sha256(tweakPub || pubKey)) mod N
	//
	// NOTE: If this value is nil, then the input can be signed using only
	// the above public key. Either a SingleTweak should be set or a
	// DoubleTweak, not both.
	DoubleTweak *btcec.PrivateKey

	// WitnessScript is the full script required to properly redeem the
	// output. This field should be set to the full script if a p2wsh
	// output is being signed. For p2wkh it should be set to the hashed
	// script (PkScript).
	WitnessScript []byte

	// Output is the target output which should be signed. The PkScript and
	// Value fields within the output should be properly populated,
	// otherwise an invalid signature may be generated.
	Output *wire.TxOut

	// HashType is the target sighash type that should be used when
	// generating the final sighash, and signature.
	HashType txscript.SigHashType

	// InputIndex is the target input within the transaction that should be
	// signed.
	InputIndex int
}

SignDescriptor houses the necessary information required to successfully sign a given segwit output. This struct is used by the Signer interface in order to gain access to critical data needed to generate a valid signature.

type SignerClient

type SignerClient interface {
	SignOutputRaw(ctx context.Context, tx *wire.MsgTx,
		signDescriptors []*SignDescriptor) ([][]byte, error)

	// ComputeInputScript generates the proper input script for P2WPKH
	// output and NP2WPKH outputs. This method only requires that the
	// `Output`, `HashType`, `SigHashes` and `InputIndex` fields are
	// populated within the sign descriptors.
	ComputeInputScript(ctx context.Context, tx *wire.MsgTx,
		signDescriptors []*SignDescriptor) ([]*input.Script, error)

	// SignMessage signs a message with the key specified in the key
	// locator. The returned signature is fixed-size LN wire format encoded.
	SignMessage(ctx context.Context, msg []byte,
		locator keychain.KeyLocator) ([]byte, error)

	// VerifyMessage verifies a signature over a message using the public
	// key provided. The signature must be fixed-size LN wire format
	// encoded.
	VerifyMessage(ctx context.Context, msg, sig []byte, pubkey [33]byte) (
		bool, error)

	// DeriveSharedKey returns a shared secret key by performing
	// Diffie-Hellman key derivation between the ephemeral public key and
	// the key specified by the key locator (or the node's identity private
	// key if no key locator is specified):
	//
	//     P_shared = privKeyNode * ephemeralPubkey
	//
	// The resulting shared public key is serialized in the compressed
	// format and hashed with SHA256, resulting in a final key length of 256
	// bits.
	DeriveSharedKey(ctx context.Context, ephemeralPubKey *btcec.PublicKey,
		keyLocator *keychain.KeyLocator) ([32]byte, error)
}

SignerClient exposes sign functionality.

type Transaction

type Transaction struct {
	// Tx is the on chain transaction.
	Tx *wire.MsgTx

	// TxHash is the transaction hash string.
	TxHash string

	// Timestamp is the timestamp our wallet has for the transaction.
	Timestamp time.Time

	// Amount is the balance change that this transaction had on addresses
	// controlled by our wallet.
	Amount btcutil.Amount

	// Fee is the amount of fees our wallet committed to this transaction.
	// Note that this field is not exhaustive, as it does not account for
	// fees taken from inputs that that wallet doesn't know it owns (for
	// example, the fees taken from our channel balance when we close a
	// channel).
	Fee btcutil.Amount

	// Confirmations is the number of confirmations the transaction has.
	Confirmations int32

	// Label is an optional label set for on chain transactions.
	Label string
}

Transaction represents an on chain transaction.

type VersionerClient

type VersionerClient interface {
	// GetVersion returns the version and build information of the lnd
	// daemon.
	GetVersion(ctx context.Context) (*verrpc.Version, error)
}

VersionerClient exposes the version of lnd.

type WaitingCloseChannel

type WaitingCloseChannel struct {
	// PendingChannel contains information about the channel.
	PendingChannel

	// LocalTxid is our close transaction's txid.
	LocalTxid chainhash.Hash

	// RemoteTxid is the remote party's close txid.
	RemoteTxid chainhash.Hash

	// RemotePending is the txid of the remote party's pending commit.
	RemotePending chainhash.Hash
}

WaitingCloseChannel describes a channel that we are waiting to be closed on chain. It contains both parties close txids because either may confirm at this point.

type WalletBalance

type WalletBalance struct {
	// Confirmed is our total confirmed balance.
	Confirmed btcutil.Amount

	// Unconfirmed is our total unconfirmed balance.
	Unconfirmed btcutil.Amount
}

WalletBalance describes our wallet's current balance.

type WalletKitClient

type WalletKitClient interface {
	// ListUnspent returns a list of all utxos spendable by the wallet with
	// a number of confirmations between the specified minimum and maximum.
	ListUnspent(ctx context.Context, minConfs, maxConfs int32) (
		[]*lnwallet.Utxo, error)

	// LeaseOutput locks an output to the given ID, preventing it from being
	// available for any future coin selection attempts. The absolute time
	// of the lock's expiration is returned. The expiration of the lock can
	// be extended by successive invocations of this call. Outputs can be
	// unlocked before their expiration through `ReleaseOutput`.
	LeaseOutput(ctx context.Context, lockID wtxmgr.LockID,
		op wire.OutPoint) (time.Time, error)

	// ReleaseOutput unlocks an output, allowing it to be available for coin
	// selection if it remains unspent. The ID should match the one used to
	// originally lock the output.
	ReleaseOutput(ctx context.Context, lockID wtxmgr.LockID,
		op wire.OutPoint) error

	DeriveNextKey(ctx context.Context, family int32) (
		*keychain.KeyDescriptor, error)

	DeriveKey(ctx context.Context, locator *keychain.KeyLocator) (
		*keychain.KeyDescriptor, error)

	NextAddr(ctx context.Context) (btcutil.Address, error)

	PublishTransaction(ctx context.Context, tx *wire.MsgTx,
		label string) error

	SendOutputs(ctx context.Context, outputs []*wire.TxOut,
		feeRate chainfee.SatPerKWeight,
		label string) (*wire.MsgTx, error)

	EstimateFee(ctx context.Context, confTarget int32) (chainfee.SatPerKWeight,
		error)

	// ListSweeps returns a list of sweep transaction ids known to our node.
	// Note that this function only looks up transaction ids, and does not
	// query our wallet for the full set of transactions.
	ListSweeps(ctx context.Context) ([]string, error)

	// BumpFee attempts to bump the fee of a transaction by spending one of
	// its outputs at the given fee rate. This essentially results in a
	// child-pays-for-parent (CPFP) scenario. If the given output has been
	// used in a previous BumpFee call, then a transaction replacing the
	// previous is broadcast, resulting in a replace-by-fee (RBF) scenario.
	BumpFee(context.Context, wire.OutPoint, chainfee.SatPerKWeight) error
}

WalletKitClient exposes wallet functionality.

Jump to

Keyboard shortcuts

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