peer

package
v0.0.0-...-4461705 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2022 License: MIT Imports: 52 Imported by: 0

Documentation

Index

Constants

View Source
const (

	// ErrorBufferSize is the number of historic peer errors that we store.
	ErrorBufferSize = 10
)

Variables

View Source
var (
	// ErrChannelNotFound is an error returned when a channel is queried and
	// either the Brontide doesn't know of it, or the channel in question
	// is pending.
	ErrChannelNotFound = fmt.Errorf("channel not found")
)

Functions

func DisableLog

func DisableLog()

DisableLog disables all logging output.

func UseLogger

func UseLogger(logger bronlog.Logger)

UseLogger uses a specified Logger to output package logging info.

func WaitForChanToClose

func WaitForChanToClose(bestHeight uint32, notifier chainntnfs.ChainNotifier,
	errChan chan error, chanPoint *wire.OutPoint,
	closingTxID *chainhash.Hash, closeScript []byte, cb func())

WaitForChanToClose uses the passed notifier to wait until the channel has been detected as closed on chain and then concludes by executing the following actions: the channel point will be sent over the settleChan, and finally the callback will be executed. If any error is encountered within the function, then it will be sent over the errChan.

Types

type Brontide

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

Brontide is an active peer on the Lightning Network. This struct is responsible for managing any channel state related to this peer. To do so, it has several helper goroutines to handle events such as HTLC timeouts, new funding workflow, and detecting an uncooperative closure of any active channels. TODO(roasbeef): proper reconnection logic

func NewBrontide

func NewBrontide(cfg Config) *Brontide

NewBrontide creates a new Brontide from a peer.Config struct.

func (*Brontide) ActiveSignal

func (p *Brontide) ActiveSignal() chan struct{}

ActiveSignal returns the peer's active signal.

func (*Brontide) AddNewChannel

func (p *Brontide) AddNewChannel(channel *channeldb.OpenChannel,
	cancel <-chan struct{}) error

AddNewChannel adds a new channel to the peer. The channel should fail to be added if the cancel channel is closed.

NOTE: Part of the lnpeer.Peer interface.

func (*Brontide) Address

func (p *Brontide) Address() net.Addr

Address returns the network address of the remote peer.

NOTE: Part of the lnpeer.Peer interface.

func (*Brontide) BytesReceived

func (p *Brontide) BytesReceived() uint64

BytesReceived returns the number of bytes received from the peer.

func (*Brontide) BytesSent

func (p *Brontide) BytesSent() uint64

BytesSent returns the number of bytes sent to the peer.

func (*Brontide) ChannelSnapshots

func (p *Brontide) ChannelSnapshots() []*channeldb.ChannelSnapshot

ChannelSnapshots returns a slice of channel snapshots detailing all currently active channels maintained with the remote peer.

func (*Brontide) Conn

func (p *Brontide) Conn() net.Conn

Conn returns a pointer to the peer's connection struct.

func (*Brontide) ConnReq

func (p *Brontide) ConnReq() *connmgr.ConnReq

ConnReq is a getter for the Brontide's connReq in cfg.

func (*Brontide) Disconnect

func (p *Brontide) Disconnect(reason error)

Disconnect terminates the connection with the remote peer. Additionally, a signal is sent to the server and htlcSwitch indicating the resources allocated to the peer can now be cleaned up.

func (*Brontide) ErrorBuffer

func (p *Brontide) ErrorBuffer() *queue.CircularBuffer

ErrorBuffer is a getter for the Brontide's errorBuffer in cfg.

func (*Brontide) HandleLocalCloseChanReqs

func (p *Brontide) HandleLocalCloseChanReqs(req *htlcswitch.ChanClose)

HandleLocalCloseChanReqs accepts a *htlcswitch.ChanClose and passes it onto the channelManager goroutine, which will shut down the link and possibly close the channel.

func (*Brontide) IdentityKey

func (p *Brontide) IdentityKey() *bronec.PublicKey

IdentityKey returns the public key of the remote peer.

NOTE: Part of the lnpeer.Peer interface.

func (*Brontide) Inbound

func (p *Brontide) Inbound() bool

Inbound is a getter for the Brontide's Inbound boolean in cfg.

func (*Brontide) LastRemotePingPayload

func (p *Brontide) LastRemotePingPayload() []byte

LastRemotePingPayload returns the last payload the remote party sent as part of their ping.

func (*Brontide) LocalFeatures

func (p *Brontide) LocalFeatures() *lnwire.FeatureVector

LocalFeatures returns the set of global features that has been advertised by the local node. This allows sub-systems that use this interface to gate their behavior off the set of negotiated feature bits.

NOTE: Part of the lnpeer.Peer interface.

func (*Brontide) NetAddress

func (p *Brontide) NetAddress() *lnwire.NetAddress

NetAddress returns the network of the remote peer as an lnwire.NetAddress.

func (*Brontide) PingTime

func (p *Brontide) PingTime() int64

PingTime returns the estimated ping time to the peer in microseconds.

func (*Brontide) PubKey

func (p *Brontide) PubKey() [33]byte

PubKey returns the pubkey of the peer in compressed serialized format.

NOTE: Part of the lnpeer.Peer interface.

func (*Brontide) QuitSignal

func (p *Brontide) QuitSignal() <-chan struct{}

QuitSignal is a method that should return a channel which will be sent upon or closed once the backing peer exits. This allows callers using the interface to cancel any processing in the event the backing implementation exits.

NOTE: Part of the lnpeer.Peer interface.

func (*Brontide) RemoteFeatures

func (p *Brontide) RemoteFeatures() *lnwire.FeatureVector

RemoteFeatures returns the set of global features that has been advertised by the remote node. This allows sub-systems that use this interface to gate their behavior off the set of negotiated feature bits.

NOTE: Part of the lnpeer.Peer interface.

func (*Brontide) SendMessage

func (p *Brontide) SendMessage(sync bool, msgs ...lnwire.Message) error

SendMessage sends a variadic number of high-priority messages to the remote peer. The first argument denotes if the method should block until the messages have been sent to the remote peer or an error is returned, otherwise it returns immediately after queuing.

NOTE: Part of the lnpeer.Peer interface.

func (*Brontide) SendMessageLazy

func (p *Brontide) SendMessageLazy(sync bool, msgs ...lnwire.Message) error

SendMessageLazy sends a variadic number of low-priority messages to the remote peer. The first argument denotes if the method should block until the messages have been sent to the remote peer or an error is returned, otherwise it returns immediately after queueing.

NOTE: Part of the lnpeer.Peer interface.

func (*Brontide) SetAddress

func (p *Brontide) SetAddress(address net.Addr)

SetAddress sets the remote peer's address given an address.

func (*Brontide) Start

func (p *Brontide) Start() error

Start starts all helper goroutines the peer needs for normal operations. In the case this peer has already been started, then this function is a noop.

func (*Brontide) StartTime

func (p *Brontide) StartTime() time.Time

StartTime returns the time at which the connection was established if the peer started successfully, and zero otherwise.

func (*Brontide) String

func (p *Brontide) String() string

String returns the string representation of this peer.

func (*Brontide) WaitForDisconnect

func (p *Brontide) WaitForDisconnect(ready chan struct{})

WaitForDisconnect waits until the peer has disconnected. A peer may be disconnected if the local or remote side terminates the connection, or an irrecoverable protocol error has been encountered. This method will only begin watching the peer's waitgroup after the ready channel or the peer's quit channel are signaled. The ready channel should only be signaled if a call to Start returns no error. Otherwise, if the peer fails to start, calling Disconnect will signal the quit channel and the method will not block, since no goroutines were spawned.

func (*Brontide) WipeChannel

func (p *Brontide) WipeChannel(chanPoint *wire.OutPoint)

WipeChannel removes the passed channel point from all indexes associated with the peer and the switch.

type ChannelCloseUpdate

type ChannelCloseUpdate struct {
	ClosingTxid []byte
	Success     bool
}

ChannelCloseUpdate contains the outcome of the close channel operation.

type Config

type Config struct {
	// Conn is the underlying network connection for this peer.
	Conn MessageConn

	// ConnReq stores information related to the persistent connection request
	// for this peer.
	ConnReq *connmgr.ConnReq

	// PubKeyBytes is the serialized, compressed public key of this peer.
	PubKeyBytes [33]byte

	// Addr is the network address of the peer.
	Addr *lnwire.NetAddress

	// Inbound indicates whether or not the peer is an inbound peer.
	Inbound bool

	// Features is the set of features that we advertise to the remote party.
	Features *lnwire.FeatureVector

	// LegacyFeatures is the set of features that we advertise to the remote
	// peer for backwards compatibility. Nodes that have not implemented
	// flat features will still be able to read our feature bits from the
	// legacy global field, but we will also advertise everything in the
	// default features field.
	LegacyFeatures *lnwire.FeatureVector

	// OutgoingCltvRejectDelta defines the number of blocks before expiry of
	// an htlc where we don't offer it anymore.
	OutgoingCltvRejectDelta uint32

	// ChanActiveTimeout specifies the duration the peer will wait to request
	// a channel reenable, beginning from the time the peer was started.
	ChanActiveTimeout time.Duration

	// ErrorBuffer stores a set of errors related to a peer. It contains error
	// messages that our peer has recently sent us over the wire and records of
	// unknown messages that were sent to us so that we can have a full track
	// record of the communication errors we have had with our peer. If we
	// choose to disconnect from a peer, it also stores the reason we had for
	// disconnecting.
	ErrorBuffer *queue.CircularBuffer

	// WritePool is the task pool that manages reuse of write buffers. Write
	// tasks are submitted to the pool in order to conserve the total number of
	// write buffers allocated at any one time, and decouple write buffer
	// allocation from the peer life cycle.
	WritePool *pool.Write

	// ReadPool is the task pool that manages reuse of read buffers.
	ReadPool *pool.Read

	// Switch is a pointer to the htlcswitch. It is used to setup, get, and
	// tear-down ChannelLinks.
	Switch messageSwitch

	// InterceptSwitch is a pointer to the InterceptableSwitch, a wrapper around
	// the regular Switch. We only export it here to pass ForwardPackets to the
	// ChannelLinkConfig.
	InterceptSwitch *htlcswitch.InterceptableSwitch

	// ChannelDB is used to fetch opened channels, and closed channels.
	ChannelDB *channeldb.ChannelStateDB

	// ChannelGraph is a pointer to the channel graph which is used to
	// query information about the set of known active channels.
	ChannelGraph *channeldb.ChannelGraph

	// ChainArb is used to subscribe to channel events, update contract signals,
	// and force close channels.
	ChainArb *contractcourt.ChainArbitrator

	// AuthGossiper is needed so that the Brontide impl can register with the
	// gossiper and process remote channel announcements.
	AuthGossiper *discovery.AuthenticatedGossiper

	// ChanStatusMgr is used to set or un-set the disabled bit in channel
	// updates.
	ChanStatusMgr *netann.ChanStatusManager

	// ChainIO is used to retrieve the best block.
	ChainIO lnwallet.BlockChainIO

	// FeeEstimator is used to compute our target ideal fee-per-kw when
	// initializing the coop close process.
	FeeEstimator chainfee.Estimator

	// Signer is used when creating *lnwallet.LightningChannel instances.
	Signer input.Signer

	// SigPool is used when creating *lnwallet.LightningChannel instances.
	SigPool *lnwallet.SigPool

	// Wallet is used to publish transactions and generates delivery
	// scripts during the coop close process.
	Wallet *lnwallet.LightningWallet

	// ChainNotifier is used to receive confirmations of a coop close
	// transaction.
	ChainNotifier chainntnfs.ChainNotifier

	// RoutingPolicy is used to set the forwarding policy for links created by
	// the Brontide.
	RoutingPolicy htlcswitch.ForwardingPolicy

	// Sphinx is used when setting up ChannelLinks so they can decode sphinx
	// onion blobs.
	Sphinx *hop.OnionProcessor

	// WitnessBeacon is used when setting up ChannelLinks so they can add any
	// preimages that they learn.
	WitnessBeacon contractcourt.WitnessBeacon

	// Invoices is passed to the ChannelLink on creation and handles all
	// invoice-related logic.
	Invoices *invoices.InvoiceRegistry

	// ChannelNotifier is used by the link to notify other sub-systems about
	// channel-related events and by the Brontide to subscribe to
	// ActiveLinkEvents.
	ChannelNotifier *channelnotifier.ChannelNotifier

	// HtlcNotifier is used when creating a ChannelLink.
	HtlcNotifier *htlcswitch.HtlcNotifier

	// TowerClient is used by legacy channels to backup revoked states.
	TowerClient wtclient.Client

	// AnchorTowerClient is used by anchor channels to backup revoked
	// states.
	AnchorTowerClient wtclient.Client

	// DisconnectPeer is used to disconnect this peer if the cooperative close
	// process fails.
	DisconnectPeer func(*bronec.PublicKey) error

	// GenNodeAnnouncement is used to send our node announcement to the remote
	// on startup.
	GenNodeAnnouncement func(bool,
		...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error)

	// PrunePersistentPeerConnection is used to remove all internal state
	// related to this peer in the server.
	PrunePersistentPeerConnection func([33]byte)

	// FetchLastChanUpdate fetches our latest channel update for a target
	// channel.
	FetchLastChanUpdate func(lnwire.ShortChannelID) (*lnwire.ChannelUpdate,
		error)

	// FundingManager is an implementation of the funding.Controller interface.
	FundingManager funding.Controller

	// Hodl is used when creating ChannelLinks to specify HodlFlags as
	// breakpoints in dev builds.
	Hodl *hodl.Config

	// UnsafeReplay is used when creating ChannelLinks to specify whether or
	// not to replay adds on its commitment tx.
	UnsafeReplay bool

	// MaxOutgoingCltvExpiry is used when creating ChannelLinks and is the max
	// number of blocks that funds could be locked up for when forwarding
	// payments.
	MaxOutgoingCltvExpiry uint32

	// MaxChannelFeeAllocation is used when creating ChannelLinks and is the
	// maximum percentage of total funds that can be allocated to a channel's
	// commitment fee. This only applies for the initiator of the channel.
	MaxChannelFeeAllocation float64

	// MaxAnchorsCommitFeeRate is the maximum fee rate we'll use as an
	// initiator for anchor channel commitments.
	MaxAnchorsCommitFeeRate chainfee.SatPerKWeight

	// CoopCloseTargetConfs is the confirmation target that will be used
	// to estimate the fee rate to use during a cooperative channel
	// closure initiated by the remote peer.
	CoopCloseTargetConfs uint32

	// ServerPubKey is the serialized, compressed public key of our lnd node.
	// It is used to determine which policy (channel edge) to pass to the
	// ChannelLink.
	ServerPubKey [33]byte

	// ChannelCommitInterval is the maximum time that is allowed to pass between
	// receiving a channel state update and signing the next commitment.
	// Setting this to a longer duration allows for more efficient channel
	// operations at the cost of latency.
	ChannelCommitInterval time.Duration

	// ChannelCommitBatchSize is the maximum number of channel state updates
	// that is accumulated before signing a new commitment.
	ChannelCommitBatchSize uint32

	// HandleCustomMessage is called whenever a custom message is received
	// from the peer.
	HandleCustomMessage func(peer [33]byte, msg *lnwire.Custom) error

	// PongBuf is a slice we'll reuse instead of allocating memory on the
	// heap. Since only reads will occur and no writes, there is no need
	// for any synchronization primitives. As a result, it's safe to share
	// this across multiple Peer struct instances.
	PongBuf []byte

	// Quit is the server's quit channel. If this is closed, we halt operation.
	Quit chan struct{}
}

Config defines configuration fields that are necessary for a peer object to function.

type LinkUpdater

type LinkUpdater interface {
	// TargetChanID returns the channel id of the link for which this message
	// is intended.
	TargetChanID() lnwire.ChannelID
}

LinkUpdater is an interface implemented by most messages in BOLT 2 that are allowed to update the channel state.

type MessageConn

type MessageConn interface {
	// RemoteAddr returns the remote address on the other end of the connection.
	RemoteAddr() net.Addr

	// LocalAddr returns the local address on our end of the connection.
	LocalAddr() net.Addr

	// Read reads bytes from the connection.
	Read([]byte) (int, error)

	// Write writes bytes to the connection.
	Write([]byte) (int, error)

	// SetDeadline sets the deadline for the connection.
	SetDeadline(time.Time) error

	// SetReadDeadline sets the read deadline.
	SetReadDeadline(time.Time) error

	// SetWriteDeadline sets the write deadline.
	SetWriteDeadline(time.Time) error

	// Close closes the connection.
	Close() error

	// Flush attempts a flush.
	Flush() (int, error)

	// WriteMessage writes the message.
	WriteMessage([]byte) error

	// ReadNextHeader reads the next header.
	ReadNextHeader() (uint32, error)

	// ReadNextBody reads the next body.
	ReadNextBody([]byte) ([]byte, error)
}

MessageConn is an interface implemented by anything that delivers an lnwire.Message using a net.Conn interface.

type PendingUpdate

type PendingUpdate struct {
	Txid        []byte
	OutputIndex uint32
}

PendingUpdate describes the pending state of a closing channel.

type TimestampedError

type TimestampedError struct {
	Error     error
	Timestamp time.Time
}

TimestampedError is a timestamped error that is used to store the most recent errors we have experienced with our peers.

Jump to

Keyboard shortcuts

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