2019-03-12 15:10:37 +00:00
|
|
|
package loop
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"crypto/rand"
|
|
|
|
"crypto/sha256"
|
2020-05-29 09:27:47 +00:00
|
|
|
"errors"
|
2019-03-12 15:10:37 +00:00
|
|
|
"fmt"
|
2020-07-16 10:01:02 +00:00
|
|
|
"sync"
|
2019-03-12 15:10:37 +00:00
|
|
|
"time"
|
|
|
|
|
2023-01-06 16:16:17 +00:00
|
|
|
"github.com/btcsuite/btcd/btcec/v2"
|
2022-03-14 12:36:02 +00:00
|
|
|
"github.com/btcsuite/btcd/btcutil"
|
2020-06-25 10:35:22 +00:00
|
|
|
"github.com/btcsuite/btcd/chaincfg/chainhash"
|
2021-03-03 09:21:24 +00:00
|
|
|
"github.com/btcsuite/btcd/mempool"
|
2019-03-12 15:10:37 +00:00
|
|
|
"github.com/btcsuite/btcd/wire"
|
2020-06-17 20:25:57 +00:00
|
|
|
"github.com/lightninglabs/lndclient"
|
2020-10-15 07:15:25 +00:00
|
|
|
"github.com/lightninglabs/loop/labels"
|
2019-03-12 15:10:37 +00:00
|
|
|
"github.com/lightninglabs/loop/loopdb"
|
2019-10-09 10:36:16 +00:00
|
|
|
"github.com/lightninglabs/loop/swap"
|
2023-11-14 00:52:39 +00:00
|
|
|
"github.com/lightninglabs/loop/utils"
|
2020-06-25 10:35:22 +00:00
|
|
|
"github.com/lightningnetwork/lnd/chainntnfs"
|
2023-01-09 15:36:52 +00:00
|
|
|
invpkg "github.com/lightningnetwork/lnd/invoices"
|
2023-01-06 16:16:17 +00:00
|
|
|
"github.com/lightningnetwork/lnd/keychain"
|
2020-06-25 10:35:22 +00:00
|
|
|
"github.com/lightningnetwork/lnd/lnrpc/invoicesrpc"
|
2022-07-07 15:28:22 +00:00
|
|
|
"github.com/lightningnetwork/lnd/lnrpc/walletrpc"
|
2019-03-12 15:10:37 +00:00
|
|
|
"github.com/lightningnetwork/lnd/lntypes"
|
2021-03-03 09:21:24 +00:00
|
|
|
"github.com/lightningnetwork/lnd/lnwallet/chainfee"
|
2020-06-25 10:35:22 +00:00
|
|
|
"github.com/lightningnetwork/lnd/lnwire"
|
2021-10-19 22:05:59 +00:00
|
|
|
"github.com/lightningnetwork/lnd/routing/route"
|
2019-03-12 15:10:37 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
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)
|
2023-11-13 13:50:10 +00:00
|
|
|
|
|
|
|
// ErrSwapFinalized is returned when a to be executed swap is already in
|
|
|
|
// a final state.
|
|
|
|
ErrSwapFinalized = errors.New("swap is in a final state")
|
2019-03-12 15:10:37 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// loopInSwap contains all the in-memory state related to a pending loop in
|
|
|
|
// swap.
|
|
|
|
type loopInSwap struct {
|
|
|
|
swapKit
|
|
|
|
|
2020-04-29 17:47:27 +00:00
|
|
|
executeConfig
|
|
|
|
|
2019-03-12 15:10:37 +00:00
|
|
|
loopdb.LoopInContract
|
|
|
|
|
2020-04-29 17:47:27 +00:00
|
|
|
htlc *swap.Htlc
|
|
|
|
|
2020-04-24 15:35:32 +00:00
|
|
|
htlcP2WSH *swap.Htlc
|
|
|
|
|
2022-04-24 20:59:41 +00:00
|
|
|
htlcP2TR *swap.Htlc
|
|
|
|
|
2020-06-25 10:35:22 +00:00
|
|
|
// htlcTxHash is the confirmed htlc tx id.
|
|
|
|
htlcTxHash *chainhash.Hash
|
|
|
|
|
2019-03-12 15:10:37 +00:00
|
|
|
timeoutAddr btcutil.Address
|
2020-07-16 10:01:02 +00:00
|
|
|
|
2023-11-13 13:50:10 +00:00
|
|
|
abandonChan chan struct{}
|
|
|
|
|
2020-07-16 10:01:02 +00:00
|
|
|
wg sync.WaitGroup
|
2019-03-12 15:10:37 +00:00
|
|
|
}
|
|
|
|
|
2020-06-30 12:06:36 +00:00
|
|
|
// loopInInitResult contains information about a just-initiated loop in swap.
|
|
|
|
type loopInInitResult struct {
|
2020-06-30 12:10:33 +00:00
|
|
|
swap *loopInSwap
|
|
|
|
serverMessage string
|
2020-06-30 12:06:36 +00:00
|
|
|
}
|
|
|
|
|
2019-03-12 15:10:37 +00:00
|
|
|
// newLoopInSwap initiates a new loop in swap.
|
|
|
|
func newLoopInSwap(globalCtx context.Context, cfg *swapConfig,
|
2020-06-30 12:06:36 +00:00
|
|
|
currentHeight int32, request *LoopInRequest) (*loopInInitResult,
|
|
|
|
error) {
|
2019-03-12 15:10:37 +00:00
|
|
|
|
2021-10-19 22:05:59 +00:00
|
|
|
var err error
|
|
|
|
|
2023-06-26 10:51:25 +00:00
|
|
|
// Private and route hints are mutually exclusive as setting private
|
|
|
|
// means we retrieve our own route hints from the connected node.
|
2021-10-19 22:05:59 +00:00
|
|
|
if len(request.RouteHints) != 0 && request.Private {
|
|
|
|
return nil, fmt.Errorf("private and route_hints both set")
|
|
|
|
}
|
|
|
|
|
2023-06-26 10:51:25 +00:00
|
|
|
// If Private is set, we generate route hints.
|
2021-10-19 22:05:59 +00:00
|
|
|
if request.Private {
|
2023-06-26 10:51:25 +00:00
|
|
|
// If last_hop is set, we'll only add channels with peers set to
|
|
|
|
// the last_hop parameter.
|
2021-10-19 22:05:59 +00:00
|
|
|
includeNodes := make(map[route.Vertex]struct{})
|
|
|
|
if request.LastHop != nil {
|
|
|
|
includeNodes[*request.LastHop] = struct{}{}
|
|
|
|
}
|
|
|
|
|
2023-06-26 10:51:25 +00:00
|
|
|
// Because the Private flag is set, we'll generate our own set
|
|
|
|
// of hop hints.
|
2021-10-19 22:05:59 +00:00
|
|
|
request.RouteHints, err = SelectHopHints(
|
2024-06-14 10:37:58 +00:00
|
|
|
globalCtx, cfg.lnd.Client, request.Amount,
|
|
|
|
DefaultMaxHopHints, includeNodes,
|
2021-10-19 22:05:59 +00:00
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-12 15:10:37 +00:00
|
|
|
// Request current server loop in terms and use these to calculate the
|
|
|
|
// swap fee that we should subtract from the swap amount in the payment
|
2021-07-28 16:11:45 +00:00
|
|
|
// request that we send to the server. We pass nil as optional route
|
|
|
|
// hints as hop hint selection when generating invoices with private
|
2023-06-26 10:51:25 +00:00
|
|
|
// channels is an LND side black box feature. Advanced users will quote
|
|
|
|
// directly anyway and there they have the option to add specific route
|
|
|
|
// hints.
|
2021-05-10 14:55:53 +00:00
|
|
|
quote, err := cfg.server.GetLoopInQuote(
|
|
|
|
globalCtx, request.Amount, cfg.lnd.NodePubkey, request.LastHop,
|
2023-06-20 18:52:07 +00:00
|
|
|
request.RouteHints, request.Initiator,
|
2021-05-10 14:55:53 +00:00
|
|
|
)
|
2019-03-12 15:10:37 +00:00
|
|
|
if err != nil {
|
2021-07-19 08:01:33 +00:00
|
|
|
return nil, wrapGrpcError("loop in terms", err)
|
2019-03-12 15:10:37 +00:00
|
|
|
}
|
|
|
|
|
2019-10-08 20:28:20 +00:00
|
|
|
swapFee := quote.SwapFee
|
2019-03-12 15:10:37 +00:00
|
|
|
|
|
|
|
if swapFee > request.MaxSwapFee {
|
2019-10-28 16:06:07 +00:00
|
|
|
log.Warnf("Swap fee %v exceeding maximum of %v",
|
2019-03-12 15:10:37 +00:00
|
|
|
swapFee, request.MaxSwapFee)
|
|
|
|
|
|
|
|
return nil, ErrSwapFeeTooHigh
|
|
|
|
}
|
|
|
|
|
|
|
|
// Calculate the swap invoice amount. The prepay is added which
|
|
|
|
// effectively forces the server to pay us back our prepayment on a
|
|
|
|
// successful swap.
|
|
|
|
swapInvoiceAmt := request.Amount - swapFee
|
|
|
|
|
|
|
|
// Generate random preimage.
|
|
|
|
var swapPreimage lntypes.Preimage
|
|
|
|
if _, err := rand.Read(swapPreimage[:]); err != nil {
|
2019-10-28 16:06:07 +00:00
|
|
|
log.Error("Cannot generate preimage")
|
2019-03-12 15:10:37 +00:00
|
|
|
}
|
|
|
|
swapHash := lntypes.Hash(sha256.Sum256(swapPreimage[:]))
|
|
|
|
|
|
|
|
// Derive a sender key for this swap.
|
|
|
|
keyDesc, err := cfg.lnd.WalletKit.DeriveNextKey(
|
|
|
|
globalCtx, swap.KeyFamily,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
var senderKey [33]byte
|
|
|
|
copy(senderKey[:], keyDesc.PubKey.SerializeCompressed())
|
|
|
|
|
|
|
|
// Create the swap invoice in lnd.
|
|
|
|
_, swapInvoice, err := cfg.lnd.Client.AddInvoice(
|
|
|
|
globalCtx, &invoicesrpc.AddInvoiceData{
|
2021-10-19 22:05:59 +00:00
|
|
|
Preimage: &swapPreimage,
|
|
|
|
Value: lnwire.NewMSatFromSatoshis(swapInvoiceAmt),
|
|
|
|
Memo: "swap",
|
|
|
|
Expiry: 3600 * 24 * 365,
|
|
|
|
RouteHints: request.RouteHints,
|
2019-03-12 15:10:37 +00:00
|
|
|
},
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2020-05-29 09:27:47 +00:00
|
|
|
// Create the probe invoice in lnd. Derive the payment hash
|
|
|
|
// deterministically from the swap hash in such a way that the server
|
|
|
|
// can be sure that we don't know the preimage.
|
|
|
|
probeHash := lntypes.Hash(sha256.Sum256(swapHash[:]))
|
|
|
|
probeHash[0] ^= 1
|
|
|
|
|
|
|
|
log.Infof("Creating probe invoice %v", probeHash)
|
|
|
|
probeInvoice, err := cfg.lnd.Invoices.AddHoldInvoice(
|
|
|
|
globalCtx, &invoicesrpc.AddInvoiceData{
|
2021-10-19 22:05:59 +00:00
|
|
|
Hash: &probeHash,
|
|
|
|
Value: lnwire.NewMSatFromSatoshis(swapInvoiceAmt),
|
|
|
|
Memo: "loop in probe",
|
|
|
|
Expiry: 3600,
|
|
|
|
RouteHints: request.RouteHints,
|
2020-05-29 09:27:47 +00:00
|
|
|
},
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2023-01-06 16:16:17 +00:00
|
|
|
// Default the HTLC internal key to our sender key.
|
|
|
|
senderInternalPubKey := senderKey
|
|
|
|
|
2023-06-26 10:51:25 +00:00
|
|
|
// If this is a MuSig2 swap then we'll generate a brand new key pair and
|
|
|
|
// will use that as the internal key for the HTLC.
|
2023-01-06 16:16:17 +00:00
|
|
|
if loopdb.CurrentProtocolVersion() >= loopdb.ProtocolVersionMuSig2 {
|
|
|
|
secret, err := sharedSecretFromHash(
|
|
|
|
globalCtx, cfg.lnd.Signer, swapHash,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
_, pubKey := btcec.PrivKeyFromBytes(secret[:])
|
|
|
|
copy(senderInternalPubKey[:], pubKey.SerializeCompressed())
|
|
|
|
}
|
|
|
|
|
2020-05-29 09:27:47 +00:00
|
|
|
// Create a cancellable context that is used for monitoring the probe.
|
|
|
|
probeWaitCtx, probeWaitCancel := context.WithCancel(globalCtx)
|
|
|
|
|
|
|
|
// Launch a goroutine to monitor the probe.
|
|
|
|
probeResult, err := awaitProbe(probeWaitCtx, *cfg.lnd, probeHash)
|
|
|
|
if err != nil {
|
|
|
|
probeWaitCancel()
|
|
|
|
return nil, fmt.Errorf("probe failed: %v", err)
|
|
|
|
}
|
|
|
|
|
2019-03-12 15:10:37 +00:00
|
|
|
// Post the swap parameters to the swap server. The response contains
|
|
|
|
// the server success key and the expiry height of the on-chain swap
|
|
|
|
// htlc.
|
2019-10-28 16:06:07 +00:00
|
|
|
log.Infof("Initiating swap request at height %v", currentHeight)
|
2019-03-12 15:10:37 +00:00
|
|
|
swapResp, err := cfg.server.NewLoopInSwap(globalCtx, swapHash,
|
2023-01-06 16:16:17 +00:00
|
|
|
request.Amount, senderKey, senderInternalPubKey, swapInvoice,
|
|
|
|
probeInvoice, request.LastHop, request.Initiator,
|
2019-03-12 15:10:37 +00:00
|
|
|
)
|
2020-05-29 09:27:47 +00:00
|
|
|
probeWaitCancel()
|
2019-03-12 15:10:37 +00:00
|
|
|
if err != nil {
|
2021-07-19 08:01:33 +00:00
|
|
|
return nil, wrapGrpcError("cannot initiate swap", err)
|
2019-03-12 15:10:37 +00:00
|
|
|
}
|
|
|
|
|
2020-05-29 09:27:47 +00:00
|
|
|
// Because the context is cancelled, it is guaranteed that we will be
|
|
|
|
// able to read from the probeResult channel.
|
|
|
|
err = <-probeResult
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("probe error: %v", err)
|
|
|
|
}
|
|
|
|
|
2023-06-26 10:51:25 +00:00
|
|
|
// Validate if the response parameters are outside our allowed range
|
|
|
|
// preventing us from continuing with a swap.
|
2022-12-15 15:43:38 +00:00
|
|
|
err = validateLoopInContract(currentHeight, swapResp)
|
2019-03-12 15:10:37 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Instantiate a struct that contains all required data to start the
|
|
|
|
// swap.
|
|
|
|
initiationTime := time.Now()
|
|
|
|
|
|
|
|
contract := loopdb.LoopInContract{
|
|
|
|
HtlcConfTarget: request.HtlcConfTarget,
|
2020-02-11 12:25:03 +00:00
|
|
|
LastHop: request.LastHop,
|
2019-03-28 12:29:21 +00:00
|
|
|
ExternalHtlc: request.ExternalHtlc,
|
2019-03-12 15:10:37 +00:00
|
|
|
SwapContract: loopdb.SwapContract{
|
|
|
|
InitiationHeight: currentHeight,
|
|
|
|
InitiationTime: initiationTime,
|
2023-01-05 17:16:05 +00:00
|
|
|
HtlcKeys: loopdb.HtlcKeys{
|
|
|
|
SenderScriptKey: senderKey,
|
|
|
|
SenderInternalPubKey: senderKey,
|
|
|
|
ReceiverScriptKey: swapResp.receiverKey,
|
|
|
|
ReceiverInternalPubKey: swapResp.receiverKey,
|
|
|
|
ClientScriptKeyLocator: keyDesc.KeyLocator,
|
|
|
|
},
|
|
|
|
Preimage: swapPreimage,
|
|
|
|
AmountRequested: request.Amount,
|
|
|
|
CltvExpiry: swapResp.expiry,
|
|
|
|
MaxMinerFee: request.MaxMinerFee,
|
|
|
|
MaxSwapFee: request.MaxSwapFee,
|
|
|
|
Label: request.Label,
|
|
|
|
ProtocolVersion: loopdb.CurrentProtocolVersion(),
|
2019-03-12 15:10:37 +00:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2023-01-06 16:16:17 +00:00
|
|
|
// For MuSig2 swaps we store the proper internal keys that we generated
|
|
|
|
// and received from the server.
|
|
|
|
if loopdb.CurrentProtocolVersion() >= loopdb.ProtocolVersionMuSig2 {
|
|
|
|
contract.HtlcKeys.SenderInternalPubKey = senderInternalPubKey
|
|
|
|
contract.HtlcKeys.ReceiverInternalPubKey = swapResp.receiverInternalKey
|
|
|
|
}
|
|
|
|
|
2020-04-29 17:47:27 +00:00
|
|
|
swapKit := newSwapKit(
|
2020-07-23 15:30:53 +00:00
|
|
|
swapHash, swap.TypeIn,
|
|
|
|
cfg, &contract.SwapContract,
|
2019-03-12 15:10:37 +00:00
|
|
|
)
|
2020-04-29 17:47:27 +00:00
|
|
|
|
|
|
|
swapKit.lastUpdateTime = initiationTime
|
|
|
|
|
2019-03-12 15:10:37 +00:00
|
|
|
swap := &loopInSwap{
|
|
|
|
LoopInContract: contract,
|
|
|
|
swapKit: *swapKit,
|
2020-04-24 15:35:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if err := swap.initHtlcs(); err != nil {
|
|
|
|
return nil, err
|
2019-03-12 15:10:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Persist the data before exiting this function, so that the caller can
|
|
|
|
// trust that this swap will be resumed on restart.
|
2023-05-16 15:40:52 +00:00
|
|
|
err = cfg.store.CreateLoopIn(globalCtx, swapHash, &swap.LoopInContract)
|
2019-03-12 15:10:37 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("cannot store swap: %v", err)
|
|
|
|
}
|
|
|
|
|
2020-06-30 10:55:50 +00:00
|
|
|
if swapResp.serverMessage != "" {
|
|
|
|
swap.log.Infof("Server message: %v", swapResp.serverMessage)
|
|
|
|
}
|
|
|
|
|
2023-11-13 13:50:10 +00:00
|
|
|
swap.abandonChan = make(chan struct{}, 1)
|
|
|
|
|
2020-06-30 12:06:36 +00:00
|
|
|
return &loopInInitResult{
|
2020-06-30 12:10:33 +00:00
|
|
|
swap: swap,
|
|
|
|
serverMessage: swapResp.serverMessage,
|
2020-06-30 12:06:36 +00:00
|
|
|
}, nil
|
2019-03-12 15:10:37 +00:00
|
|
|
}
|
|
|
|
|
2020-05-29 09:27:47 +00:00
|
|
|
// awaitProbe waits for a probe payment to arrive and cancels it. This is a
|
|
|
|
// workaround for the current lack of multi-path probing.
|
|
|
|
func awaitProbe(ctx context.Context, lnd lndclient.LndServices,
|
|
|
|
probeHash lntypes.Hash) (chan error, error) {
|
|
|
|
|
|
|
|
// Subscribe to the probe invoice.
|
|
|
|
updateChan, errChan, err := lnd.Invoices.SubscribeSingleInvoice(
|
|
|
|
ctx, probeHash,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Wait in the background for the probe to arrive.
|
|
|
|
probeResult := make(chan error, 1)
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case update := <-updateChan:
|
|
|
|
switch update.State {
|
2023-01-09 15:36:52 +00:00
|
|
|
case invpkg.ContractAccepted:
|
2020-05-29 09:27:47 +00:00
|
|
|
log.Infof("Server probe successful")
|
|
|
|
probeResult <- nil
|
|
|
|
|
|
|
|
// Cancel probe invoice so that the
|
|
|
|
// server will know that its probe was
|
|
|
|
// successful.
|
|
|
|
err := lnd.Invoices.CancelInvoice(
|
|
|
|
ctx, probeHash,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("Cancel probe "+
|
|
|
|
"invoice: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return
|
|
|
|
|
2023-01-09 15:36:52 +00:00
|
|
|
case invpkg.ContractCanceled:
|
2020-05-29 09:27:47 +00:00
|
|
|
probeResult <- errors.New(
|
|
|
|
"probe invoice expired")
|
|
|
|
|
|
|
|
return
|
|
|
|
|
2023-01-09 15:36:52 +00:00
|
|
|
case invpkg.ContractSettled:
|
2020-05-29 09:27:47 +00:00
|
|
|
probeResult <- errors.New(
|
|
|
|
"impossible that probe " +
|
|
|
|
"invoice was settled")
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
case err := <-errChan:
|
|
|
|
probeResult <- err
|
|
|
|
return
|
|
|
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
probeResult <- ctx.Err()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return probeResult, nil
|
|
|
|
}
|
|
|
|
|
2019-03-12 15:10:37 +00:00
|
|
|
// resumeLoopInSwap returns a swap object representing a pending swap that has
|
|
|
|
// been restored from the database.
|
2021-03-03 09:21:24 +00:00
|
|
|
func resumeLoopInSwap(_ context.Context, cfg *swapConfig,
|
2019-03-12 15:10:37 +00:00
|
|
|
pend *loopdb.LoopIn) (*loopInSwap, error) {
|
|
|
|
|
|
|
|
hash := lntypes.Hash(sha256.Sum256(pend.Contract.Preimage[:]))
|
|
|
|
|
2019-10-28 16:06:07 +00:00
|
|
|
log.Infof("Resuming loop in swap %v", hash)
|
2019-03-12 15:10:37 +00:00
|
|
|
|
2020-04-29 17:47:27 +00:00
|
|
|
swapKit := newSwapKit(
|
2020-07-23 15:30:53 +00:00
|
|
|
hash, swap.TypeIn, cfg,
|
|
|
|
&pend.Contract.SwapContract,
|
2019-03-12 15:10:37 +00:00
|
|
|
)
|
2020-04-29 17:47:27 +00:00
|
|
|
|
2019-03-12 15:10:37 +00:00
|
|
|
swap := &loopInSwap{
|
|
|
|
LoopInContract: *pend.Contract,
|
|
|
|
swapKit: *swapKit,
|
2020-04-24 15:35:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if err := swap.initHtlcs(); err != nil {
|
|
|
|
return nil, err
|
2019-03-12 15:10:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
lastUpdate := pend.LastUpdate()
|
|
|
|
if lastUpdate == nil {
|
|
|
|
swap.lastUpdateTime = pend.Contract.InitiationTime
|
|
|
|
} else {
|
|
|
|
swap.state = lastUpdate.State
|
|
|
|
swap.lastUpdateTime = lastUpdate.Time
|
2020-06-25 10:35:22 +00:00
|
|
|
swap.htlcTxHash = lastUpdate.HtlcTxHash
|
2021-03-03 09:21:24 +00:00
|
|
|
swap.cost = lastUpdate.Cost
|
2019-03-12 15:10:37 +00:00
|
|
|
}
|
|
|
|
|
2023-11-21 16:20:36 +00:00
|
|
|
// Upon restoring the swap we also need to assign a new abandon channel
|
|
|
|
// that the client can use to signal that the swap should be abandoned.
|
|
|
|
swap.abandonChan = make(chan struct{}, 1)
|
|
|
|
|
2019-03-12 15:10:37 +00:00
|
|
|
return swap, nil
|
|
|
|
}
|
|
|
|
|
2023-06-26 10:51:25 +00:00
|
|
|
// validateLoopInContract validates the contract parameters against our request.
|
2022-12-15 15:43:38 +00:00
|
|
|
func validateLoopInContract(height int32, response *newLoopInResponse) error {
|
2023-06-26 10:51:25 +00:00
|
|
|
// Verify that we are not forced to publish a htlc that locks up our
|
2019-03-12 15:10:37 +00:00
|
|
|
// funds for too long in case the server doesn't follow through.
|
|
|
|
if response.expiry-height > MaxLoopInAcceptDelta {
|
|
|
|
return ErrExpiryTooFar
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-06-26 10:51:25 +00:00
|
|
|
// initHtlcs creates and updates the native and nested segwit htlcs of the
|
|
|
|
// loopInSwap.
|
2020-04-24 15:35:32 +00:00
|
|
|
func (s *loopInSwap) initHtlcs() error {
|
2023-11-14 00:52:39 +00:00
|
|
|
htlc, err := utils.GetHtlc(
|
2022-11-16 18:01:28 +00:00
|
|
|
s.hash, &s.SwapContract, s.swapKit.lnd.ChainParams,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-04-24 20:59:41 +00:00
|
|
|
|
2022-11-16 18:01:28 +00:00
|
|
|
switch htlc.OutputType {
|
|
|
|
case swap.HtlcP2WSH:
|
|
|
|
s.htlcP2WSH = htlc
|
2022-04-24 20:59:41 +00:00
|
|
|
|
2022-11-16 18:01:28 +00:00
|
|
|
case swap.HtlcP2TR:
|
|
|
|
s.htlcP2TR = htlc
|
2022-04-24 20:59:41 +00:00
|
|
|
|
2022-11-16 18:01:28 +00:00
|
|
|
default:
|
|
|
|
return fmt.Errorf("invalid output type")
|
2020-04-24 15:35:32 +00:00
|
|
|
}
|
|
|
|
|
2022-11-16 18:01:28 +00:00
|
|
|
s.swapKit.log.Infof("Htlc address (%s): %v", htlc.OutputType,
|
|
|
|
htlc.Address)
|
2020-04-24 15:35:32 +00:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-04-29 17:47:27 +00:00
|
|
|
// sendUpdate reports an update to the swap state.
|
|
|
|
func (s *loopInSwap) sendUpdate(ctx context.Context) error {
|
|
|
|
info := s.swapInfo()
|
|
|
|
s.log.Infof("Loop in swap state: %v", info.State)
|
|
|
|
|
2022-04-24 20:59:41 +00:00
|
|
|
if IsTaprootSwap(&s.SwapContract) {
|
|
|
|
info.HtlcAddressP2TR = s.htlcP2TR.Address
|
|
|
|
} else {
|
|
|
|
info.HtlcAddressP2WSH = s.htlcP2WSH.Address
|
|
|
|
}
|
|
|
|
|
2020-04-30 13:54:48 +00:00
|
|
|
info.ExternalHtlc = s.ExternalHtlc
|
2020-04-29 17:47:27 +00:00
|
|
|
|
2023-06-26 10:51:25 +00:00
|
|
|
// In order to avoid potentially dangerous ownership sharing we copy the
|
|
|
|
// last hop vertex.
|
2022-05-27 09:14:16 +00:00
|
|
|
if s.LastHop != nil {
|
|
|
|
lastHop := &route.Vertex{}
|
|
|
|
copy(lastHop[:], s.LastHop[:])
|
|
|
|
info.LastHop = lastHop
|
|
|
|
}
|
|
|
|
|
2020-04-29 17:47:27 +00:00
|
|
|
select {
|
|
|
|
case s.statusChan <- *info:
|
|
|
|
case <-ctx.Done():
|
|
|
|
return ctx.Err()
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-03-12 15:10:37 +00:00
|
|
|
// execute starts/resumes the swap. It is a thin wrapper around executeSwap to
|
|
|
|
// conveniently handle the error case.
|
|
|
|
func (s *loopInSwap) execute(mainCtx context.Context,
|
|
|
|
cfg *executeConfig, height int32) error {
|
|
|
|
|
2020-07-16 10:01:02 +00:00
|
|
|
defer s.wg.Wait()
|
|
|
|
|
2019-03-12 15:10:37 +00:00
|
|
|
s.executeConfig = *cfg
|
|
|
|
s.height = height
|
|
|
|
|
2020-07-16 10:01:02 +00:00
|
|
|
// Create context for our state subscription which we will cancel once
|
|
|
|
// swap execution has completed, ensuring that we kill the subscribe
|
|
|
|
// goroutine.
|
|
|
|
subCtx, cancel := context.WithCancel(mainCtx)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
s.wg.Add(1)
|
|
|
|
go func() {
|
|
|
|
defer s.wg.Done()
|
|
|
|
subscribeAndLogUpdates(
|
|
|
|
subCtx, s.hash, s.log, s.server.SubscribeLoopInUpdates,
|
|
|
|
)
|
|
|
|
}()
|
|
|
|
|
2019-03-12 15:10:37 +00:00
|
|
|
// Announce swap by sending out an initial update.
|
|
|
|
err := s.sendUpdate(mainCtx)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Execute the swap until it either reaches a final state or a temporary
|
|
|
|
// error occurs.
|
|
|
|
err = s.executeSwap(mainCtx)
|
|
|
|
|
2023-11-27 12:46:53 +00:00
|
|
|
// If there are insufficient confirmed funds to publish the swap, we
|
|
|
|
// finalize its state so a new swap will be published if funds become
|
|
|
|
// available.
|
|
|
|
if errors.Is(err, ErrInsufficientBalance) {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2023-11-13 13:50:10 +00:00
|
|
|
// Stop the execution if the swap has been abandoned.
|
|
|
|
if err != nil && s.state == loopdb.StateFailAbandoned {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-03-12 15:10:37 +00:00
|
|
|
// Sanity check. If there is no error, the swap must be in a final
|
|
|
|
// state.
|
|
|
|
if err == nil && s.state.Type() == loopdb.StateTypePending {
|
|
|
|
err = fmt.Errorf("swap in non-final state %v", s.state)
|
|
|
|
}
|
|
|
|
|
2023-06-26 10:51:25 +00:00
|
|
|
// If an unexpected error happened, report a temporary failure but don't
|
|
|
|
// persist the error. Otherwise, for example a connection error could
|
|
|
|
// lead to abandoning the swap permanently and losing funds.
|
2019-03-12 15:10:37 +00:00
|
|
|
if err != nil {
|
|
|
|
s.log.Errorf("Swap error: %v", err)
|
2019-04-02 08:51:51 +00:00
|
|
|
s.setState(loopdb.StateFailTemporary)
|
2019-03-12 15:10:37 +00:00
|
|
|
|
2023-06-26 10:51:25 +00:00
|
|
|
// If we cannot send out this update, there is nothing we can
|
|
|
|
// do.
|
2019-03-12 15:10:37 +00:00
|
|
|
_ = s.sendUpdate(mainCtx)
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
s.log.Infof("Loop in swap completed: %v "+
|
2019-05-15 12:01:27 +00:00
|
|
|
"(final cost: server %v, onchain %v, offchain %v)",
|
2019-03-12 15:10:37 +00:00
|
|
|
s.state,
|
|
|
|
s.cost.Server,
|
|
|
|
s.cost.Onchain,
|
2019-05-15 12:01:27 +00:00
|
|
|
s.cost.Offchain,
|
2019-03-12 15:10:37 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// executeSwap executes the swap.
|
|
|
|
func (s *loopInSwap) executeSwap(globalCtx context.Context) error {
|
|
|
|
var err error
|
|
|
|
|
2023-11-13 13:50:10 +00:00
|
|
|
// If the swap is already in a final state, we can return immediately.
|
|
|
|
if s.state.IsFinal() {
|
|
|
|
return ErrSwapFinalized
|
|
|
|
}
|
|
|
|
|
2019-03-12 15:10:37 +00:00
|
|
|
// For loop in, the client takes the first step by publishing the
|
2023-06-26 10:51:25 +00:00
|
|
|
// on-chain htlc. Only do this if we haven't already done so in a
|
2019-03-12 15:10:37 +00:00
|
|
|
// previous run.
|
|
|
|
if s.state == loopdb.StateInitiated {
|
2019-03-28 12:29:21 +00:00
|
|
|
if s.ExternalHtlc {
|
|
|
|
// If an external htlc was indicated, we can move to the
|
|
|
|
// HtlcPublished state directly and wait for
|
|
|
|
// confirmation.
|
2019-04-02 08:51:51 +00:00
|
|
|
s.setState(loopdb.StateHtlcPublished)
|
2020-06-25 11:14:39 +00:00
|
|
|
err = s.persistAndAnnounceState(globalCtx)
|
2019-03-28 12:29:21 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
published, err := s.publishOnChainHtlc(globalCtx)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if !published {
|
|
|
|
return nil
|
|
|
|
}
|
2019-03-12 15:10:37 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-06-26 10:51:25 +00:00
|
|
|
// Wait for the htlc to confirm. After a restart, this will pick up a
|
2019-03-12 15:10:37 +00:00
|
|
|
// previously published tx.
|
|
|
|
conf, err := s.waitForHtlcConf(globalCtx)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Determine the htlc outpoint by inspecting the htlc tx.
|
|
|
|
htlcOutpoint, htlcValue, err := swap.GetScriptOutput(
|
2019-04-04 10:20:45 +00:00
|
|
|
conf.Tx, s.htlc.PkScript,
|
2019-03-12 15:10:37 +00:00
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-06-25 11:55:27 +00:00
|
|
|
// Verify that the confirmed (external) htlc value matches the swap
|
2024-01-12 10:36:03 +00:00
|
|
|
// amount. If the amounts mismatch we update the swap state to indicate
|
|
|
|
// this, but end processing the swap. Instead, we continue to wait for
|
|
|
|
// the htlc to expire and publish a timeout tx to reclaim the funds. We
|
|
|
|
// skip this part if the swap was recovered from this state.
|
|
|
|
if s.state != loopdb.StateFailIncorrectHtlcAmt &&
|
|
|
|
htlcValue != s.LoopInContract.AmountRequested {
|
|
|
|
|
2020-06-25 11:55:27 +00:00
|
|
|
s.setState(loopdb.StateFailIncorrectHtlcAmt)
|
2024-01-12 10:36:03 +00:00
|
|
|
err = s.persistAndAnnounceState(globalCtx)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("Error persisting state: %v", err)
|
|
|
|
}
|
2020-06-25 11:55:27 +00:00
|
|
|
}
|
|
|
|
|
2023-06-26 10:51:25 +00:00
|
|
|
// The server is expected to see the htlc on-chain and know that it can
|
|
|
|
// sweep that htlc with the preimage, it should pay our swap invoice,
|
|
|
|
// receive the preimage and sweep the htlc. We are waiting for this to
|
|
|
|
// happen and simultaneously watch the htlc expiry height. When the htlc
|
|
|
|
// expires, we will publish a timeout tx to reclaim the funds.
|
2019-04-02 08:51:51 +00:00
|
|
|
err = s.waitForSwapComplete(globalCtx, htlcOutpoint, htlcValue)
|
2019-03-12 15:10:37 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Persist swap outcome.
|
2020-06-25 11:14:39 +00:00
|
|
|
if err := s.persistAndAnnounceState(globalCtx); err != nil {
|
2019-03-12 15:10:37 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// waitForHtlcConf watches the chain until the htlc confirms.
|
|
|
|
func (s *loopInSwap) waitForHtlcConf(globalCtx context.Context) (
|
|
|
|
*chainntnfs.TxConfirmation, error) {
|
|
|
|
|
2020-06-25 10:35:22 +00:00
|
|
|
// Register for confirmation of the htlc. It is essential to specify not
|
|
|
|
// just the pk script, because an attacker may publish the same htlc
|
2023-06-26 10:51:25 +00:00
|
|
|
// with a lower value, and we don't want to follow through with that tx.
|
|
|
|
// In the unlikely event that our call to SendOutputs crashes, and we
|
2020-06-25 10:35:22 +00:00
|
|
|
// restart, htlcTxHash will be nil at this point. Then only register
|
|
|
|
// with PkScript and accept the risk that the call triggers on a
|
|
|
|
// different htlc outpoint.
|
|
|
|
s.log.Infof("Register for htlc conf (hh=%v, txid=%v)",
|
|
|
|
s.InitiationHeight, s.htlcTxHash)
|
|
|
|
|
|
|
|
if s.htlcTxHash == nil {
|
|
|
|
s.log.Warnf("No htlc tx hash available, registering with " +
|
|
|
|
"just the pkscript")
|
|
|
|
}
|
|
|
|
|
2019-03-12 15:10:37 +00:00
|
|
|
ctx, cancel := context.WithCancel(globalCtx)
|
|
|
|
defer cancel()
|
2020-04-24 15:35:32 +00:00
|
|
|
|
|
|
|
notifier := s.lnd.ChainNotifier
|
|
|
|
|
2022-04-24 20:59:41 +00:00
|
|
|
notifyConfirmation := func(htlc *swap.Htlc) (
|
|
|
|
chan *chainntnfs.TxConfirmation, chan error, error) {
|
|
|
|
|
|
|
|
if htlc == nil {
|
|
|
|
return nil, nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return notifier.RegisterConfirmationsNtfn(
|
|
|
|
ctx, s.htlcTxHash, htlc.PkScript, 1, s.InitiationHeight,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
confChanP2WSH, confErrP2WSH, err := notifyConfirmation(s.htlcP2WSH)
|
2020-04-24 15:35:32 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2022-04-24 20:59:41 +00:00
|
|
|
confChanP2TR, confErrP2TR, err := notifyConfirmation(s.htlcP2TR)
|
2019-03-12 15:10:37 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-04-24 15:35:32 +00:00
|
|
|
|
2020-06-25 10:11:17 +00:00
|
|
|
var conf *chainntnfs.TxConfirmation
|
|
|
|
for conf == nil {
|
2019-03-12 15:10:37 +00:00
|
|
|
select {
|
2020-04-24 15:35:32 +00:00
|
|
|
// P2WSH htlc confirmed.
|
2020-06-25 10:11:17 +00:00
|
|
|
case conf = <-confChanP2WSH:
|
2020-04-24 15:35:32 +00:00
|
|
|
s.htlc = s.htlcP2WSH
|
|
|
|
s.log.Infof("P2WSH htlc confirmed")
|
|
|
|
|
2022-04-24 20:59:41 +00:00
|
|
|
// P2TR htlc confirmed.
|
|
|
|
case conf = <-confChanP2TR:
|
|
|
|
s.htlc = s.htlcP2TR
|
|
|
|
s.log.Infof("P2TR htlc confirmed")
|
|
|
|
|
2019-03-12 15:10:37 +00:00
|
|
|
// Conf ntfn error.
|
2020-04-24 15:35:32 +00:00
|
|
|
case err := <-confErrP2WSH:
|
|
|
|
return nil, err
|
|
|
|
|
2022-04-24 20:59:41 +00:00
|
|
|
// Conf ntfn error.
|
|
|
|
case err := <-confErrP2TR:
|
|
|
|
return nil, err
|
|
|
|
|
2019-03-12 15:10:37 +00:00
|
|
|
// Keep up with block height.
|
|
|
|
case notification := <-s.blockEpochChan:
|
|
|
|
s.height = notification.(int32)
|
|
|
|
|
2023-11-13 13:50:10 +00:00
|
|
|
// If the client requested the swap to be abandoned, we override
|
|
|
|
// the status in the database.
|
|
|
|
case <-s.abandonChan:
|
|
|
|
return nil, s.setStateAbandoned(ctx)
|
|
|
|
|
2019-03-12 15:10:37 +00:00
|
|
|
// Cancel.
|
|
|
|
case <-globalCtx.Done():
|
|
|
|
return nil, globalCtx.Err()
|
|
|
|
}
|
|
|
|
}
|
2020-06-25 10:11:17 +00:00
|
|
|
|
2020-06-25 10:35:22 +00:00
|
|
|
// Store htlc tx hash for accounting purposes. Usually this call is a
|
|
|
|
// no-op because the htlc tx hash was already known. Exceptions are:
|
|
|
|
//
|
|
|
|
// - Old pending swaps that were initiated before we persisted the htlc
|
|
|
|
// tx hash directly after publish.
|
|
|
|
//
|
|
|
|
// - Swaps that experienced a crash during their call to SendOutputs. In
|
|
|
|
// that case, we weren't able to record the tx hash.
|
|
|
|
txHash := conf.Tx.TxHash()
|
|
|
|
s.htlcTxHash = &txHash
|
|
|
|
|
2020-06-25 10:11:17 +00:00
|
|
|
return conf, nil
|
2019-03-12 15:10:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// publishOnChainHtlc checks whether there are still enough blocks left and if
|
|
|
|
// so, it publishes the htlc and advances the swap state.
|
|
|
|
func (s *loopInSwap) publishOnChainHtlc(ctx context.Context) (bool, error) {
|
|
|
|
var err error
|
|
|
|
|
|
|
|
blocksRemaining := s.CltvExpiry - s.height
|
|
|
|
s.log.Infof("Blocks left until on-chain expiry: %v", blocksRemaining)
|
|
|
|
|
|
|
|
// Verify whether it still makes sense to publish the htlc.
|
|
|
|
if blocksRemaining < MinLoopInPublishDelta {
|
2019-04-02 08:51:51 +00:00
|
|
|
s.setState(loopdb.StateFailTimeout)
|
2020-06-25 11:14:39 +00:00
|
|
|
return false, s.persistAndAnnounceState(ctx)
|
2019-03-12 15:10:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Get fee estimate from lnd.
|
2022-06-02 16:26:17 +00:00
|
|
|
feeRate, err := s.lnd.WalletKit.EstimateFeeRate(
|
2019-03-12 15:10:37 +00:00
|
|
|
ctx, s.LoopInContract.HtlcConfTarget,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return false, fmt.Errorf("estimate fee: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Transition to state HtlcPublished before calling SendOutputs to
|
|
|
|
// prevent us from ever paying multiple times after a crash.
|
2019-04-02 08:51:51 +00:00
|
|
|
s.setState(loopdb.StateHtlcPublished)
|
2020-06-25 11:14:39 +00:00
|
|
|
err = s.persistAndAnnounceState(ctx)
|
2019-03-12 15:10:37 +00:00
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
|
|
|
|
s.log.Infof("Publishing on chain HTLC with fee rate %v", feeRate)
|
2020-04-24 15:35:32 +00:00
|
|
|
|
2022-04-24 20:59:41 +00:00
|
|
|
var pkScript []byte
|
|
|
|
if IsTaprootSwap(&s.SwapContract) {
|
|
|
|
pkScript = s.htlcP2TR.PkScript
|
|
|
|
} else {
|
|
|
|
pkScript = s.htlcP2WSH.PkScript
|
|
|
|
}
|
|
|
|
|
2020-10-15 07:15:25 +00:00
|
|
|
tx, err := s.lnd.WalletKit.SendOutputs(
|
|
|
|
ctx, []*wire.TxOut{{
|
2022-04-24 20:59:41 +00:00
|
|
|
PkScript: pkScript,
|
2019-03-12 15:10:37 +00:00
|
|
|
Value: int64(s.LoopInContract.AmountRequested),
|
2020-10-15 07:15:25 +00:00
|
|
|
}}, feeRate, labels.LoopInHtlcLabel(swap.ShortHash(&s.hash)),
|
2019-03-12 15:10:37 +00:00
|
|
|
)
|
|
|
|
if err != nil {
|
2023-11-27 12:46:53 +00:00
|
|
|
s.log.Errorf("send outputs: %v", err)
|
|
|
|
s.setState(loopdb.StateFailInsufficientConfirmedBalance)
|
|
|
|
|
|
|
|
// If we cannot send out this update, there is nothing we can
|
|
|
|
// do.
|
|
|
|
_ = s.persistAndAnnounceState(ctx)
|
|
|
|
|
|
|
|
return false, ErrInsufficientBalance
|
2019-03-12 15:10:37 +00:00
|
|
|
}
|
2021-03-03 09:21:24 +00:00
|
|
|
|
2020-06-25 10:35:22 +00:00
|
|
|
txHash := tx.TxHash()
|
2021-03-03 09:21:24 +00:00
|
|
|
fee := getTxFee(tx, feeRate.FeePerKVByte())
|
|
|
|
|
|
|
|
s.log.Infof("Published on chain HTLC tx %v, fee: %v", txHash, fee)
|
2020-06-25 10:35:22 +00:00
|
|
|
|
|
|
|
// Persist the htlc hash so that after a restart we are still waiting
|
|
|
|
// for our own htlc. We don't need to announce to clients, because the
|
|
|
|
// state remains unchanged.
|
|
|
|
s.htlcTxHash = &txHash
|
2021-03-03 09:21:24 +00:00
|
|
|
|
|
|
|
// We do not expect any on-chain fees to be recorded yet, and we only
|
|
|
|
// publish our htlc once, so we set our total on-chain costs to equal
|
|
|
|
// the fee for publishing the htlc.
|
|
|
|
s.cost.Onchain = fee
|
|
|
|
|
2020-06-25 10:35:22 +00:00
|
|
|
s.lastUpdateTime = time.Now()
|
2023-05-16 15:40:52 +00:00
|
|
|
if err := s.persistState(ctx); err != nil {
|
2020-06-25 10:35:22 +00:00
|
|
|
return false, fmt.Errorf("persist htlc tx: %v", err)
|
|
|
|
}
|
2019-03-12 15:10:37 +00:00
|
|
|
|
|
|
|
return true, nil
|
|
|
|
}
|
|
|
|
|
2021-03-03 09:21:24 +00:00
|
|
|
// getTxFee calculates our fee for a transaction that we have broadcast. We use
|
|
|
|
// sat per kvbyte because this is what lnd uses, and we will run into rounding
|
|
|
|
// issues if we do not use the same fee rate as lnd.
|
|
|
|
func getTxFee(tx *wire.MsgTx, fee chainfee.SatPerKVByte) btcutil.Amount {
|
|
|
|
btcTx := btcutil.NewTx(tx)
|
|
|
|
vsize := mempool.GetTxVirtualSize(btcTx)
|
|
|
|
|
2024-05-30 19:38:19 +00:00
|
|
|
return fee.FeeForVSize(lntypes.VByte(vsize))
|
2021-03-03 09:21:24 +00:00
|
|
|
}
|
|
|
|
|
2019-04-02 08:51:51 +00:00
|
|
|
// waitForSwapComplete waits until a spending tx of the htlc gets confirmed and
|
|
|
|
// the swap invoice is either settled or canceled. If the htlc times out, the
|
|
|
|
// timeout tx will be published.
|
|
|
|
func (s *loopInSwap) waitForSwapComplete(ctx context.Context,
|
2020-01-15 08:17:01 +00:00
|
|
|
htlcOutpoint *wire.OutPoint, htlcValue btcutil.Amount) error {
|
2019-03-12 15:10:37 +00:00
|
|
|
|
|
|
|
// Register the htlc spend notification.
|
|
|
|
rpcCtx, cancel := context.WithCancel(ctx)
|
|
|
|
defer cancel()
|
|
|
|
spendChan, spendErr, err := s.lnd.ChainNotifier.RegisterSpendNtfn(
|
2020-06-25 10:35:22 +00:00
|
|
|
rpcCtx, htlcOutpoint, s.htlc.PkScript, s.InitiationHeight,
|
2019-03-12 15:10:37 +00:00
|
|
|
)
|
|
|
|
if err != nil {
|
2019-04-02 08:51:51 +00:00
|
|
|
return fmt.Errorf("register spend ntfn: %v", err)
|
2019-03-12 15:10:37 +00:00
|
|
|
}
|
|
|
|
|
2019-04-02 08:51:51 +00:00
|
|
|
// Register for swap invoice updates.
|
|
|
|
rpcCtx, cancel = context.WithCancel(ctx)
|
|
|
|
defer cancel()
|
|
|
|
s.log.Infof("Subscribing to swap invoice %v", s.hash)
|
|
|
|
swapInvoiceChan, swapInvoiceErr, err := s.lnd.Invoices.SubscribeSingleInvoice(
|
|
|
|
rpcCtx, s.hash,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("subscribe to swap invoice: %v", err)
|
|
|
|
}
|
|
|
|
|
2023-08-10 12:51:38 +00:00
|
|
|
// publishTxOnTimeout publishes the timeout tx if the contract has
|
|
|
|
// expired.
|
|
|
|
publishTxOnTimeout := func() (btcutil.Amount, error) {
|
2019-04-03 12:03:32 +00:00
|
|
|
if s.height >= s.LoopInContract.CltvExpiry {
|
2020-01-15 08:17:01 +00:00
|
|
|
return s.publishTimeoutTx(ctx, htlcOutpoint, htlcValue)
|
2019-04-03 12:03:32 +00:00
|
|
|
}
|
|
|
|
|
2021-03-03 09:21:24 +00:00
|
|
|
return 0, nil
|
2019-04-03 12:03:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Check timeout at current height. After a restart we may want to
|
|
|
|
// publish the tx immediately.
|
2021-03-03 09:21:24 +00:00
|
|
|
var sweepFee btcutil.Amount
|
2023-08-10 12:51:38 +00:00
|
|
|
sweepFee, err = publishTxOnTimeout()
|
2019-04-03 12:03:32 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-04-02 08:51:51 +00:00
|
|
|
htlcSpend := false
|
|
|
|
invoiceFinalized := false
|
2023-01-06 17:02:29 +00:00
|
|
|
htlcKeyRevealed := false
|
2019-04-02 08:51:51 +00:00
|
|
|
for !htlcSpend || !invoiceFinalized {
|
2019-03-12 15:10:37 +00:00
|
|
|
select {
|
2023-11-13 13:50:10 +00:00
|
|
|
// If the client requested the swap to be abandoned, we override
|
|
|
|
// the status in the database.
|
|
|
|
case <-s.abandonChan:
|
|
|
|
return s.setStateAbandoned(ctx)
|
|
|
|
|
2019-03-12 15:10:37 +00:00
|
|
|
// Spend notification error.
|
|
|
|
case err := <-spendErr:
|
2019-04-02 08:51:51 +00:00
|
|
|
return err
|
2019-03-12 15:10:37 +00:00
|
|
|
|
2019-04-02 08:51:51 +00:00
|
|
|
// Receive block epochs and start publishing the timeout tx
|
|
|
|
// whenever possible.
|
2019-03-12 15:10:37 +00:00
|
|
|
case notification := <-s.blockEpochChan:
|
|
|
|
s.height = notification.(int32)
|
|
|
|
|
2023-08-10 12:51:38 +00:00
|
|
|
sweepFee, err = publishTxOnTimeout()
|
2019-04-03 12:03:32 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
2019-03-12 15:10:37 +00:00
|
|
|
}
|
|
|
|
|
2023-01-06 17:02:29 +00:00
|
|
|
if invoiceFinalized && !htlcKeyRevealed {
|
|
|
|
htlcKeyRevealed = s.tryPushHtlcKey(ctx)
|
|
|
|
}
|
|
|
|
|
2019-04-02 08:51:51 +00:00
|
|
|
// The htlc spend is confirmed. Inspect the spending tx to
|
|
|
|
// determine the final swap state.
|
2019-03-12 15:10:37 +00:00
|
|
|
case spendDetails := <-spendChan:
|
|
|
|
s.log.Infof("Htlc spend by tx: %v",
|
|
|
|
spendDetails.SpenderTxHash)
|
|
|
|
|
2024-02-06 16:04:41 +00:00
|
|
|
err := s.processHtlcSpend(ctx, spendDetails, sweepFee)
|
2019-04-02 08:51:51 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-03-12 15:10:37 +00:00
|
|
|
|
2019-04-02 08:51:51 +00:00
|
|
|
htlcSpend = true
|
2019-03-12 15:10:37 +00:00
|
|
|
|
|
|
|
// Swap invoice ntfn error.
|
2021-06-07 08:56:36 +00:00
|
|
|
case err, ok := <-swapInvoiceErr:
|
|
|
|
// If the channel has been closed, the server has
|
|
|
|
// finished sending updates, so we set the channel to
|
|
|
|
// nil because we don't want to constantly select this
|
|
|
|
// case.
|
|
|
|
if !ok {
|
|
|
|
swapInvoiceErr = nil
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2019-03-12 15:10:37 +00:00
|
|
|
return err
|
|
|
|
|
2019-10-07 15:29:24 +00:00
|
|
|
// An update to the swap invoice occurred. Check the new state
|
2019-04-02 08:51:51 +00:00
|
|
|
// and update the swap state accordingly.
|
2021-06-07 08:56:36 +00:00
|
|
|
case update, ok := <-swapInvoiceChan:
|
|
|
|
// If the channel has been closed, the server has
|
|
|
|
// finished sending updates, so we set the channel to
|
|
|
|
// nil because we don't want to constantly select this
|
|
|
|
// case.
|
|
|
|
if !ok {
|
|
|
|
swapInvoiceChan = nil
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2019-03-12 15:10:37 +00:00
|
|
|
s.log.Infof("Received swap invoice update: %v",
|
|
|
|
update.State)
|
|
|
|
|
|
|
|
switch update.State {
|
|
|
|
// Swap invoice was paid, so update server cost balance.
|
2023-01-09 15:36:52 +00:00
|
|
|
case invpkg.ContractSettled:
|
2019-04-02 08:51:51 +00:00
|
|
|
// If invoice settlement and htlc spend happen
|
|
|
|
// in the expected order, move the swap to an
|
|
|
|
// intermediate state that indicates that the
|
|
|
|
// swap is complete from the user point of view,
|
|
|
|
// but still incomplete with regards to
|
|
|
|
// accounting data.
|
|
|
|
if s.state == loopdb.StateHtlcPublished {
|
|
|
|
s.setState(loopdb.StateInvoiceSettled)
|
2020-06-25 11:14:39 +00:00
|
|
|
err := s.persistAndAnnounceState(ctx)
|
2019-04-02 08:51:51 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
invoiceFinalized = true
|
2023-01-06 17:02:29 +00:00
|
|
|
htlcKeyRevealed = s.tryPushHtlcKey(ctx)
|
2024-02-06 16:04:41 +00:00
|
|
|
s.cost.Server = s.AmountRequested -
|
|
|
|
update.AmtPaid
|
2019-03-12 15:10:37 +00:00
|
|
|
|
|
|
|
// Canceled invoice has no effect on server cost
|
|
|
|
// balance.
|
2023-01-09 15:36:52 +00:00
|
|
|
case invpkg.ContractCanceled:
|
2019-04-02 08:51:51 +00:00
|
|
|
invoiceFinalized = true
|
2019-03-12 15:10:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
return ctx.Err()
|
|
|
|
}
|
|
|
|
}
|
2019-04-02 08:51:51 +00:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-01-06 17:02:29 +00:00
|
|
|
// tryPushHtlcKey attempts to push the htlc key to the server. If the server
|
2023-06-26 10:51:25 +00:00
|
|
|
// returns an error of any kind we'll log it as a warning but won't act as the
|
|
|
|
// swap execution can just go on without the server gaining knowledge of our
|
|
|
|
// internal key.
|
2023-01-06 17:02:29 +00:00
|
|
|
func (s *loopInSwap) tryPushHtlcKey(ctx context.Context) bool {
|
|
|
|
if s.ProtocolVersion < loopdb.ProtocolVersionMuSig2 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Infof("Attempting to reveal internal HTLC key to the server")
|
|
|
|
|
|
|
|
internalPrivKey, err := sharedSecretFromHash(
|
|
|
|
ctx, s.swapConfig.lnd.Signer, s.hash,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
s.log.Warnf("Unable to derive HTLC internal private key: %v",
|
|
|
|
err)
|
|
|
|
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
err = s.server.PushKey(ctx, s.ProtocolVersion, s.hash, internalPrivKey)
|
|
|
|
if err != nil {
|
|
|
|
s.log.Warnf("Internal HTLC key reveal failed: %v", err)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2019-04-02 08:51:51 +00:00
|
|
|
func (s *loopInSwap) processHtlcSpend(ctx context.Context,
|
2024-02-06 16:04:41 +00:00
|
|
|
spend *chainntnfs.SpendDetail, sweepFee btcutil.Amount) error {
|
2019-04-02 08:51:51 +00:00
|
|
|
|
|
|
|
// Determine the htlc input of the spending tx and inspect the witness
|
2023-08-10 12:51:38 +00:00
|
|
|
// to find out whether a success or a timeout tx spent the htlc.
|
2019-04-02 08:51:51 +00:00
|
|
|
htlcInput := spend.SpendingTx.TxIn[spend.SpenderInputIndex]
|
|
|
|
|
|
|
|
if s.htlc.IsSuccessWitness(htlcInput.Witness) {
|
|
|
|
s.setState(loopdb.StateSuccess)
|
|
|
|
} else {
|
2021-03-03 09:21:24 +00:00
|
|
|
// We needed another on chain tx to sweep the timeout clause,
|
|
|
|
// which we now include in our costs.
|
|
|
|
s.cost.Onchain += sweepFee
|
2024-01-12 10:36:03 +00:00
|
|
|
|
|
|
|
// If the swap is in state StateFailIncorrectHtlcAmt we know
|
|
|
|
// that the deposited htlc amount wasn't equal to the contract
|
|
|
|
// amount. We can finalize the swap by setting an appropriate
|
|
|
|
// state.
|
|
|
|
if s.state == loopdb.StateFailIncorrectHtlcAmt {
|
|
|
|
s.setState(loopdb.StateFailIncorrectHtlcAmtSwept)
|
|
|
|
} else {
|
|
|
|
s.setState(loopdb.StateFailTimeout)
|
|
|
|
}
|
2019-04-02 08:51:51 +00:00
|
|
|
|
|
|
|
// Now that the timeout tx confirmed, we can safely cancel the
|
|
|
|
// swap invoice. We still need to query the final invoice state.
|
|
|
|
// This is not a hodl invoice, so it may be that the invoice was
|
|
|
|
// already settled. This means that the server didn't succeed in
|
|
|
|
// sweeping the htlc after paying the invoice.
|
|
|
|
err := s.lnd.Invoices.CancelInvoice(ctx, s.hash)
|
2023-01-09 15:36:52 +00:00
|
|
|
if err != nil && err != invpkg.ErrInvoiceAlreadySettled {
|
2019-04-02 08:51:51 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
2019-03-12 15:10:37 +00:00
|
|
|
}
|
|
|
|
|
2021-03-03 09:21:24 +00:00
|
|
|
// publishTimeoutTx publishes a timeout tx after the on-chain htlc has expired,
|
|
|
|
// returning the fee that is paid by the sweep tx. We cannot update our swap
|
|
|
|
// costs in this function because it is called multiple times. The swap failed
|
|
|
|
// and we are reclaiming our funds.
|
2019-03-12 15:10:37 +00:00
|
|
|
func (s *loopInSwap) publishTimeoutTx(ctx context.Context,
|
2021-03-03 09:21:24 +00:00
|
|
|
htlcOutpoint *wire.OutPoint, htlcValue btcutil.Amount) (btcutil.Amount,
|
|
|
|
error) {
|
2019-03-12 15:10:37 +00:00
|
|
|
|
|
|
|
if s.timeoutAddr == nil {
|
|
|
|
var err error
|
2022-07-07 15:28:22 +00:00
|
|
|
s.timeoutAddr, err = s.lnd.WalletKit.NextAddr(
|
|
|
|
ctx, "", walletrpc.AddressType_WITNESS_PUBKEY_HASH,
|
|
|
|
false,
|
|
|
|
)
|
2019-03-12 15:10:37 +00:00
|
|
|
if err != nil {
|
2021-03-03 09:21:24 +00:00
|
|
|
return 0, err
|
2019-03-12 15:10:37 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-06-26 10:51:25 +00:00
|
|
|
// Calculate sweep tx fee.
|
2019-03-12 15:10:37 +00:00
|
|
|
fee, err := s.sweeper.GetSweepFee(
|
2019-07-30 11:37:47 +00:00
|
|
|
ctx, s.htlc.AddTimeoutToEstimator, s.timeoutAddr,
|
|
|
|
TimeoutTxConfTarget,
|
2019-03-12 15:10:37 +00:00
|
|
|
)
|
|
|
|
if err != nil {
|
2021-03-03 09:21:24 +00:00
|
|
|
return 0, err
|
2019-03-12 15:10:37 +00:00
|
|
|
}
|
|
|
|
|
2022-03-29 11:17:19 +00:00
|
|
|
// Create a function that will assemble our timeout witness.
|
2019-03-12 15:10:37 +00:00
|
|
|
witnessFunc := func(sig []byte) (wire.TxWitness, error) {
|
2022-04-14 16:40:30 +00:00
|
|
|
return s.htlc.GenTimeoutWitness(sig)
|
2019-03-12 15:10:37 +00:00
|
|
|
}
|
|
|
|
|
2022-03-29 11:17:19 +00:00
|
|
|
// Retrieve the full script required to unlock the output.
|
|
|
|
redeemScript := s.htlc.TimeoutScript()
|
|
|
|
|
2020-08-24 18:46:02 +00:00
|
|
|
sequence := uint32(0)
|
2019-03-12 15:10:37 +00:00
|
|
|
timeoutTx, err := s.sweeper.CreateSweepTx(
|
2023-01-05 17:16:05 +00:00
|
|
|
ctx, s.height, sequence, s.htlc, *htlcOutpoint,
|
|
|
|
s.HtlcKeys.SenderScriptKey, redeemScript, witnessFunc,
|
|
|
|
htlcValue, fee, s.timeoutAddr,
|
2019-03-12 15:10:37 +00:00
|
|
|
)
|
|
|
|
if err != nil {
|
2021-03-03 09:21:24 +00:00
|
|
|
return 0, err
|
2019-03-12 15:10:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
timeoutTxHash := timeoutTx.TxHash()
|
|
|
|
s.log.Infof("Publishing timeout tx %v with fee %v to addr %v",
|
|
|
|
timeoutTxHash, fee, s.timeoutAddr)
|
|
|
|
|
2020-10-15 07:15:25 +00:00
|
|
|
err = s.lnd.WalletKit.PublishTransaction(
|
|
|
|
ctx, timeoutTx,
|
|
|
|
labels.LoopInSweepTimeout(swap.ShortHash(&s.hash)),
|
|
|
|
)
|
2019-03-12 15:10:37 +00:00
|
|
|
if err != nil {
|
|
|
|
s.log.Warnf("publish timeout: %v", err)
|
|
|
|
}
|
|
|
|
|
2021-03-03 09:21:24 +00:00
|
|
|
return fee, nil
|
2019-03-12 15:10:37 +00:00
|
|
|
}
|
|
|
|
|
2023-11-13 13:50:10 +00:00
|
|
|
// setStateAbandoned stores the abandoned state and announces it. It also
|
|
|
|
// cancels the swap invoice so the server can't settle it.
|
|
|
|
func (s *loopInSwap) setStateAbandoned(ctx context.Context) error {
|
|
|
|
s.log.Infof("Abandoning swap %v...", s.hash)
|
|
|
|
|
|
|
|
if !s.state.IsPending() {
|
|
|
|
return fmt.Errorf("cannot abandon swap in state %v", s.state)
|
|
|
|
}
|
|
|
|
|
|
|
|
s.setState(loopdb.StateFailAbandoned)
|
|
|
|
|
|
|
|
err := s.persistAndAnnounceState(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the invoice is already settled or canceled, this is a nop.
|
|
|
|
_ = s.lnd.Invoices.CancelInvoice(ctx, s.hash)
|
|
|
|
|
|
|
|
return fmt.Errorf("swap hash "+
|
|
|
|
"abandoned by client, "+
|
|
|
|
"swap ID: %v, %v",
|
|
|
|
s.hash, err)
|
|
|
|
}
|
|
|
|
|
2020-06-25 11:14:39 +00:00
|
|
|
// persistAndAnnounceState updates the swap state on disk and sends out an
|
|
|
|
// update notification.
|
|
|
|
func (s *loopInSwap) persistAndAnnounceState(ctx context.Context) error {
|
2019-03-12 15:10:37 +00:00
|
|
|
// Update state in store.
|
2023-05-16 15:40:52 +00:00
|
|
|
if err := s.persistState(ctx); err != nil {
|
2020-06-25 11:15:58 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Send out swap update
|
|
|
|
return s.sendUpdate(ctx)
|
|
|
|
}
|
|
|
|
|
|
|
|
// persistState updates the swap state on disk.
|
2023-05-16 15:40:52 +00:00
|
|
|
func (s *loopInSwap) persistState(ctx context.Context) error {
|
2020-06-25 11:15:58 +00:00
|
|
|
return s.store.UpdateLoopIn(
|
2023-05-16 15:40:52 +00:00
|
|
|
ctx, s.hash, s.lastUpdateTime,
|
2019-05-15 11:55:41 +00:00
|
|
|
loopdb.SwapStateData{
|
2020-06-25 10:35:22 +00:00
|
|
|
State: s.state,
|
|
|
|
Cost: s.cost,
|
|
|
|
HtlcTxHash: s.htlcTxHash,
|
2019-05-15 11:55:41 +00:00
|
|
|
},
|
|
|
|
)
|
2019-03-12 15:10:37 +00:00
|
|
|
}
|
2019-04-02 08:51:51 +00:00
|
|
|
|
|
|
|
// setState updates the swap state and last update timestamp.
|
|
|
|
func (s *loopInSwap) setState(state loopdb.SwapState) {
|
|
|
|
s.lastUpdateTime = time.Now()
|
|
|
|
s.state = state
|
|
|
|
}
|
2023-01-06 16:16:17 +00:00
|
|
|
|
|
|
|
// sharedSecretFromHash derives the shared secret from the swap hash using the
|
|
|
|
// swap.KeyFamily family and zero as index.
|
|
|
|
func sharedSecretFromHash(ctx context.Context, signer lndclient.SignerClient,
|
|
|
|
hash lntypes.Hash) ([32]byte, error) {
|
|
|
|
|
|
|
|
_, hashPubKey := btcec.PrivKeyFromBytes(hash[:])
|
|
|
|
|
|
|
|
return signer.DeriveSharedKey(
|
|
|
|
ctx, hashPubKey, &keychain.KeyLocator{
|
|
|
|
Family: keychain.KeyFamily(swap.KeyFamily),
|
|
|
|
Index: 0,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
}
|