2
0
mirror of https://github.com/lightninglabs/loop synced 2024-11-08 01:10:29 +00:00
loop/testcontext_test.go

295 lines
7.0 KiB
Go
Raw Normal View History

package loop
2019-03-06 20:13:50 +00:00
import (
"context"
"fmt"
2019-03-06 20:13:50 +00:00
"testing"
"time"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcutil"
2019-03-06 20:13:50 +00:00
"github.com/btcsuite/btcd/wire"
"github.com/lightninglabs/lndclient"
"github.com/lightninglabs/loop/loopdb"
"github.com/lightninglabs/loop/swap"
"github.com/lightninglabs/loop/sweep"
"github.com/lightninglabs/loop/sweepbatcher"
"github.com/lightninglabs/loop/test"
2019-03-06 20:13:50 +00:00
"github.com/lightningnetwork/lnd/chainntnfs"
"github.com/lightningnetwork/lnd/lnrpc"
2019-03-06 20:13:50 +00:00
"github.com/lightningnetwork/lnd/lntypes"
"github.com/stretchr/testify/require"
2019-03-06 20:13:50 +00:00
)
var (
testPreimage = lntypes.Preimage([32]byte{
1, 1, 1, 1, 2, 2, 2, 2,
3, 3, 3, 3, 4, 4, 4, 4,
1, 1, 1, 1, 2, 2, 2, 2,
3, 3, 3, 3, 4, 4, 4, 4,
})
)
// testContext contains functionality to support client unit tests.
type testContext struct {
test.Context
serverMock *serverMock
swapClient *Client
statusChan chan SwapInfo
2024-01-18 11:26:07 +00:00
store *loopdb.StoreMock
2019-03-06 20:13:50 +00:00
expiryChan chan time.Time
runErr chan error
stop func()
}
// mockVerifySchnorrSigFail is used to simulate failed taproot keyspend
// signature verification. If passed to the executeConfig we'll test an
// uncooperative server and will fall back to scriptspend sweep.
func mockVerifySchnorrSigFail(pubKey *btcec.PublicKey, hash,
sig []byte) error {
return fmt.Errorf("invalid sig")
}
// mockVerifySchnorrSigSuccess is used to simulate successful taproot keyspend
// signature verification. If passed to the executeConfig we'll test an
// uncooperative server and will fall back to scriptspend sweep.
func mockVerifySchnorrSigSuccess(pubKey *btcec.PublicKey, hash,
sig []byte) error {
return fmt.Errorf("invalid sig")
}
func mockMuSig2SignSweep(ctx context.Context,
protocolVersion loopdb.ProtocolVersion, swapHash lntypes.Hash,
paymentAddr [32]byte, nonce []byte, sweepTxPsbt []byte,
prevoutMap map[wire.OutPoint]*wire.TxOut) (
[]byte, []byte, error) {
return nil, nil, nil
}
func newSwapClient(t *testing.T, config *clientConfig) *Client {
2019-03-06 20:13:50 +00:00
sweeper := &sweep.Sweeper{
Lnd: config.LndServices,
}
lndServices := config.LndServices
batcherStore := sweepbatcher.NewStoreMock()
sweepStore, err := sweepbatcher.NewSweepFetcherFromSwapStore(
config.Store, config.LndServices.ChainParams,
)
require.NoError(t, err)
batcher := sweepbatcher.NewBatcher(
config.LndServices.WalletKit, config.LndServices.ChainNotifier,
config.LndServices.Signer, mockMuSig2SignSweep,
mockVerifySchnorrSigSuccess, config.LndServices.ChainParams,
batcherStore, sweepStore,
)
2019-03-06 20:13:50 +00:00
executor := newExecutor(&executorConfig{
lnd: lndServices,
store: config.Store,
sweeper: sweeper,
batcher: batcher,
2019-03-06 20:13:50 +00:00
createExpiryTimer: config.CreateExpiryTimer,
cancelSwap: config.Server.CancelLoopOutSwap,
verifySchnorrSig: mockVerifySchnorrSigFail,
2019-03-06 20:13:50 +00:00
})
return &Client{
errChan: make(chan error),
clientConfig: *config,
lndServices: lndServices,
sweeper: sweeper,
executor: executor,
resumeReady: make(chan struct{}),
}
}
func createClientTestContext(t *testing.T,
pendingSwaps []*loopdb.LoopOut) *testContext {
2019-03-06 20:13:50 +00:00
clientLnd := test.NewMockLnd()
2020-05-29 09:27:47 +00:00
serverMock := newServerMock(clientLnd)
2019-03-06 20:13:50 +00:00
2024-01-18 11:26:07 +00:00
store := loopdb.NewStoreMock(t)
2019-03-06 20:13:50 +00:00
for _, s := range pendingSwaps {
2024-01-18 11:26:07 +00:00
store.LoopOutSwaps[s.Hash] = s.Contract
2019-03-06 20:13:50 +00:00
updates := []loopdb.SwapStateData{}
2019-03-06 20:13:50 +00:00
for _, e := range s.Events {
updates = append(updates, e.SwapStateData)
2019-03-06 20:13:50 +00:00
}
2024-01-18 11:26:07 +00:00
store.LoopOutUpdates[s.Hash] = updates
2019-03-06 20:13:50 +00:00
}
expiryChan := make(chan time.Time)
timerFactory := func(expiry time.Duration) <-chan time.Time {
return expiryChan
}
swapClient := newSwapClient(t, &clientConfig{
2019-03-06 20:13:50 +00:00
LndServices: &clientLnd.LndServices,
Server: serverMock,
Store: store,
CreateExpiryTimer: timerFactory,
})
statusChan := make(chan SwapInfo)
ctx := &testContext{
Context: test.NewContext(
t,
clientLnd,
),
swapClient: swapClient,
statusChan: statusChan,
expiryChan: expiryChan,
store: store,
serverMock: serverMock,
}
ctx.runErr = make(chan error)
runCtx, stop := context.WithCancel(context.Background())
ctx.stop = stop
go func() {
2023-11-14 18:05:59 +00:00
err := swapClient.Run(runCtx, statusChan)
2019-10-28 16:06:07 +00:00
log.Errorf("client run: %v", err)
2019-03-12 15:10:37 +00:00
ctx.runErr <- err
2019-03-06 20:13:50 +00:00
}()
return ctx
}
func (ctx *testContext) finish() {
ctx.stop()
select {
case err := <-ctx.runErr:
2023-03-29 13:56:40 +00:00
require.NoError(ctx.Context.T, err)
2019-03-06 20:13:50 +00:00
case <-time.After(test.Timeout):
2023-03-29 13:56:40 +00:00
ctx.Context.T.Fatal("client not stopping")
2019-03-06 20:13:50 +00:00
}
ctx.assertIsDone()
}
func (ctx *testContext) assertIsDone() {
2023-03-29 13:56:40 +00:00
require.NoError(ctx.Context.T, ctx.Context.Lnd.IsDone())
2024-01-18 11:26:07 +00:00
require.NoError(ctx.Context.T, ctx.store.IsDone())
2019-03-06 20:13:50 +00:00
select {
case <-ctx.statusChan:
2023-03-29 13:56:40 +00:00
ctx.Context.T.Fatalf("not all status updates read")
2019-03-06 20:13:50 +00:00
default:
}
}
func (ctx *testContext) assertStored() {
2023-03-29 13:56:40 +00:00
ctx.Context.T.Helper()
2019-03-06 20:13:50 +00:00
2024-01-18 11:26:07 +00:00
ctx.store.AssertLoopOutStored()
2019-03-06 20:13:50 +00:00
}
func (ctx *testContext) assertStorePreimageReveal() {
2023-03-29 13:56:40 +00:00
ctx.Context.T.Helper()
2019-03-06 20:13:50 +00:00
2024-01-18 11:26:07 +00:00
ctx.store.AssertStorePreimageReveal()
2019-03-06 20:13:50 +00:00
}
func (ctx *testContext) assertStoreFinished(expectedResult loopdb.SwapState) {
2023-03-29 13:56:40 +00:00
ctx.Context.T.Helper()
2019-03-06 20:13:50 +00:00
2024-01-18 11:26:07 +00:00
ctx.store.AssertStoreFinished(expectedResult)
2019-03-06 20:13:50 +00:00
}
func (ctx *testContext) assertStatus(expectedState loopdb.SwapState) {
2023-03-29 13:56:40 +00:00
ctx.Context.T.Helper()
2019-03-06 20:13:50 +00:00
for {
select {
case update := <-ctx.statusChan:
if update.SwapType != swap.TypeOut {
2019-03-06 20:13:50 +00:00
continue
}
if update.State == expectedState {
return
}
case <-time.After(test.Timeout):
2023-03-29 13:56:40 +00:00
ctx.Context.T.Fatalf("expected status %v not "+
2019-03-06 20:13:50 +00:00
"received in time", expectedState)
}
}
}
func (ctx *testContext) publishHtlc(script []byte,
amt btcutil.Amount) wire.OutPoint {
2019-03-06 20:13:50 +00:00
// Create the htlc tx.
htlcTx := wire.MsgTx{}
htlcTx.AddTxIn(&wire.TxIn{
PreviousOutPoint: wire.OutPoint{},
})
htlcTx.AddTxOut(&wire.TxOut{
PkScript: script,
Value: int64(amt),
})
htlcTxHash := htlcTx.TxHash()
// Signal client that script has been published.
select {
case ctx.Lnd.ConfChannel <- &chainntnfs.TxConfirmation{
Tx: &htlcTx,
}:
case <-time.After(test.Timeout):
2023-03-29 13:56:40 +00:00
ctx.Context.T.Fatalf("htlc confirmed not consumed")
2019-03-06 20:13:50 +00:00
}
return wire.OutPoint{
Hash: htlcTxHash,
Index: 0,
}
}
// trackPayment asserts that a call to track payment was sent and sends the
// status provided into the updates channel.
func (ctx *testContext) trackPayment(status lnrpc.Payment_PaymentStatus) {
trackPayment := ctx.Context.AssertTrackPayment()
select {
case trackPayment.Updates <- lndclient.PaymentStatus{
State: status,
}:
case <-time.After(test.Timeout):
2023-03-29 13:56:40 +00:00
ctx.Context.T.Fatalf("could not send payment update")
}
}
// assertPreimagePush asserts that we made an attempt to push our preimage to
// the server.
func (ctx *testContext) assertPreimagePush(preimage lntypes.Preimage) {
select {
case pushedPreimage := <-ctx.serverMock.preimagePush:
2023-03-29 13:56:40 +00:00
require.Equal(ctx.Context.T, preimage, pushedPreimage)
case <-time.After(test.Timeout):
2023-03-29 13:56:40 +00:00
ctx.Context.T.Fatalf("preimage not pushed")
}
}
func (ctx *testContext) AssertEpochListeners(numListeners int32) {
ctx.Context.T.Helper()
require.Eventually(ctx.Context.T, func() bool {
return ctx.Lnd.EpochSubscribers() == numListeners
}, test.Timeout, time.Millisecond*250)
}