htlcswitch

package
v0.0.0-...-a42b203 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2017 License: MIT Imports: 31 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrChannelLinkNotFound is used when channel link hasn't been found.
	ErrChannelLinkNotFound = errors.New("channel link not found")
)

Functions

func DisableLog

func DisableLog()

DisableLog disables all library log output. Logging output is disabled by default until UseLogger is called.

func ExpectedFee

func ExpectedFee(f ForwardingPolicy, htlcAmt btcutil.Amount) btcutil.Amount

ExpectedFee computes the expected fee for a given htlc amount. The value returned from this function is to be used as a sanity check when forwarding HTLC's to ensure that an incoming HTLC properly adheres to our propagated forwarding policy.

TODO(roasbeef): also add in current available channel bandwidth, inverse func

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.

Types

type ChanClose

type ChanClose struct {
	// CloseType is a variable which signals the type of channel closure the
	// peer should execute.
	CloseType ChannelCloseType

	// ChanPoint represent the id of the channel which should be closed.
	ChanPoint *wire.OutPoint

	// Updates is used by request creator to receive the notifications about
	// execution of the close channel request.
	Updates chan *lnrpc.CloseStatusUpdate

	// Err is used by request creator to receive request execution error.
	Err chan error
}

ChanClose represents a request which close a particular channel specified by its id.

type ChannelCloseType

type ChannelCloseType uint8

ChannelCloseType is a enum which signals the type of channel closure the peer should execute.

const (
	// CloseRegular indicates a regular cooperative channel closure
	// should be attempted.
	CloseRegular ChannelCloseType = iota

	// CloseBreach indicates that a channel breach has been dtected, and
	// the link should immediately be marked as unavailable.
	CloseBreach
)
type ChannelLink interface {
	// HandleSwitchPacket handles the switch packets. This packets might be
	// forwarded to us from another channel link in case the htlc update
	// came from another peer or if the update was created by user
	// initially.
	HandleSwitchPacket(*htlcPacket)

	// HandleChannelUpdate handles the htlc requests as settle/add/fail
	// which sent to us from remote peer we have a channel with.
	HandleChannelUpdate(lnwire.Message)

	// ChanID returns the channel ID for the channel link. The channel ID
	// is a more compact representation of a channel's full outpoint.
	ChanID() lnwire.ChannelID

	// ShortChanID returns the short channel ID for the channel link. The
	// short channel ID encodes the exact location in the main chain that
	// the original funding output can be found.
	ShortChanID() lnwire.ShortChannelID

	// UpdateForwardingPolicy updates the forwarding policy for the target
	// ChannelLink. Once updated, the link will use the new forwarding
	// policy to govern if it an incoming HTLC should be forwarded or not.
	UpdateForwardingPolicy(ForwardingPolicy)

	// Bandwidth returns the amount of satoshis which current link might
	// pass through channel link. The value returned from this method
	// represents the up to date available flow through the channel. This
	// takes into account any forwarded but un-cleared HTLC's, and any
	// HTLC's which have been set to the over flow queue.
	Bandwidth() btcutil.Amount

	// Stats return the statistics of channel link. Number of updates,
	// total sent/received satoshis.
	Stats() (uint64, btcutil.Amount, btcutil.Amount)

	// Peer returns the representation of remote peer with which we have
	// the channel link opened.
	Peer() Peer

	// Start/Stop are used to initiate the start/stop of the channel link
	// functioning.
	Start() error
	Stop()
}

ChannelLink is an interface which represents the subsystem for managing the incoming htlc requests, applying the changes to the channel, and also propagating/forwarding it to htlc switch.

 abstraction level
      ^
      |
      | - - - - - - - - - - - - Lightning - - - - - - - - - - - - -
      |
      | (Switch)		     (Switch)		       (Switch)
      |  Alice <-- channel link --> Bob <-- channel link --> Carol
	 |
      | - - - - - - - - - - - - - TCP - - - - - - - - - - - - - - -
      |
      |  (Peer) 		     (Peer)	                (Peer)
      |  Alice <----- tcp conn --> Bob <---- tcp conn -----> Carol
      |
func NewChannelLink(cfg ChannelLinkConfig, channel *lnwallet.LightningChannel,
	currentHeight uint32) ChannelLink

NewChannelLink creates a new instance of a ChannelLink given a configuration and active channel that will be used to verify/apply updates to.

type ChannelLinkConfig

type ChannelLinkConfig struct {
	// FwrdingPolicy is the initial forwarding policy to be used when
	// deciding whether to forwarding incoming HTLC's or not. This value
	// can be updated with subsequent calls to UpdateForwardingPolicy
	// targeted at a given ChannelLink concrete interface implementation.
	FwrdingPolicy ForwardingPolicy

	// Switch is a subsystem which is used to forward the incoming HTLC
	// packets according to the encoded hop forwarding information
	// contained in the forwarding blob within each HTLC.
	Switch *Switch

	// DecodeHopIterator function is responsible for decoding HTLC Sphinx
	// onion blob, and creating hop iterator which will give us next
	// destination of HTLC.
	DecodeHopIterator func(r io.Reader, rHash []byte) (HopIterator, lnwire.FailCode)

	// DecodeOnionObfuscator function is responsible for decoding HTLC
	// Sphinx onion blob, and creating onion failure obfuscator.
	DecodeOnionObfuscator func(r io.Reader) (Obfuscator, lnwire.FailCode)

	// GetLastChannelUpdate retrieves the latest routing policy for this
	// particular channel. This will be used to provide payment senders our
	// latest policy when sending encrypted error messages.
	GetLastChannelUpdate func() (*lnwire.ChannelUpdate, error)

	// Peer is a lightning network node with which we have the channel link
	// opened.
	Peer Peer

	// Registry is a sub-system which responsible for managing the invoices
	// in thread-safe manner.
	Registry InvoiceDatabase

	// BlockEpochs is an active block epoch event stream backed by an
	// active ChainNotifier instance. The ChannelLink will use new block
	// notifications sent over this channel to decide when a _new_ HTLC is
	// too close to expiry, and also when any active HTLC's have expired
	// (or are close to expiry).
	BlockEpochs *chainntnfs.BlockEpochEvent

	// SettledContracts is used to notify that a channel has peacefully
	// been closed. Once a channel has been closed the other subsystem no
	// longer needs to watch for breach closes.
	SettledContracts chan *wire.OutPoint

	// DebugHTLC should be turned on if you want all HTLCs sent to a node
	// with the debug htlc R-Hash are immediately settled in the next
	// available state transition.
	DebugHTLC bool
}

ChannelLinkConfig defines the configuration for the channel link. ALL elements within the configuration MUST be non-nil for channel link to carry out its duties.

type Config

type Config struct {
	// LocalChannelClose kicks-off the workflow to execute a cooperative
	// or forced unilateral closure of the channel initiated by a local
	// subsystem.
	LocalChannelClose func(pubKey []byte, request *ChanClose)

	// UpdateTopology sends the onion error failure topology update to router
	// subsystem.
	UpdateTopology func(msg *lnwire.ChannelUpdate) error
}

Config defines the configuration for the service. ALL elements within the configuration MUST be non-nil for the service to carry out its duties.

type Deobfuscator

type Deobfuscator interface {
	// Deobfuscate peels off each layer of onion encryption from the first
	// hop, to the source of the error. A fully populated
	// lnwire.FailureMessage is returned.
	Deobfuscate(lnwire.OpaqueReason) (lnwire.FailureMessage, error)
}

Deobfuscator is an interface that is used to decrypt the onion encrypted failure reason an extra out a well formed error.

type FailureDeobfuscator

type FailureDeobfuscator struct {
	*sphinx.OnionDeobfuscator
}

FailureDeobfuscator wraps the sphinx data obfuscator and adds awareness of the lnwire onion failure messages to it.

func (*FailureDeobfuscator) Deobfuscate

Deobfuscate peels off each layer of onion encryption from the first hop, to the source of the error. A fully populated lnwire.FailureMessage is returned.

NOTE: Part of the Obfuscator interface.

type FailureObfuscator

type FailureObfuscator struct {
	*sphinx.OnionObfuscator
}

FailureObfuscator is used to obfuscate the onion failure.

func (*FailureObfuscator) BackwardObfuscate

func (o *FailureObfuscator) BackwardObfuscate(reason lnwire.OpaqueReason) lnwire.OpaqueReason

BackwardObfuscate wraps an already encrypted opaque reason error in an additional layer of onion encryption. This process repeats until the error arrives at the source of the payment. We re-encrypt the message on the backwards path to ensure that the error is indistinguishable from any other error seen.

NOTE: Part of the Obfuscator interface.

func (*FailureObfuscator) InitialObfuscate

func (o *FailureObfuscator) InitialObfuscate(failure lnwire.FailureMessage) (lnwire.OpaqueReason, error)

InitialObfuscate transforms a concrete failure message into an encrypted opaque failure reason. This method will be used at the source that the error occurs. It differs from BackwardObfuscate slightly, in that it computes a proper MAC over the error.

NOTE: Part of the Obfuscator interface.

type ForwardingInfo

type ForwardingInfo struct {
	// Network is the target blockchain network that the HTLC will travel
	// over next.
	Network NetworkHop

	// NextHop is the channel ID of the next hop. The received HTLC should
	// be forwarded to this particular channel in order to continue the
	// end-to-end route.
	NextHop lnwire.ShortChannelID

	// AmountToForward is the amount that the receiving node should forward
	// to the next hop.
	AmountToForward btcutil.Amount

	// OutgoingCTLV is the specified value of the CTLV timelock to be used
	// in the outgoing HTLC.
	OutgoingCTLV uint32
}

ForwardingInfo contains all the information that is necessary to forward and incoming HTLC to the next hop encoded within a valid HopIterator instance. Forwarding links are to use this information to authenticate the information received within the incoming HTLC, to ensure that the prior hop didn't tamper with the end-to-end routing information at all.

type ForwardingPolicy

type ForwardingPolicy struct {
	// MinHTLC is the smallest HTLC that is to be forwarded.
	MinHTLC btcutil.Amount

	// BaseFee is the base fee, expressed in milli-satoshi that must be
	// paid for each incoming HTLC. This field, combined with FeeRate is
	// used to compute the required fee for a given HTLC.
	//
	// TODO(roasbeef): need to be in mSAT
	BaseFee btcutil.Amount

	// FeeRate is the fee rate, expressed in milli-satoshi that must be
	// paid for each incoming HTLC. This field combined with BaseFee is
	// used to compute the required fee for a given HTLC.
	FeeRate btcutil.Amount

	// TimeLockDelta is the absolute time-lock value, expressed in blocks,
	// that will be subtracted from an incoming HTLC's timelock value to
	// create the time-lock value for the forwarded outgoing HTLC. The
	// following constraint MUST hold for an HTLC to be forwarded:
	//
	//  * incomingHtlc.timeLock - timeLockDelta = fwdInfo.OutgoingCTLV
	//
	//    where fwdInfo is the forwarding information extracted from the
	//    per-hop payload of the incoming HTLC's onion packet.
	TimeLockDelta uint32
}

ForwardingPolicy describes the set of constraints that a given ChannelLink is to adhere to when forwarding HTLC's. For each incoming HTLC, this set of constraints will be consulted in order to ensure that adequate fees are paid, and our time-lock parameters are respected. In the event that an incoming HTLC violates any of these constraints, it is to be _rejected_ with the error possibly carrying along a ChannelUpdate message that includes the latest policy.

type HopIterator

type HopIterator interface {
	// ForwardingInstructions returns the set of fields that detail exactly
	// _how_ this hop should forward the HTLC to the next hop.
	// Additionally, the information encoded within the returned
	// ForwardingInfo is to be used by each hop to authenticate the
	// information given to it by the prior hop.
	ForwardingInstructions() ForwardingInfo

	// EncodeNextHop encodes the onion packet destined for the next hop
	// into the passed io.Writer.
	EncodeNextHop(w io.Writer) error
}

HopIterator is an interface that abstracts away the routing information included in HTLC's which includes the entirety of the payment path of an HTLC. This interface provides two basic method which carry out: how to interpret the forwarding information encoded within the HTLC packet, and hop to encode the forwarding information for the _next_ hop.

type InvoiceDatabase

type InvoiceDatabase interface {
	// LookupInvoice attempts to look up an invoice according to it's 32
	// byte payment hash.
	LookupInvoice(chainhash.Hash) (*channeldb.Invoice, error)

	// SettleInvoice attempts to mark an invoice corresponding to the
	// passed payment hash as fully settled.
	SettleInvoice(chainhash.Hash) error
}

InvoiceDatabase is an interface which represents the persistent subsystem which may search, lookup and settle invoices.

type NetworkHop

type NetworkHop uint8

NetworkHop indicates the blockchain network that is intended to be the next hop for a forwarded HTLC. The existnce of this field within the ForwardingInfo struct enables the ability for HTLC to cross chain-boundaries at will.

const (
	// BitcoinHop denotes that an HTLC is to be forwarded along the Bitcoin
	// link with the specified short channel ID.
	BitcoinHop NetworkHop = iota

	// LitecoinHop denotes that an HTLC is to be forwarded along the
	// Litecoin link with the specified short channel ID.
	LitecoinHop
)

func (NetworkHop) String

func (c NetworkHop) String() string

String returns the string representation of the target NetworkHop.

type Obfuscator

type Obfuscator interface {

	// InitialObfuscate transforms a concrete failure message into an
	// encrypted opaque failure reason. This method will be used at the
	// source that the error occurs. It differs from BackwardObfuscate
	// slightly, in that it computes a proper MAC over the error.
	InitialObfuscate(lnwire.FailureMessage) (lnwire.OpaqueReason, error)

	// BackwardObfuscate wraps an already encrypted opaque reason error in
	// an additional layer of onion encryption. This process repeats until
	// the error arrives at the source of the payment.
	BackwardObfuscate(lnwire.OpaqueReason) lnwire.OpaqueReason
}

Obfuscator is an interface that is used to encrypt HTLC related errors at the source of the error, and also at each intermediate hop all the way back to the source of the payment.

type OnionProcessor

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

OnionProcessor is responsible for keeping all sphinx dependent parts inside and expose only decoding function. With such approach we give freedom for subsystems which wants to decode sphinx path to not be dependable from sphinx at all.

NOTE: The reason for keeping decoder separated from hop iterator is too maintain the hop iterator abstraction. Without it the structures which using the hop iterator should contain sphinx router which makes their creations in tests dependent from the sphinx internal parts.

func NewOnionProcessor

func NewOnionProcessor(router *sphinx.Router) *OnionProcessor

NewOnionProcessor creates new instance of decoder.

func (*OnionProcessor) DecodeHopIterator

func (p *OnionProcessor) DecodeHopIterator(r io.Reader, rHash []byte) (HopIterator,
	lnwire.FailCode)

DecodeHopIterator attempts to decode a valid sphinx packet from the passed io.Reader instance using the rHash as the associated data when checking the relevant MACs during the decoding process.

func (*OnionProcessor) DecodeOnionObfuscator

func (p *OnionProcessor) DecodeOnionObfuscator(r io.Reader) (Obfuscator, lnwire.FailCode)

DecodeOnionObfuscator takes an io.Reader which should contain the onion packet as original received by a forwarding node and creates an Obfuscator instance using the derived shared secret. In the case that en error occurs, a lnwire failure code detailing the parsing failure will be returned.

type Peer

type Peer interface {
	// SendMessage sends message to remote peer.
	SendMessage(lnwire.Message) error

	// WipeChannel removes the passed channel from all indexes associated
	// with the peer.
	WipeChannel(*lnwallet.LightningChannel) error

	// PubKey returns the serialize public key of the source peer.
	PubKey() [33]byte

	// Disconnect disconnects with peer if we have error which we can't
	// properly handle.
	Disconnect(reason error)
}

Peer is an interface which represents the remote lightning node inside our system.

type Switch

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

Switch is the central messaging bus for all incoming/outgoing HTLCs. Connected peers with active channels are treated as named interfaces which refer to active channels as links. A link is the switch's message communication point with the goroutine that manages an active channel. New links are registered each time a channel is created, and unregistered once the channel is closed. The switch manages the hand-off process for multi-hop HTLCs, forwarding HTLCs initiated from within the daemon, and finally notifies users local-systems concerning their outstanding payment requests.

func New

func New(cfg Config) *Switch

New creates the new instance of htlc switch.

func (s *Switch) AddLink(link ChannelLink) error

AddLink is used to initiate the handling of the add link command. The request will be propagated and handled in the main goroutine.

func (s *Switch) CloseLink(chanPoint *wire.OutPoint,
	closeType ChannelCloseType) (chan *lnrpc.CloseStatusUpdate, chan error)

CloseLink creates and sends the close channel command.

func (s *Switch) GetLink(chanID lnwire.ChannelID) (ChannelLink, error)

GetLink is used to initiate the handling of the get link command. The request will be propagated/handled to/in the main goroutine.

func (*Switch) GetLinksByInterface

func (s *Switch) GetLinksByInterface(hop [33]byte) ([]ChannelLink, error)

GetLinksByInterface fetches all the links connected to a particular node identified by the serialized compressed form of its public key.

func (s *Switch) RemoveLink(chanID lnwire.ChannelID) error

RemoveLink is used to initiate the handling of the remove link command. The request will be propagated/handled to/in the main goroutine.

func (*Switch) SendHTLC

func (s *Switch) SendHTLC(nextNode [33]byte, htlc *lnwire.UpdateAddHTLC,
	deobfuscator Deobfuscator) ([sha256.Size]byte, error)

SendHTLC is used by other subsystems which aren't belong to htlc switch package in order to send the htlc update.

func (*Switch) Start

func (s *Switch) Start() error

Start starts all helper goroutines required for the operation of the switch.

func (*Switch) Stop

func (s *Switch) Stop() error

Stop gracefully stops all active helper goroutines, then waits until they've exited.

Jump to

Keyboard shortcuts

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