loop/instantout/manager.go
Slyghtning 508b9dfdc1
multi: require Loop Out permission for Instant Out
The InstantOut RPC accepts a caller-controlled dest_addr that becomes
the output of the cooperative sweepless sweep (and of the htlc success
sweep on the fallback path), so it is a fund-moving operation equivalent
to LoopOut. Until now it required only swap:execute, while LoopOut
requires both swap:execute and loop:out. A macaroon scoped to
swap:execute -- intended for, say, an autoloop scheduler or a quote
poller -- could therefore drain reservation balances to an attacker
address. ReservationRequest is analogous on the inbound side: it
triggers an outgoing LN prepayment, so it also belongs behind loop:out.

We also harden the address handling in instantout.Manager.NewInstantOut
to match validateLoopOutRequest:

  - sweepAddr.IsForNet(m.cfg.Network) is now enforced. btcutil
    .DecodeAddress is more permissive than IsForNet for some formats
    (notably anything that happens to share a network prefix); without
    the explicit network check cross-chain copy-paste mistakes parse
    silently and then sign over an unspendable output.
  - The address must be one of the formats Loop normally accepts: P2TR /
    P2WSH / P2WPKH / P2SH / P2PKH. Anything else (e.g. a future address
    type that the user's wallet would otherwise interpret differently)
    is rejected up front rather than failing later in the signing path.

InstantOutQuote and ReservationQuote stay on swap:read since they are
read-only.
2026-08-11 15:02:42 +02:00

289 lines
6.8 KiB
Go

package instantout
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/btcsuite/btcd/btcutil"
"github.com/lightninglabs/loop/fsm"
"github.com/lightninglabs/loop/instantout/reservation"
"github.com/lightninglabs/loop/swapserverrpc"
"github.com/lightningnetwork/lnd/lntypes"
)
var (
defaultStateWaitTime = 30 * time.Second
defaultCltv = 100
ErrSwapDoesNotExist = errors.New("swap does not exist")
)
// Manager manages the instantout state machines.
type Manager struct {
sync.Mutex
// cfg contains all the services that the reservation manager needs to
// operate.
cfg *Config
// activeInstantOuts contains all the active instantouts.
activeInstantOuts map[lntypes.Hash]*FSM
// currentHeight stores the currently best known block height.
currentHeight int32
// blockEpochChan receives new block heights.
blockEpochChan chan int32
runCtx context.Context
}
// NewInstantOutManager creates a new instantout manager.
func NewInstantOutManager(cfg *Config, height int32) *Manager {
return &Manager{
cfg: cfg,
activeInstantOuts: make(map[lntypes.Hash]*FSM),
blockEpochChan: make(chan int32),
currentHeight: height,
}
}
// Run runs the instantout manager.
func (m *Manager) Run(ctx context.Context, initChan chan struct{}) error {
log.Debugf("Starting instantout manager")
defer func() {
log.Debugf("Stopping instantout manager")
}()
runCtx, cancel := context.WithCancel(ctx)
defer cancel()
m.runCtx = runCtx
err := m.recoverInstantOuts(runCtx)
if err != nil {
close(initChan)
return err
}
newBlockChan, newBlockErrChan, err := m.cfg.ChainNotifier.
RegisterBlockEpochNtfn(ctx)
if err != nil {
close(initChan)
return err
}
close(initChan)
for {
select {
case <-runCtx.Done():
return nil
case height := <-newBlockChan:
m.Lock()
m.currentHeight = height
m.Unlock()
case err := <-newBlockErrChan:
return err
}
}
}
// recoverInstantOuts recovers all the active instantouts from the database.
func (m *Manager) recoverInstantOuts(ctx context.Context) error {
// Fetch all the active instantouts from the database.
activeInstantOuts, err := m.cfg.Store.ListInstantLoopOuts(ctx)
if err != nil {
return err
}
for _, instantOut := range activeInstantOuts {
if isFinalState(instantOut.State) {
continue
}
log.Debugf("Recovering instantout %v", instantOut.SwapHash)
instantOutFSM, err := NewFSMFromInstantOut(
m.cfg, instantOut,
)
if err != nil {
return err
}
m.activeInstantOuts[instantOut.SwapHash] = instantOutFSM
// As SendEvent can block, we'll start a goroutine to process
// the event.
recoverCtx := &RecoverInstantOutCtx{
currentHeight: m.currentHeight,
}
go func() {
err := instantOutFSM.SendEvent(ctx, OnRecover, recoverCtx)
if err != nil {
log.Errorf("FSM %v Error sending recover "+
"event %v, state: %v",
instantOutFSM.InstantOut.SwapHash, err,
instantOutFSM.InstantOut.State)
}
}()
}
return nil
}
// NewInstantOut creates a new instantout.
func (m *Manager) NewInstantOut(ctx context.Context,
reservations []reservation.ID, sweepAddress string,
maxSwapFee btcutil.Amount) (*FSM, error) {
if maxSwapFee < 0 {
return nil, fmt.Errorf("maximum swap fee must not be negative")
}
var (
sweepAddr btcutil.Address
err error
)
if sweepAddress != "" {
sweepAddr, err = btcutil.DecodeAddress(
sweepAddress, m.cfg.Network,
)
if err != nil {
return nil, err
}
if !sweepAddr.IsForNet(m.cfg.Network) {
return nil, fmt.Errorf("sweep address %s is not "+
"valid for network %s", sweepAddress,
m.cfg.Network.Name)
}
switch sweepAddr.(type) {
case *btcutil.AddressTaproot,
*btcutil.AddressWitnessScriptHash,
*btcutil.AddressWitnessPubKeyHash,
*btcutil.AddressScriptHash,
*btcutil.AddressPubKeyHash:
default:
return nil, fmt.Errorf("unsupported sweep address "+
"type %T", sweepAddr)
}
}
m.Lock()
// Create the instantout request.
request := &InitInstantOutCtx{
cltvExpiry: m.currentHeight + int32(defaultCltv),
reservations: reservations,
initationHeight: m.currentHeight,
protocolVersion: CurrentProtocolVersion(),
sweepAddress: sweepAddr,
maxSwapFee: maxSwapFee,
}
instantOut, err := NewFSM(m.cfg, ProtocolVersionFullReservation)
if err != nil {
m.Unlock()
return nil, err
}
m.activeInstantOuts[instantOut.InstantOut.SwapHash] = instantOut
m.Unlock()
// Start the instantout FSM.
go func() {
err := instantOut.SendEvent(m.runCtx, OnStart, request)
if err != nil {
log.Errorf("Error sending event: %v", err)
}
}()
// If everything went well, we'll wait for the instant out to be
// waiting for sweepless sweep to be confirmed.
err = instantOut.DefaultObserver.WaitForState(
ctx, defaultStateWaitTime, WaitForSweeplessSweepConfirmed,
fsm.WithAbortEarlyOnErrorOption(),
)
if err != nil {
return nil, err
}
return instantOut, nil
}
// GetActiveInstantOut returns an active instant out.
func (m *Manager) GetActiveInstantOut(swapHash lntypes.Hash) (*FSM, error) {
m.Lock()
defer m.Unlock()
fsm, ok := m.activeInstantOuts[swapHash]
if !ok {
return nil, ErrSwapDoesNotExist
}
// If the instant out is in a final state, we'll remove it from the
// active instant outs.
if isFinalState(fsm.InstantOut.State) {
delete(m.activeInstantOuts, swapHash)
}
return fsm, nil
}
type Quote struct {
// ServiceFee is the fee in sat that is paid to the loop service.
ServiceFee btcutil.Amount
// OnChainFee is the estimated on chain fee in sat.
OnChainFee btcutil.Amount
}
// GetInstantOutQuote returns a quote for an instant out.
func (m *Manager) GetInstantOutQuote(ctx context.Context,
amt btcutil.Amount, reservationIDs [][]byte) (Quote, error) {
if len(reservationIDs) == 0 {
return Quote{}, fmt.Errorf("no reservations selected")
}
if amt <= 0 {
return Quote{}, fmt.Errorf("no amount selected")
}
// Get the service fee.
quoteRes, err := m.cfg.InstantOutClient.GetInstantOutQuote(
ctx, &swapserverrpc.GetInstantOutQuoteRequest{
Amount: uint64(amt),
ReservationIds: reservationIDs,
},
)
if err != nil {
return Quote{}, err
}
// Get the offchain fee by getting the fee estimate from the lnd client
// and multiplying it by the estimated sweepless sweep transaction.
feeRate, err := m.cfg.Wallet.EstimateFeeRate(ctx, normalConfTarget)
if err != nil {
return Quote{}, err
}
// The on chain chainFee is the chainFee rate times the estimated
// sweepless sweep transaction size.
chainFee := feeRate.FeeForWeight(sweeplessSweepWeight(len(reservationIDs)))
return Quote{
ServiceFee: btcutil.Amount(quoteRes.SwapFee),
OnChainFee: chainFee,
}, nil
}
// ListInstantOuts returns all instant outs from the database.
func (m *Manager) ListInstantOuts(ctx context.Context) ([]*InstantOut, error) {
return m.cfg.Store.ListInstantLoopOuts(ctx)
}