loop

package module
v0.3.1-alpha Latest Latest
Warning

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

Go to latest
Published: Jan 15, 2020 License: MIT Imports: 31 Imported by: 1

README

Lightning Loop

Lightning Loop is a non-custodial service offered by Lightning Labs to bridge on-chain and off-chain Bitcoin using submarine swaps. This repository is home to the Loop client and depends on the Lightning Network daemon lnd. All of lnd’s supported chain backends are fully supported when using the Loop client: Neutrino, Bitcoin Core, and btcd.

In the current iteration of the Loop software, two swap types are supported:

  • off-chain to on-chain, where the Loop client sends funds off-chain in
  • on-chain to off-chain, where the Loop client sends funds to an on-chain address using an off-chain channel

We call off-chain to on-chain swaps, a Loop Out. The service can be used in various situations:

  • Acquiring inbound channel liquidity from arbitrary nodes on the Lightning network
  • Depositing funds to a Bitcoin on-chain address without closing active channels
  • Paying to on-chain fallback addresses in the case of insufficient route liquidity

We call our on-chain to off-chain swaps, a Loop In. This allows you to use on-chain funds to increase the local balance of a channel, effectively "refilling" an existing channel.

Potential uses for Loop In:

  • Refilling depleted channels with funds from cold-wallets or exchange withdrawals
  • Servicing off-chain Lightning withdrawals using on-chain payments, with no funds in channels required
  • As a failsafe payment method that can be used when channel liquidity along a route is insufficient

Development and Support

The Loop client is currently in an early beta state, and offers a simple command line application. Future APIs will be added to support implementation or use of the Loop service.

The Loop daemon exposes a gRPC API (defaults to port 11010) and a REST API (defaults to port 8081).

The GitHub issue tracker can be used to request specific improvements or register and get help with any problems. Community support is also available in the LND Slack .

Setup and Install

LND and the loop client are using Go modules. Make sure that the GO111MODULE env variable is set to on.

In order to execute a swap, You need to run lnd 0.7.1+, or master built with sub-servers enabled.

LND

If you are building from source, and not using a 0.7.1 or higher release of lnd, make sure that you are using the master branch of lnd. You can get this by git cloning the repository

git clone https://github.com/lightningnetwork/lnd.git

Once the lnd repository is cloned, it will need to be built with special build tags that enable the swap. This enables the required lnd rpc services.

cd lnd
make install tags="signrpc walletrpc chainrpc invoicesrpc routerrpc"

Check to see if you have already installed lnd. If you have, you will need to delete the .macaroon files from your lnd directory and restart lnd.

Do not delete any other files other than the .macaroon files

// Example on Linux to see macaroons in the default directory:
ls ~/.lnd/data/chain/bitcoin/mainnet

This should show no .macaroon files. If it does? Stop lnd, delete macaroons, restart lnd.

lncli stop

Now delete the .macaroon files and restart lnd. (don't delete any other files)

Loopd

After lnd is installed, you will need to clone the Lightning Loop repo and install the command line interface and swap client service.

git clone https://github.com/lightninglabs/loop.git
cd loop/cmd
go install ./...

Execute a Swap

After you have lnd and the Loop client installed, you can execute a Loop swap.

The Loop client needs its own short-lived daemon which will deal with the swaps in progress.

Command to start loopd::

loopd

// Or if you want to do everything in the same terminal and background loopd
loopd &

// For testnet mode, you'll need to specify the network as mainnet is the
default:
loopd --network=testnet

By default loopd attempts to connect to the lnd instance running on localhost:10009 and reads the macaroon and tls certificate from ~/.lnd. This can be altered using command line flags. See loopd --help.

loopd only listens on localhost and uses an unencrypted and unauthenticated connection.

Loop Out Swaps

Now that loopd is running, you can initiate a simple Loop Out. This will pay out Lightning off-chain funds and you will receive Bitcoin on-chain funds in return. There will be some chain and routing fees associated with this swap.

NAME:
   loop out - perform an off-chain to on-chain swap (looping out)

USAGE:
   loop out [command options] amt [addr]

DESCRIPTION:

  Attempts loop out the target amount into either the backing lnd's
  wallet, or a targeted address.

  The amount is to be specified in satoshis.

  Optionally a BASE58/bech32 encoded bitcoin destination address may be
  specified. If not specified, a new wallet address will be generated.

OPTIONS:
   --channel value  the 8-byte compact channel ID of the channel to loop out (default: 0)
   --addr value     the optional address that the looped out funds should be sent to, if left blank the funds will go to lnd's wallet
   --amt value      the amount in satoshis to loop out (default: 0)

It's possible to receive more inbound capacity on a particular channel (--channel), and also have the loop daemon send the coins to a target address (addr). The latter option allows ones to effectively send on-chain from their existing channels!

loop out <amt_in_satoshis>

This will take some time, as it requires an on-chain confirmation. When the swap is initiated successfully, loopd will see the process through.

To query in-flight swap statuses, run loop monitor.

Loop In Swaps

Additionally, Loop In is now also supported for mainnet as well. A Loop In swap lets one refill their channel (ability to send more coins) by sending to a special script on-chain.

NAME:
   loop in - perform an on-chain to off-chain swap (loop in)

USAGE:
   loop in [command options] amt

DESCRIPTION:

    Send the amount in satoshis specified by the amt argument off-chain.

OPTIONS:
   --amt value  the amount in satoshis to loop in (default: 0)
   --external   expect htlc to be published externally

The --external argument allows the on-chain HTLC transacting to be published externally. This allows for a number of use cases like using this address to withdraw from an exchange into your Lightning channel!

A Loop In swap can be executed a follows:

loop in <amt_in_satoshis>

Resume

When loopd is terminated (or killed) for whatever reason, it will pickup pending swaps after a restart.

Information about pending swaps is stored persistently in the swap database. Its location is ~/.loopd/<network>/loop.db.

Multiple Simultaneous Swaps

It is possible to execute multiple swaps simultaneously. Just keep loopd running.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrSwapFeeTooHigh is returned when the swap invoice amount is too
	// high.
	ErrSwapFeeTooHigh = errors.New("swap fee too high")

	// ErrPrepayAmountTooHigh is returned when the prepay invoice amount is
	// too high.
	ErrPrepayAmountTooHigh = errors.New("prepay amount too high")

	// ErrSwapAmountTooLow is returned when the requested swap amount is
	// less than the server minimum.
	ErrSwapAmountTooLow = errors.New("swap amount too low")

	// ErrSwapAmountTooHigh is returned when the requested swap amount is
	// more than the server maximum.
	ErrSwapAmountTooHigh = errors.New("swap amount too high")

	// ErrExpiryTooSoon is returned when the server proposes an expiry that
	// is too soon for us.
	ErrExpiryTooSoon = errors.New("swap expiry too soon")

	// ErrExpiryTooFar is returned when the server proposes an expiry that
	// is too soon for us.
	ErrExpiryTooFar = errors.New("swap expiry too far")

	// ErrSweepConfTargetTooFar is returned when the client proposes a
	// confirmation target to sweep the on-chain HTLC of a Loop Out that is
	// beyond the expiration height proposed by the server.
	ErrSweepConfTargetTooFar = errors.New("sweep confirmation target is " +
		"beyond swap expiration height")
)
View Source
var (
	// MaxLoopInAcceptDelta configures the maximum acceptable number of
	// remaining blocks until the on-chain htlc expires. This value is used
	// to decide whether we want to continue with the swap parameters as
	// proposed by the server. It is a protection to prevent the server from
	// getting us to lock up our funds to an arbitrary point in the future.
	MaxLoopInAcceptDelta = int32(1500)

	// MinLoopInPublishDelta defines the minimum number of remaining blocks
	// until on-chain htlc expiry required to proceed to publishing the htlc
	// tx. This value isn't critical, as we could even safely publish the
	// htlc after expiry. The reason we do implement this check is to
	// prevent us from publishing an htlc that the server surely wouldn't
	// follow up to.
	MinLoopInPublishDelta = int32(10)

	// TimeoutTxConfTarget defines the confirmation target for the loop in
	// timeout tx.
	TimeoutTxConfTarget = int32(2)
)
View Source
var (
	// MinLoopOutPreimageRevealDelta configures the minimum number of
	// remaining blocks before htlc expiry required to reveal preimage.
	MinLoopOutPreimageRevealDelta int32 = 20

	// DefaultSweepConfTarget is the default confirmation target we'll use
	// when sweeping on-chain HTLCs.
	DefaultSweepConfTarget int32 = 6

	// DefaultSweepConfTargetDelta is the delta of blocks from a Loop Out
	// swap's expiration height at which we begin to use the default sweep
	// confirmation target.
	//
	// TODO(wilmer): tune?
	DefaultSweepConfTargetDelta = DefaultSweepConfTarget * 2
)
View Source
var Commit string

Commit stores the current commit hash of this build, this should be set using the -ldflags during compilation.

Functions

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 Version

func Version() string

Version returns the application version as a properly formed string per the semantic versioning 2.0.0 spec (http://semver.org/).

Types

type Client

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

Client performs the client side part of swaps. This interface exists to be able to implement a stub.

func NewClient

func NewClient(dbDir string, serverAddress string, insecure bool,
	tlsPathServer string, lnd *lndclient.LndServices, maxLSATCost,
	maxLSATFee btcutil.Amount) (*Client, func(), error)

NewClient returns a new instance to initiate swaps with.

func (*Client) FetchSwaps

func (s *Client) FetchSwaps() ([]*SwapInfo, error)

FetchSwaps returns all loop in and out swaps currently in the database.

func (*Client) LoopIn

func (s *Client) LoopIn(globalCtx context.Context,
	request *LoopInRequest) (*lntypes.Hash, btcutil.Address, error)

LoopIn initiates a loop in swap.

func (*Client) LoopInQuote

func (s *Client) LoopInQuote(ctx context.Context,
	request *LoopInQuoteRequest) (*LoopInQuote, error)

LoopInQuote takes an amount and returns a break down of estimated costs for the client. Both the swap server and the on-chain fee estimator are queried to get to build the quote response.

func (*Client) LoopInTerms

func (s *Client) LoopInTerms(ctx context.Context) (
	*LoopInTerms, error)

LoopInTerms returns the terms on which the server executes swaps.

func (*Client) LoopOut

func (s *Client) LoopOut(globalCtx context.Context,
	request *OutRequest) (*lntypes.Hash, btcutil.Address, error)

LoopOut initiates a loop out swap. It blocks until the swap is initiation with the swap server is completed (typically this takes only a short amount of time). From there on further status information can be acquired through the status channel returned from the Run call.

When the call returns, the swap has been persisted and will be resumed automatically after restarts.

The return value is a hash that uniquely identifies the new swap.

func (*Client) LoopOutQuote

func (s *Client) LoopOutQuote(ctx context.Context,
	request *LoopOutQuoteRequest) (*LoopOutQuote, error)

LoopOutQuote takes a LoopOut amount and returns a break down of estimated costs for the client. Both the swap server and the on-chain fee estimator are queried to get to build the quote response.

func (*Client) LoopOutTerms

func (s *Client) LoopOutTerms(ctx context.Context) (
	*LoopOutTerms, error)

LoopOutTerms returns the terms on which the server executes swaps.

func (*Client) Run

func (s *Client) Run(ctx context.Context,
	statusChan chan<- SwapInfo) error

Run is a blocking call that executes all swaps. Any pending swaps are restored from persistent storage and resumed. Subsequent updates will be sent through the passed in statusChan. The function can be terminated by cancelling the context.

type In

type In struct {
	loopdb.LoopInContract

	SwapInfoKit

	// State where the swap is in.
	State loopdb.SwapState
}

In contains status information for a loop in swap.

func (*In) LastUpdate

func (s *In) LastUpdate() time.Time

LastUpdate returns the last update time of the swap

func (*In) SwapHash

func (s *In) SwapHash() lntypes.Hash

SwapHash returns the swap hash.

type LoopInQuote

type LoopInQuote struct {
	// SwapFee is the fee that the swap server is charging for the swap.
	SwapFee btcutil.Amount

	// MinerFee is an estimate of the on-chain fee that needs to be paid to
	// sweep the htlc.
	MinerFee btcutil.Amount

	// Time lock delta relative to current block height that swap server
	// will accept on the swap initiation call.
	CltvDelta int32
}

LoopInQuote contains estimates for the fees making up the total swap cost for the client.

type LoopInQuoteRequest

type LoopInQuoteRequest struct {
	// Amount specifies the requested swap amount in sat. This does not
	// include the swap and miner fee.
	Amount btcutil.Amount

	// HtlcConfTarget specifies the targeted confirmation target for the
	// client sweep tx.
	HtlcConfTarget int32

	// ExternalHtlc specifies whether the htlc is published by an external
	// source.
	ExternalHtlc bool
}

LoopInQuoteRequest specifies the swap parameters for which a quote is requested.

type LoopInRequest

type LoopInRequest struct {
	// Amount specifies the requested swap amount in sat. This does not
	// include the swap and miner fee.
	Amount btcutil.Amount

	// MaxSwapFee is the maximum we are willing to pay the server for the
	// swap. This value is not disclosed in the swap initiation call, but if
	// the server asks for a higher fee, we abort the swap. Typically this
	// value is taken from the response of the LoopInQuote call. It
	// includes the prepay amount.
	MaxSwapFee btcutil.Amount

	// MaxMinerFee is the maximum in on-chain fees that we are willing to
	// spent. If we publish the on-chain htlc and the fee estimate turns out
	// higher than this value, we cancel the swap.
	//
	// MaxMinerFee is typically taken from the response of the LoopInQuote
	// call.
	MaxMinerFee btcutil.Amount

	// HtlcConfTarget specifies the targeted confirmation target for the
	// client htlc tx.
	HtlcConfTarget int32

	// LoopInChannel optionally specifies the short channel id of the
	// channel to loop in.
	LoopInChannel *uint64

	// ExternalHtlc specifies whether the htlc is published by an external
	// source.
	ExternalHtlc bool
}

LoopInRequest contains the required parameters for the swap.

type LoopInTerms

type LoopInTerms struct {
	// MinSwapAmount is the minimum amount that the server requires for a
	// swap.
	MinSwapAmount btcutil.Amount

	// MaxSwapAmount is the maximum amount that the server accepts for a
	// swap.
	MaxSwapAmount btcutil.Amount
}

LoopInTerms are the server terms on which it executes loop in swaps.

type LoopOutQuote

type LoopOutQuote struct {
	// SwapFee is the fee that the swap server is charging for the swap.
	SwapFee btcutil.Amount

	// PrepayAmount is the part of the swap fee that is requested as a
	// prepayment.
	PrepayAmount btcutil.Amount

	// MinerFee is an estimate of the on-chain fee that needs to be paid to
	// sweep the htlc.
	MinerFee btcutil.Amount

	// Time lock delta relative to current block height that swap server
	// will accept on the swap initiation call.
	CltvDelta int32

	// SwapPaymentDest is the node pubkey where to swap payment needs to be
	// sent to.
	SwapPaymentDest [33]byte
}

LoopOutQuote contains estimates for the fees making up the total swap cost for the client.

type LoopOutQuoteRequest

type LoopOutQuoteRequest struct {
	// Amount specifies the requested swap amount in sat. This does not
	// include the swap and miner fee.
	Amount btcutil.Amount

	// SweepConfTarget specifies the targeted confirmation target for the
	// client sweep tx.
	SweepConfTarget int32

	// SwapPublicationDeadline can be set by the client to allow the server
	// delaying publication of the swap HTLC to save on chain fees.
	SwapPublicationDeadline time.Time
}

LoopOutQuoteRequest specifies the swap parameters for which a quote is requested.

type LoopOutTerms

type LoopOutTerms struct {
	// MinSwapAmount is the minimum amount that the server requires for a
	// swap.
	MinSwapAmount btcutil.Amount

	// MaxSwapAmount is the maximum amount that the server accepts for a
	// swap.
	MaxSwapAmount btcutil.Amount
}

LoopOutTerms are the server terms on which it executes swaps.

type Out

type Out struct {
	// LoopOutContract describes the details of this loop.Out. Using these
	// details,the full swap can be executed.
	loopdb.LoopOutContract

	// State is the current state of the target swap.
	State loopdb.SwapState

	// SwapInfoKit contains shared data amongst all swap types.
	SwapInfoKit
}

Out contains the full details of a loop out request. This includes things like the payment hash, the total value, and the final CTLV delay of the swap. We'll use this to track an active swap throughout that various swap stages.

type OutRequest

type OutRequest struct {
	// Amount specifies the requested swap amount in sat. This does not
	// include the swap and miner fee.
	Amount btcutil.Amount

	// Destination address for the swap.
	DestAddr btcutil.Address

	// MaxSwapRoutingFee is the maximum off-chain fee in msat that may be
	// paid for payment to the server. This limit is applied during path
	// finding. Typically this value is taken from the response of the
	// LoopOutQuote call.
	MaxSwapRoutingFee btcutil.Amount

	// MaxPrepayRoutingFee is the maximum off-chain fee in msat that may be
	// paid for payment to the server. This limit is applied during path
	// finding. Typically this value is taken from the response of the
	// LoopOutQuote call.
	MaxPrepayRoutingFee btcutil.Amount

	// MaxSwapFee is the maximum we are willing to pay the server for the
	// swap. This value is not disclosed in the swap initiation call, but
	// if the server asks for a higher fee, we abort the swap. Typically
	// this value is taken from the response of the LoopOutQuote call. It
	// includes the prepay amount.
	MaxSwapFee btcutil.Amount

	// MaxPrepayAmount is the maximum amount of the swap fee that may be
	// charged as a prepayment.
	MaxPrepayAmount btcutil.Amount

	// MaxMinerFee is the maximum in on-chain fees that we are willing to
	// spent. If we want to sweep the on-chain htlc and the fee estimate
	// turns out higher than this value, we cancel the swap. If the fee
	// estimate is lower, we publish the sweep tx.
	//
	// If the sweep tx isn't confirmed, we are forced to ratchet up fees
	// until it is swept. Possibly even exceeding MaxMinerFee if we get
	// close to the htlc timeout. Because the initial publication revealed
	// the preimage, we have no other choice. The server may already have
	// pulled the off-chain htlc. Only when the fee becomes higher than the
	// swap amount, we can only wait for fees to come down and hope - if we
	// are past the timeout - that the server isn't publishing the
	// revocation.
	//
	// MaxMinerFee is typically taken from the response of the
	// LoopOutQuote call.
	MaxMinerFee btcutil.Amount

	// SweepConfTarget specifies the targeted confirmation target for the
	// client sweep tx.
	SweepConfTarget int32

	// LoopOutChannel optionally specifies the short channel id of the
	// channel to loop out.
	LoopOutChannel *uint64

	// SwapPublicationDeadline can be set by the client to allow the server
	// delaying publication of the swap HTLC to save on chain fees.
	SwapPublicationDeadline time.Time
}

OutRequest contains the required parameters for a loop out swap.

type SwapInfo

type SwapInfo struct {
	loopdb.SwapStateData

	LastUpdate time.Time

	SwapHash lntypes.Hash

	SwapType swap.Type

	loopdb.SwapContract

	HtlcAddress btcutil.Address
}

SwapInfo exposes common info fields for loop in and loop out swaps.

type SwapInfoKit

type SwapInfoKit struct {
	// Hash is the sha256 hash of the preimage that unlocks the htlcs. It
	// is used to uniquely identify this swap.
	Hash lntypes.Hash

	// LastUpdateTime is the time of the last update of this swap.
	LastUpdateTime time.Time
}

SwapInfoKit contains common swap info fields.

Directories

Path Synopsis
cmd
Package looprpc is a reverse proxy.
Package looprpc is a reverse proxy.

Jump to

Keyboard shortcuts

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