loop/swap.go
Slyghtning b702aebbf4
multi: inject clocks into swap lifecycle and update tests
Inject clock.Clock into swapConfig so that swap initiation times
are deterministic and testable. Update all swap tests to use
TestClock with a fixed time, and assert that InitiationTime
matches the clock value.
2026-03-13 08:58:56 +01:00

101 lines
2 KiB
Go

package loop
import (
"context"
"time"
"github.com/lightninglabs/lndclient"
"github.com/lightninglabs/loop/assets"
"github.com/lightninglabs/loop/loopdb"
"github.com/lightninglabs/loop/swap"
"github.com/lightninglabs/loop/utils"
"github.com/lightningnetwork/lnd/clock"
"github.com/lightningnetwork/lnd/lntypes"
)
type swapKit struct {
swapConfig
hash lntypes.Hash
height int32 //nolint:structcheck
log *swap.PrefixLog
lastUpdateTime time.Time
cost loopdb.SwapCost
state loopdb.SwapState
contract *loopdb.SwapContract
swapType swap.Type
}
func newSwapKit(hash lntypes.Hash, swapType swap.Type, cfg *swapConfig,
contract *loopdb.SwapContract) *swapKit {
log := &swap.PrefixLog{
Hash: hash,
Logger: log,
}
return &swapKit{
swapConfig: *cfg,
hash: hash,
log: log,
state: loopdb.StateInitiated,
contract: contract,
swapType: swapType,
}
}
// IsTaprootSwap returns true if the swap referenced by the passed swap contract
// uses the v3 (taproot) htlc.
func IsTaprootSwap(swapContract *loopdb.SwapContract) bool {
version := utils.GetHtlcScriptVersion(swapContract.ProtocolVersion)
return version == swap.HtlcV3
}
// swapInfo constructs and returns a filled SwapInfo from
// the swapKit.
func (s *swapKit) swapInfo() *SwapInfo {
return &SwapInfo{
SwapContract: *s.contract,
SwapHash: s.hash,
SwapType: s.swapType,
LastUpdate: s.lastUpdateTime,
SwapStateData: loopdb.SwapStateData{
State: s.state,
Cost: s.cost,
},
}
}
type genericSwap interface {
execute(mainCtx context.Context, cfg *executeConfig,
height int32) error
}
type swapConfig struct {
lnd *lndclient.LndServices
store loopdb.SwapStore
server swapServerClient
assets *assets.TapdClient
clock clock.Clock
}
func newSwapConfig(lnd *lndclient.LndServices, store loopdb.SwapStore,
server swapServerClient, assets *assets.TapdClient,
clock clock.Clock) *swapConfig {
return &swapConfig{
lnd: lnd,
store: store,
server: server,
assets: assets,
clock: clock,
}
}