funding

package
v0.18.0-beta.rc3 Latest Latest
Warning

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

Go to latest
Published: May 22, 2024 License: MIT Imports: 43 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MinBtcRemoteDelay is the minimum CSV delay we will require the remote
	// to use for its commitment transaction.
	MinBtcRemoteDelay uint16 = 144

	// MaxBtcRemoteDelay is the maximum CSV delay we will require the remote
	// to use for its commitment transaction.
	MaxBtcRemoteDelay uint16 = 2016

	// MinChanFundingSize is the smallest channel that we'll allow to be
	// created over the RPC interface.
	MinChanFundingSize = btcutil.Amount(20000)

	// MaxBtcFundingAmount is a soft-limit of the maximum channel size
	// currently accepted on the Bitcoin chain within the Lightning
	// Protocol. This limit is defined in BOLT-0002, and serves as an
	// initial precautionary limit while implementations are battle tested
	// in the real world.
	MaxBtcFundingAmount = btcutil.Amount(1<<24) - 1

	// MaxBtcFundingAmountWumbo is a soft-limit on the maximum size of wumbo
	// channels. This limit is 10 BTC and is the only thing standing between
	// you and limitless channel size (apart from 21 million cap).
	MaxBtcFundingAmountWumbo = btcutil.Amount(1000000000)

	// MaxWaitNumBlocksFundingConf is the maximum number of blocks to wait
	// for the funding transaction to be confirmed before forgetting
	// channels that aren't initiated by us. 2016 blocks is ~2 weeks.
	MaxWaitNumBlocksFundingConf = 2016
)
View Source
const Subsystem = "FNDG"

Subsystem defines the logging code for this subsystem.

Variables

View Source
var (
	// ErrFundingManagerShuttingDown is an error returned when attempting to
	// process a funding request/message but the funding manager has already
	// been signaled to shut down.
	ErrFundingManagerShuttingDown = errors.New("funding manager shutting " +
		"down")

	// ErrConfirmationTimeout is an error returned when we as a responder
	// are waiting for a funding transaction to confirm, but too many
	// blocks pass without confirmation.
	ErrConfirmationTimeout = errors.New("timeout waiting for funding " +
		"confirmation")
)

Functions

func DisableLog

func DisableLog()

DisableLog disables all logging output.

func UseLogger

func UseLogger(logger btclog.Logger)

UseLogger uses a specified Logger to output package logging info.

func WriteOutpoint

func WriteOutpoint(w io.Writer, o *wire.OutPoint) error

WriteOutpoint writes an outpoint to an io.Writer. This is not the same as the channeldb variant as this uses WriteVarBytes for the Hash.

Types

type BatchConfig

type BatchConfig struct {
	// RequestParser is the function that parses an incoming RPC request
	// into the internal funding initialization message.
	RequestParser RequestParser

	// ChannelOpener is the function that kicks off the initial channel open
	// negotiation with the peer.
	ChannelOpener ChannelOpener

	// ChannelAbandoner is the function that can abandon a channel in the
	// local database, graph and arbitrator state.
	ChannelAbandoner ChannelAbandoner

	// WalletKitServer is an instance of the wallet kit sub server that can
	// handle PSBT funding and finalization.
	WalletKitServer WalletKitServer

	// Wallet is an instance of the internal lightning wallet.
	Wallet Wallet

	// NetParams contains the current bitcoin network parameters.
	NetParams *chaincfg.Params

	// Quit is the channel that is selected on to recognize if the main
	// server is shutting down.
	Quit chan struct{}
}

BatchConfig is the configuration for executing a single batch transaction for opening multiple channels atomically.

type Batcher

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

Batcher is a type that can be used to perform an atomic funding of multiple channels within a single on-chain transaction.

func NewBatcher

func NewBatcher(cfg *BatchConfig) *Batcher

NewBatcher returns a new batch channel funding helper.

func (*Batcher) BatchFund

BatchFund starts the atomic batch channel funding process.

NOTE: This method should only be called once per instance.

type ChannelAbandoner

type ChannelAbandoner func(*wire.OutPoint) error

ChannelAbandoner is a function that can abandon a channel in the local database, graph and arbitrator state.

type ChannelOpener

type ChannelOpener func(*InitFundingMsg) (chan *lnrpc.OpenStatusUpdate,
	chan error)

ChannelOpener is a function that kicks off the initial channel open negotiation with the peer.

type Config

type Config struct {
	// Dev specifies config values used in integration test. For
	// production, this config will always be an empty struct.
	Dev *DevConfig

	// NoWumboChans indicates if we're to reject all incoming wumbo channel
	// requests, and also reject all outgoing wumbo channel requests.
	NoWumboChans bool

	// IDKey is the PublicKey that is used to identify this node within the
	// Lightning Network.
	IDKey *btcec.PublicKey

	// IDKeyLoc is the locator for the key that is used to identify this
	// node within the LightningNetwork.
	IDKeyLoc keychain.KeyLocator

	// Wallet handles the parts of the funding process that involves moving
	// funds from on-chain transaction outputs into Lightning channels.
	Wallet *lnwallet.LightningWallet

	// PublishTransaction facilitates the process of broadcasting a
	// transaction to the network.
	PublishTransaction func(*wire.MsgTx, string) error

	// UpdateLabel updates the label that a transaction has in our wallet,
	// overwriting any existing labels.
	UpdateLabel func(chainhash.Hash, string) error

	// FeeEstimator calculates appropriate fee rates based on historical
	// transaction information.
	FeeEstimator chainfee.Estimator

	// Notifier is used by the FundingManager to determine when the
	// channel's funding transaction has been confirmed on the blockchain
	// so that the channel creation process can be completed.
	Notifier chainntnfs.ChainNotifier

	// ChannelDB is the database that keeps track of all channel state.
	ChannelDB *channeldb.ChannelStateDB

	// SignMessage signs an arbitrary message with a given public key. The
	// actual digest signed is the double sha-256 of the message. In the
	// case that the private key corresponding to the passed public key
	// cannot be located, then an error is returned.
	//
	// TODO(roasbeef): should instead pass on this responsibility to a
	// distinct sub-system?
	SignMessage func(keyLoc keychain.KeyLocator,
		msg []byte, doubleHash bool) (*ecdsa.Signature, error)

	// CurrentNodeAnnouncement should return the latest, fully signed node
	// announcement from the backing Lightning Network node with a fresh
	// timestamp.
	CurrentNodeAnnouncement func() (lnwire.NodeAnnouncement, error)

	// SendAnnouncement is used by the FundingManager to send announcement
	// messages to the Gossiper to possibly broadcast to the greater
	// network. A set of optional message fields can be provided to populate
	// any information within the graph that is not included in the gossip
	// message.
	SendAnnouncement func(msg lnwire.Message,
		optionalFields ...discovery.OptionalMsgField) chan error

	// NotifyWhenOnline allows the FundingManager to register with a
	// subsystem that will notify it when the peer comes online. This is
	// used when sending the channelReady message, since it MUST be
	// delivered after the funding transaction is confirmed.
	//
	// NOTE: The peerChan channel must be buffered.
	NotifyWhenOnline func(peer [33]byte, peerChan chan<- lnpeer.Peer)

	// FindChannel queries the database for the channel with the given
	// channel ID. Providing the node's public key is an optimization that
	// prevents deserializing and scanning through all possible channels.
	FindChannel func(node *btcec.PublicKey,
		chanID lnwire.ChannelID) (*channeldb.OpenChannel, error)

	// TempChanIDSeed is a cryptographically random string of bytes that's
	// used as a seed to generate pending channel ID's.
	TempChanIDSeed [32]byte

	// DefaultRoutingPolicy is the default routing policy used when
	// initially announcing channels.
	DefaultRoutingPolicy models.ForwardingPolicy

	// DefaultMinHtlcIn is the default minimum incoming htlc value that is
	// set as a channel parameter.
	DefaultMinHtlcIn lnwire.MilliSatoshi

	// NumRequiredConfs is a function closure that helps the funding
	// manager decide how many confirmations it should require for a
	// channel extended to it. The function is able to take into account
	// the amount of the channel, and any funds we'll be pushed in the
	// process to determine how many confirmations we'll require.
	NumRequiredConfs func(btcutil.Amount, lnwire.MilliSatoshi) uint16

	// RequiredRemoteDelay is a function that maps the total amount in a
	// proposed channel to the CSV delay that we'll require for the remote
	// party. Naturally a larger channel should require a higher CSV delay
	// in order to give us more time to claim funds in the case of a
	// contract breach.
	RequiredRemoteDelay func(btcutil.Amount) uint16

	// RequiredRemoteChanReserve is a function closure that, given the
	// channel capacity and dust limit, will return an appropriate amount
	// for the remote peer's required channel reserve that is to be adhered
	// to at all times.
	RequiredRemoteChanReserve func(capacity,
		dustLimit btcutil.Amount) btcutil.Amount

	// RequiredRemoteMaxValue is a function closure that, given the channel
	// capacity, returns the amount of MilliSatoshis that our remote peer
	// can have in total outstanding HTLCs with us.
	RequiredRemoteMaxValue func(btcutil.Amount) lnwire.MilliSatoshi

	// RequiredRemoteMaxHTLCs is a function closure that, given the channel
	// capacity, returns the number of maximum HTLCs the remote peer can
	// offer us.
	RequiredRemoteMaxHTLCs func(btcutil.Amount) uint16

	// WatchNewChannel is to be called once a new channel enters the final
	// funding stage: waiting for on-chain confirmation. This method sends
	// the channel to the ChainArbitrator so it can watch for any on-chain
	// events related to the channel. We also provide the public key of the
	// node we're establishing a channel with for reconnection purposes.
	WatchNewChannel func(*channeldb.OpenChannel, *btcec.PublicKey) error

	// ReportShortChanID allows the funding manager to report the confirmed
	// short channel ID of a formerly pending zero-conf channel to outside
	// sub-systems.
	ReportShortChanID func(wire.OutPoint) error

	// ZombieSweeperInterval is the periodic time interval in which the
	// zombie sweeper is run.
	ZombieSweeperInterval time.Duration

	// ReservationTimeout is the length of idle time that must pass before
	// a reservation is considered a zombie.
	ReservationTimeout time.Duration

	// MinChanSize is the smallest channel size that we'll accept as an
	// inbound channel. We have such a parameter, as otherwise, nodes could
	// flood us with very small channels that would never really be usable
	// due to fees.
	MinChanSize btcutil.Amount

	// MaxChanSize is the largest channel size that we'll accept as an
	// inbound channel. We have such a parameter, so that you may decide how
	// WUMBO you would like your channel.
	MaxChanSize btcutil.Amount

	// MaxPendingChannels is the maximum number of pending channels we
	// allow for each peer.
	MaxPendingChannels int

	// RejectPush is set true if the fundingmanager should reject any
	// incoming channels having a non-zero push amount.
	RejectPush bool

	// MaxLocalCSVDelay is the maximum csv delay we will allow for our
	// commit output. Channels that exceed this value will be failed.
	MaxLocalCSVDelay uint16

	// NotifyOpenChannelEvent informs the ChannelNotifier when channels
	// transition from pending open to open.
	NotifyOpenChannelEvent func(wire.OutPoint)

	// OpenChannelPredicate is a predicate on the lnwire.OpenChannel message
	// and on the requesting node's public key that returns a bool which
	// tells the funding manager whether or not to accept the channel.
	OpenChannelPredicate chanacceptor.ChannelAcceptor

	// NotifyPendingOpenChannelEvent informs the ChannelNotifier when
	// channels enter a pending state.
	NotifyPendingOpenChannelEvent func(wire.OutPoint,
		*channeldb.OpenChannel)

	// EnableUpfrontShutdown specifies whether the upfront shutdown script
	// is enabled.
	EnableUpfrontShutdown bool

	// MaxAnchorsCommitFeeRate is the max commitment fee rate we'll use as
	// the initiator for channels of the anchor type.
	MaxAnchorsCommitFeeRate chainfee.SatPerKWeight

	// DeleteAliasEdge allows the Manager to delete an alias channel edge
	// from the graph. It also returns our local to-be-deleted policy.
	DeleteAliasEdge func(scid lnwire.ShortChannelID) (
		*models.ChannelEdgePolicy, error)

	// AliasManager is an implementation of the aliasHandler interface that
	// abstracts away the handling of many alias functions.
	AliasManager aliasHandler

	// IsSweeperOutpoint queries the sweeper store for successfully
	// published sweeps. This is useful to decide for the internal wallet
	// backed funding flow to not use utxos still being swept by the sweeper
	// subsystem.
	IsSweeperOutpoint func(wire.OutPoint) bool
}

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

type Controller

type Controller interface {
	// ProcessFundingMsg processes a funding message represented by the
	// lnwire.Message parameter along with the Peer object representing a
	// connection to the counterparty.
	ProcessFundingMsg(lnwire.Message, lnpeer.Peer)

	// IsPendingChannel returns whether a particular 32-byte identifier
	// represents a pending channel in the Controller implementation.
	IsPendingChannel([32]byte, lnpeer.Peer) bool
}

Controller is an interface with basic funding flow functions. It describes the basic functionality of a funding manager. It should at a minimum process a subset of lnwire messages that are denoted as funding messages.

type DevConfig

type DevConfig struct {
	// ProcessChannelReadyWait is the duration to sleep before processing
	// remote node's channel ready message once the channel as been marked
	// as `channelReadySent`.
	ProcessChannelReadyWait time.Duration
}

DevConfig specifies configs used for integration test only.

type InitFundingMsg

type InitFundingMsg struct {
	// Peer is the peer that we want to open a channel to.
	Peer lnpeer.Peer

	// TargetPubkey is the public key of the peer.
	TargetPubkey *btcec.PublicKey

	// ChainHash is the target genesis hash for this channel.
	ChainHash chainhash.Hash

	// SubtractFees set to true means that fees will be subtracted
	// from the LocalFundingAmt.
	SubtractFees bool

	// LocalFundingAmt is the size of the channel.
	LocalFundingAmt btcutil.Amount

	// BaseFee is the base fee charged for routing payments regardless of
	// the number of milli-satoshis sent.
	BaseFee *uint64

	// FeeRate is the fee rate in ppm (parts per million) that will be
	// charged proportionally based on the value of each forwarded HTLC, the
	// lowest possible rate is 0 with a granularity of 0.000001
	// (millionths).
	FeeRate *uint64

	// PushAmt is the amount pushed to the counterparty.
	PushAmt lnwire.MilliSatoshi

	// FundingFeePerKw is the fee for the funding transaction.
	FundingFeePerKw chainfee.SatPerKWeight

	// Private determines whether or not this channel will be private.
	Private bool

	// MinHtlcIn is the minimum incoming HTLC that we accept.
	MinHtlcIn lnwire.MilliSatoshi

	// RemoteCsvDelay is the CSV delay we require for the remote peer.
	RemoteCsvDelay uint16

	// RemoteChanReserve is the channel reserve we required for the remote
	// peer.
	RemoteChanReserve btcutil.Amount

	// MinConfs indicates the minimum number of confirmations that each
	// output selected to fund the channel should satisfy.
	MinConfs int32

	// ShutdownScript is an optional upfront shutdown script for the
	// channel. This value is optional, so may be nil.
	ShutdownScript lnwire.DeliveryAddress

	// MaxValueInFlight is the maximum amount of coins in MilliSatoshi
	// that can be pending within the channel. It only applies to the
	// remote party.
	MaxValueInFlight lnwire.MilliSatoshi

	// MaxHtlcs is the maximum number of HTLCs that the remote peer
	// can offer us.
	MaxHtlcs uint16

	// MaxLocalCsv is the maximum local csv delay we will accept from our
	// peer.
	MaxLocalCsv uint16

	// FundUpToMaxAmt is the maximum amount to try to commit to. If set, the
	// MinFundAmt field denotes the acceptable minimum amount to commit to,
	// while trying to commit as many coins as possible up to this value.
	FundUpToMaxAmt btcutil.Amount

	// MinFundAmt must be set iff FundUpToMaxAmt is set. It denotes the
	// minimum amount to commit to.
	MinFundAmt btcutil.Amount

	// Outpoints is a list of client-selected outpoints that should be used
	// for funding a channel. If LocalFundingAmt is specified then this
	// amount is allocated from the sum of outpoints towards funding. If
	// the FundUpToMaxAmt is specified the entirety of selected funds is
	// allocated towards channel funding.
	Outpoints []wire.OutPoint

	// ChanFunder is an optional channel funder that allows the caller to
	// control exactly how the channel funding is carried out. If not
	// specified, then the default chanfunding.WalletAssembler will be
	// used.
	ChanFunder chanfunding.Assembler

	// PendingChanID is not all zeroes (the default value), then this will
	// be the pending channel ID used for the funding flow within the wire
	// protocol.
	PendingChanID [32]byte

	// ChannelType allows the caller to use an explicit channel type for the
	// funding negotiation. This type will only be observed if BOTH sides
	// support explicit channel type negotiation.
	ChannelType *lnwire.ChannelType

	// Memo is any arbitrary information we wish to store locally about the
	// channel that will be useful to our future selves.
	Memo []byte

	// Updates is a channel which updates to the opening status of the
	// channel are sent on.
	Updates chan *lnrpc.OpenStatusUpdate

	// Err is a channel which errors encountered during the funding flow are
	// sent on.
	Err chan error
}

InitFundingMsg is sent by an outside subsystem to the funding manager in order to kick off a funding workflow with a specified target peer. The original request which defines the parameters of the funding workflow are embedded within this message giving the funding manager full context w.r.t the workflow.

type Manager

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

Manager acts as an orchestrator/bridge between the wallet's 'ChannelReservation' workflow, and the wire protocol's funding initiation messages. Any requests to initiate the funding workflow for a channel, either kicked-off locally or remotely are handled by the funding manager. Once a channel's funding workflow has been completed, any local callers, the local peer, and possibly the remote peer are notified of the completion of the channel workflow. Additionally, any temporary or permanent access controls between the wallet and remote peers are enforced via the funding manager.

func NewFundingManager

func NewFundingManager(cfg Config) (*Manager, error)

NewFundingManager creates and initializes a new instance of the fundingManager.

func (*Manager) CancelPeerReservations

func (f *Manager) CancelPeerReservations(nodePub [33]byte)

CancelPeerReservations cancels all active reservations associated with the passed node. This will ensure any outputs which have been pre committed, (and thus locked from coin selection), are properly freed.

func (*Manager) InitFundingWorkflow

func (f *Manager) InitFundingWorkflow(msg *InitFundingMsg)

InitFundingWorkflow sends a message to the funding manager instructing it to initiate a single funder workflow with the source peer. TODO(roasbeef): re-visit blocking nature..

func (*Manager) IsPendingChannel

func (f *Manager) IsPendingChannel(pendingChanID [32]byte,
	peer lnpeer.Peer) bool

IsPendingChannel returns a boolean indicating whether the channel identified by the pendingChanID and given peer is pending, meaning it is in the process of being funded. After the funding transaction has been confirmed, the channel will receive a new, permanent channel ID, and will no longer be considered pending.

func (*Manager) ProcessFundingMsg

func (f *Manager) ProcessFundingMsg(msg lnwire.Message, peer lnpeer.Peer)

ProcessFundingMsg sends a message to the internal fundingManager goroutine, allowing it to handle the lnwire.Message.

func (*Manager) Start

func (f *Manager) Start() error

Start launches all helper goroutines required for handling requests sent to the funding manager.

func (*Manager) Stop

func (f *Manager) Stop() error

Stop signals all helper goroutines to execute a graceful shutdown. This method will block until all goroutines have exited.

type RequestParser

type RequestParser func(*lnrpc.OpenChannelRequest) (*InitFundingMsg, error)

RequestParser is a function that parses an incoming RPC request into the internal funding initialization message.

type Wallet

type Wallet interface {
	// PsbtFundingVerify looks up a previously registered funding intent by
	// its pending channel ID and tries to advance the state machine by
	// verifying the passed PSBT.
	PsbtFundingVerify([32]byte, *psbt.Packet, bool) error

	// PsbtFundingFinalize looks up a previously registered funding intent
	// by its pending channel ID and tries to advance the state machine by
	// finalizing the passed PSBT.
	PsbtFundingFinalize([32]byte, *psbt.Packet, *wire.MsgTx) error

	// PublishTransaction performs cursory validation (dust checks, etc),
	// then finally broadcasts the passed transaction to the Bitcoin
	// network.
	PublishTransaction(*wire.MsgTx, string) error

	// CancelFundingIntent allows a caller to cancel a previously registered
	// funding intent. If no intent was found, then an error will be
	// returned.
	CancelFundingIntent([32]byte) error
}

Wallet is a local interface that abstracts away the methods we need from the internal lightning wallet instance.

type WalletKitServer

type WalletKitServer interface {
	// FundPsbt creates a fully populated PSBT that contains enough inputs
	// to fund the outputs specified in the template.
	FundPsbt(context.Context,
		*walletrpc.FundPsbtRequest) (*walletrpc.FundPsbtResponse, error)

	// FinalizePsbt expects a partial transaction with all inputs and
	// outputs fully declared and tries to sign all inputs that belong to
	// the wallet.
	FinalizePsbt(context.Context,
		*walletrpc.FinalizePsbtRequest) (*walletrpc.FinalizePsbtResponse,
		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(context.Context,
		*walletrpc.ReleaseOutputRequest) (*walletrpc.ReleaseOutputResponse,
		error)
}

WalletKitServer is a local interface that abstracts away the methods we need from the wallet kit sub server instance.

Jump to

Keyboard shortcuts

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