forked from lightninglabs/loop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
loopout_test.go
1191 lines (970 loc) · 34.2 KB
/
loopout_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package loop
import (
"context"
"errors"
"math"
"reflect"
"testing"
"time"
"github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/wire"
"github.com/lightninglabs/lndclient"
"github.com/lightninglabs/loop/loopdb"
"github.com/lightninglabs/loop/sweep"
"github.com/lightninglabs/loop/test"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/lightningnetwork/lnd/lnwallet/chainfee"
"github.com/lightningnetwork/lnd/zpay32"
"github.com/stretchr/testify/require"
)
// TestLoopOutPaymentParameters tests the first part of the loop out process up
// to the point where the off-chain payments are made.
func TestLoopOutPaymentParameters(t *testing.T) {
t.Run("stable protocol", func(t *testing.T) {
testLoopOutPaymentParameters(t)
})
t.Run("experimental protocol", func(t *testing.T) {
loopdb.EnableExperimentalProtocol()
defer loopdb.ResetCurrentProtocolVersion()
testLoopOutPaymentParameters(t)
})
}
// TestLoopOutPaymentParameters tests the first part of the loop out process up
// to the point where the off-chain payments are made.
func testLoopOutPaymentParameters(t *testing.T) {
defer test.Guard(t)()
// Set up test context objects.
lnd := test.NewMockLnd()
ctx := test.NewContext(t, lnd)
server := newServerMock(lnd)
store := newStoreMock(t)
expiryChan := make(chan time.Time)
timerFactory := func(_ time.Duration) <-chan time.Time {
return expiryChan
}
height := int32(600)
cfg := &swapConfig{
lnd: &lnd.LndServices,
store: store,
server: server,
}
sweeper := &sweep.Sweeper{Lnd: &lnd.LndServices}
blockEpochChan := make(chan interface{})
statusChan := make(chan SwapInfo)
const maxParts = 5
chanSet := loopdb.ChannelSet{2, 3}
// Initiate the swap.
req := *testRequest
req.OutgoingChanSet = chanSet
initResult, err := newLoopOutSwap(
context.Background(), cfg, height, &req,
)
if err != nil {
t.Fatal(err)
}
swap := initResult.swap
// Execute the swap in its own goroutine.
errChan := make(chan error)
swapCtx, cancel := context.WithCancel(context.Background())
go func() {
err := swap.execute(swapCtx, &executeConfig{
statusChan: statusChan,
sweeper: sweeper,
blockEpochChan: blockEpochChan,
timerFactory: timerFactory,
loopOutMaxParts: maxParts,
cancelSwap: server.CancelLoopOutSwap,
verifySchnorrSig: mockVerifySchnorrSigFail,
}, height)
if err != nil {
log.Error(err)
}
errChan <- err
}()
store.assertLoopOutStored()
state := <-statusChan
if state.State != loopdb.StateInitiated {
t.Fatal("unexpected state")
}
// Check that the SwapInfo contains the outgoing chan set
require.Equal(t, chanSet, state.OutgoingChanSet)
// Check that the SwapInfo does not contain a last hop
require.Nil(t, state.LastHop)
// Intercept the swap and prepay payments. Order is undefined.
payments := []test.RouterPaymentChannelMessage{
<-ctx.Lnd.RouterSendPaymentChannel,
<-ctx.Lnd.RouterSendPaymentChannel,
}
// Find the swap payment.
var swapPayment test.RouterPaymentChannelMessage
for _, p := range payments {
if p.Invoice == swap.SwapInvoice {
swapPayment = p
}
}
// Assert that it is sent as a multi-part payment.
if swapPayment.MaxParts != maxParts {
t.Fatalf("Expected %v parts, but got %v",
maxParts, swapPayment.MaxParts)
}
// Verify the outgoing channel set restriction.
if !reflect.DeepEqual(
[]uint64(req.OutgoingChanSet), swapPayment.OutgoingChanIds,
) {
t.Fatalf("Unexpected outgoing channel set")
}
// Swap is expected to register for confirmation of the htlc. Assert
// this to prevent a blocked channel in the mock.
ctx.AssertRegisterConf(false, defaultConfirmations)
// Cancel the swap. There is nothing else we need to assert. The payment
// parameters don't play a role in the remainder of the swap process.
cancel()
// Expect the swap to signal that it was cancelled.
err = <-errChan
if err != context.Canceled {
t.Fatal(err)
}
}
// TestLateHtlcPublish tests that the client is not revealing the preimage if
// there are not enough blocks left.
func TestLateHtlcPublish(t *testing.T) {
t.Run("stable protocol", func(t *testing.T) {
testLateHtlcPublish(t)
})
t.Run("experimental protocol", func(t *testing.T) {
loopdb.EnableExperimentalProtocol()
defer loopdb.ResetCurrentProtocolVersion()
testLateHtlcPublish(t)
})
}
func testLateHtlcPublish(t *testing.T) {
defer test.Guard(t)()
lnd := test.NewMockLnd()
ctx := test.NewContext(t, lnd)
server := newServerMock(lnd)
store := newStoreMock(t)
expiryChan := make(chan time.Time)
timerFactory := func(expiry time.Duration) <-chan time.Time {
return expiryChan
}
height := int32(600)
cfg := newSwapConfig(&lnd.LndServices, store, server)
testRequest.Expiry = height + testLoopOutMinOnChainCltvDelta
initResult, err := newLoopOutSwap(
context.Background(), cfg, height, testRequest,
)
if err != nil {
t.Fatal(err)
}
swap := initResult.swap
sweeper := &sweep.Sweeper{Lnd: &lnd.LndServices}
blockEpochChan := make(chan interface{})
statusChan := make(chan SwapInfo)
errChan := make(chan error)
go func() {
err := swap.execute(context.Background(), &executeConfig{
statusChan: statusChan,
sweeper: sweeper,
blockEpochChan: blockEpochChan,
timerFactory: timerFactory,
cancelSwap: server.CancelLoopOutSwap,
verifySchnorrSig: mockVerifySchnorrSigFail,
}, height)
if err != nil {
log.Error(err)
}
errChan <- err
}()
store.assertLoopOutStored()
state := <-statusChan
if state.State != loopdb.StateInitiated {
t.Fatal("unexpected state")
}
signalSwapPaymentResult := ctx.AssertPaid(swapInvoiceDesc)
signalPrepaymentResult := ctx.AssertPaid(prepayInvoiceDesc)
// Expect client to register for conf
ctx.AssertRegisterConf(false, defaultConfirmations)
// // Wait too long before publishing htlc.
blockEpochChan <- int32(swap.CltvExpiry - 10)
signalSwapPaymentResult(
errors.New(lndclient.PaymentResultUnknownPaymentHash),
)
signalPrepaymentResult(
errors.New(lndclient.PaymentResultUnknownPaymentHash),
)
store.assertStoreFinished(loopdb.StateFailTimeout)
status := <-statusChan
if status.State != loopdb.StateFailTimeout {
t.Fatal("unexpected state")
}
err = <-errChan
if err != nil {
t.Fatal(err)
}
}
// TestCustomSweepConfTarget ensures we are able to sweep a Loop Out HTLC with a
// custom confirmation target.
func TestCustomSweepConfTarget(t *testing.T) {
t.Run("stable protocol", func(t *testing.T) {
testCustomSweepConfTarget(t)
})
t.Run("experimental protocol", func(t *testing.T) {
loopdb.EnableExperimentalProtocol()
defer loopdb.ResetCurrentProtocolVersion()
testCustomSweepConfTarget(t)
})
}
func testCustomSweepConfTarget(t *testing.T) {
defer test.Guard(t)()
lnd := test.NewMockLnd()
ctx := test.NewContext(t, lnd)
server := newServerMock(lnd)
// Use the highest sweep confirmation target before we attempt to use
// the default.
testReq := *testRequest
testReq.SweepConfTarget = testLoopOutMinOnChainCltvDelta -
DefaultSweepConfTargetDelta - 1
// Set on-chain HTLC CLTV.
testReq.Expiry = ctx.Lnd.Height + testLoopOutMinOnChainCltvDelta
// Set up custom fee estimates such that the lower confirmation target
// yields a much higher fee rate.
ctx.Lnd.SetFeeEstimate(testReq.SweepConfTarget, 250)
ctx.Lnd.SetFeeEstimate(DefaultSweepConfTarget, 10000)
cfg := newSwapConfig(
&lnd.LndServices, newStoreMock(t), server,
)
initResult, err := newLoopOutSwap(
context.Background(), cfg, ctx.Lnd.Height, &testReq,
)
if err != nil {
t.Fatal(err)
}
swap := initResult.swap
// Set up the required dependencies to execute the swap.
//
// TODO: create test context similar to loopInTestContext.
sweeper := &sweep.Sweeper{Lnd: &lnd.LndServices}
blockEpochChan := make(chan interface{})
statusChan := make(chan SwapInfo)
expiryChan := make(chan time.Time)
timerFactory := func(expiry time.Duration) <-chan time.Time {
return expiryChan
}
errChan := make(chan error)
go func() {
err := swap.execute(context.Background(), &executeConfig{
statusChan: statusChan,
blockEpochChan: blockEpochChan,
timerFactory: timerFactory,
sweeper: sweeper,
cancelSwap: server.CancelLoopOutSwap,
verifySchnorrSig: mockVerifySchnorrSigFail,
}, ctx.Lnd.Height)
if err != nil {
log.Error(err)
}
errChan <- err
}()
// The swap should be found in its initial state.
cfg.store.(*storeMock).assertLoopOutStored()
state := <-statusChan
if state.State != loopdb.StateInitiated {
t.Fatal("unexpected state")
}
// We'll then pay both the swap and prepay invoice, which should trigger
// the server to publish the on-chain HTLC.
signalSwapPaymentResult := ctx.AssertPaid(swapInvoiceDesc)
signalPrepaymentResult := ctx.AssertPaid(prepayInvoiceDesc)
signalSwapPaymentResult(nil)
signalPrepaymentResult(nil)
// Notify the confirmation notification for the HTLC.
ctx.AssertRegisterConf(false, defaultConfirmations)
blockEpochChan <- ctx.Lnd.Height + 1
htlcTx := wire.NewMsgTx(2)
htlcTx.AddTxOut(&wire.TxOut{
Value: int64(swap.AmountRequested),
PkScript: swap.htlc.PkScript,
})
ctx.NotifyConf(htlcTx)
// The client should then register for a spend of the HTLC and attempt
// to sweep it using the custom confirmation target.
ctx.AssertRegisterSpendNtfn(swap.htlc.PkScript)
// Assert that we made a query to track our payment, as required for
// preimage push tracking.
trackPayment := ctx.AssertTrackPayment()
expiryChan <- time.Now()
// Expect a signing request for the HTLC success transaction.
if !IsTaprootSwap(&swap.SwapContract) {
<-ctx.Lnd.SignOutputRawChannel
}
cfg.store.(*storeMock).assertLoopOutState(loopdb.StatePreimageRevealed)
status := <-statusChan
if status.State != loopdb.StatePreimageRevealed {
t.Fatalf("expected state %v, got %v",
loopdb.StatePreimageRevealed, status.State)
}
// When using taproot htlcs the flow is different as we do reveal the
// preimage before sweeping in order for the server to trust us with
// our MuSig2 signing attempts.
if IsTaprootSwap(&swap.SwapContract) {
preimage := <-server.preimagePush
require.Equal(t, swap.Preimage, preimage)
// Try MuSig2 signing first and fail it so that we go for a
// normal sweep.
for i := 0; i < maxMusigSweepRetries; i++ {
expiryChan <- time.Now()
preimage := <-server.preimagePush
require.Equal(t, swap.Preimage, preimage)
}
<-ctx.Lnd.SignOutputRawChannel
}
// assertSweepTx performs some sanity checks on a sweep transaction to
// ensure it was constructed correctly.
assertSweepTx := func(expConfTarget int32) *wire.MsgTx {
t.Helper()
sweepTx := ctx.ReceiveTx()
if sweepTx.TxIn[0].PreviousOutPoint.Hash != htlcTx.TxHash() {
t.Fatalf("expected sweep tx to spend %v, got %v",
htlcTx.TxHash(), sweepTx.TxIn[0].PreviousOutPoint)
}
// The fee used for the sweep transaction is an estimate based
// on the maximum witness size, so we should expect to see a
// lower fee when using the actual witness size of the
// transaction.
fee := btcutil.Amount(
htlcTx.TxOut[0].Value - sweepTx.TxOut[0].Value,
)
weight := blockchain.GetTransactionWeight(btcutil.NewTx(sweepTx))
feeRate, err := ctx.Lnd.WalletKit.EstimateFeeRate(
context.Background(), expConfTarget,
)
if err != nil {
t.Fatalf("unable to retrieve fee estimate: %v", err)
}
minFee := feeRate.FeeForWeight(weight)
maxFee := btcutil.Amount(float64(minFee) * 1.1)
if fee < minFee && fee > maxFee {
t.Fatalf("expected sweep tx to have fee between %v-%v, "+
"got %v", minFee, maxFee, fee)
}
return sweepTx
}
// The sweep should have a fee that corresponds to the custom
// confirmation target.
_ = assertSweepTx(testReq.SweepConfTarget)
// Once we have published an on chain sweep, we expect a preimage to
// have been pushed to our server.
if !IsTaprootSwap(&swap.SwapContract) {
preimage := <-server.preimagePush
require.Equal(t, swap.Preimage, preimage)
}
// Now that we have pushed our preimage to the sever, we send an update
// indicating that our off chain htlc is settled. We do this so that
// we don't have to keep consuming preimage pushes from our server mock
// for every sweep attempt.
trackPayment.Updates <- lndclient.PaymentStatus{
State: lnrpc.Payment_SUCCEEDED,
}
// We'll then notify the height at which we begin using the default
// confirmation target.
defaultConfTargetHeight := ctx.Lnd.Height +
testLoopOutMinOnChainCltvDelta - DefaultSweepConfTargetDelta
blockEpochChan <- int32(defaultConfTargetHeight)
expiryChan <- time.Now()
// Expect another signing request.
<-ctx.Lnd.SignOutputRawChannel
// We should expect to see another sweep using the higher fee since the
// spend hasn't been confirmed yet.
sweepTx := assertSweepTx(DefaultSweepConfTarget)
// Notify the spend so that the swap reaches its final state.
ctx.NotifySpend(sweepTx, 0)
cfg.store.(*storeMock).assertLoopOutState(loopdb.StateSuccess)
status = <-statusChan
if status.State != loopdb.StateSuccess {
t.Fatalf("expected state %v, got %v", loopdb.StateSuccess,
status.State)
}
if err := <-errChan; err != nil {
t.Fatal(err)
}
}
// TestPreimagePush tests or logic that decides whether to push our preimage to
// the server. First, we test the case where we have not yet disclosed our
// preimage with a sweep, so we do not want to push our preimage yet. Next, we
// broadcast a sweep attempt and push our preimage to the server. In this stage
// we mock a server failure by not sending a settle update for our payment.
// Finally, we make a last sweep attempt, push the preimage (because we have
// not detected our settle) and settle the off chain htlc, indicating that the
// server successfully settled using the preimage push. In this test, we need
// to start with a fee rate that will be too high, then progress to an
// acceptable one.
func TestPreimagePush(t *testing.T) {
t.Run("stable protocol", func(t *testing.T) {
testPreimagePush(t)
})
t.Run("experimental protocol", func(t *testing.T) {
loopdb.EnableExperimentalProtocol()
defer loopdb.ResetCurrentProtocolVersion()
testPreimagePush(t)
})
}
func testPreimagePush(t *testing.T) {
defer test.Guard(t)()
lnd := test.NewMockLnd()
ctx := test.NewContext(t, lnd)
server := newServerMock(lnd)
testReq := *testRequest
testReq.SweepConfTarget = 10
testReq.Expiry = ctx.Lnd.Height + testLoopOutMinOnChainCltvDelta
// We set our mock fee estimate for our target sweep confs to be our
// max miner fee *2, so that our fee will definitely be above what we
// are willing to pay, and we will not sweep.
ctx.Lnd.SetFeeEstimate(
testReq.SweepConfTarget, chainfee.SatPerKWeight(
testReq.MaxMinerFee*2,
),
)
cfg := newSwapConfig(
&lnd.LndServices, newStoreMock(t), server,
)
initResult, err := newLoopOutSwap(
context.Background(), cfg, ctx.Lnd.Height, &testReq,
)
require.NoError(t, err)
swap := initResult.swap
// Set up the required dependencies to execute the swap.
sweeper := &sweep.Sweeper{Lnd: &lnd.LndServices}
blockEpochChan := make(chan interface{})
statusChan := make(chan SwapInfo)
expiryChan := make(chan time.Time)
timerFactory := func(_ time.Duration) <-chan time.Time {
return expiryChan
}
errChan := make(chan error)
go func() {
err := swap.execute(context.Background(), &executeConfig{
statusChan: statusChan,
blockEpochChan: blockEpochChan,
timerFactory: timerFactory,
sweeper: sweeper,
cancelSwap: server.CancelLoopOutSwap,
verifySchnorrSig: mockVerifySchnorrSigFail,
}, ctx.Lnd.Height)
if err != nil {
log.Error(err)
}
errChan <- err
}()
// The swap should be found in its initial state.
cfg.store.(*storeMock).assertLoopOutStored()
state := <-statusChan
require.Equal(t, loopdb.StateInitiated, state.State)
// We'll then pay both the swap and prepay invoice, which should trigger
// the server to publish the on-chain HTLC.
signalSwapPaymentResult := ctx.AssertPaid(swapInvoiceDesc)
signalPrepaymentResult := ctx.AssertPaid(prepayInvoiceDesc)
signalSwapPaymentResult(nil)
signalPrepaymentResult(nil)
// Notify the confirmation notification for the HTLC.
ctx.AssertRegisterConf(false, defaultConfirmations)
blockEpochChan <- ctx.Lnd.Height + 1
htlcTx := wire.NewMsgTx(2)
htlcTx.AddTxOut(&wire.TxOut{
Value: int64(swap.AmountRequested),
PkScript: swap.htlc.PkScript,
})
ctx.NotifyConf(htlcTx)
// The client should then register for a spend of the HTLC and attempt
// to sweep it using the custom confirmation target.
ctx.AssertRegisterSpendNtfn(swap.htlc.PkScript)
// Assert that we made a query to track our payment, as required for
// preimage push tracking.
trackPayment := ctx.AssertTrackPayment()
// Tick the expiry channel, we are still using our client confirmation
// target at this stage which has fees higher than our max acceptable
// fee. We do not expect a sweep attempt at this point. Since our
// preimage is not revealed, we also do not expect a preimage push.
expiryChan <- testTime
// When using taproot htlcs the flow is different as we do reveal the
// preimage before sweeping in order for the server to trust us with
// our MuSig2 signing attempts.
if IsTaprootSwap(&swap.SwapContract) {
cfg.store.(*storeMock).assertLoopOutState(
loopdb.StatePreimageRevealed,
)
status := <-statusChan
require.Equal(
t, status.State, loopdb.StatePreimageRevealed,
)
preimage := <-server.preimagePush
require.Equal(t, swap.Preimage, preimage)
// Try MuSig2 signing first and fail it so that we go for a
// normal sweep.
for i := 0; i < maxMusigSweepRetries; i++ {
expiryChan <- time.Now()
preimage := <-server.preimagePush
require.Equal(t, swap.Preimage, preimage)
}
<-ctx.Lnd.SignOutputRawChannel
// We expect the sweep tx to have been published.
ctx.ReceiveTx()
}
// Since we don't have a reliable mechanism to non-intrusively avoid
// races by setting the fee estimate too soon, let's sleep here a bit
// to ensure the first sweep fails.
time.Sleep(500 * time.Millisecond)
// Now we decrease our fees for the swap's confirmation target to less
// than the maximum miner fee.
ctx.Lnd.SetFeeEstimate(testReq.SweepConfTarget, chainfee.SatPerKWeight(
testReq.MaxMinerFee/2,
))
// Now when we report a new block and tick our expiry fee timer, and
// fees are acceptably low so we expect our sweep to be published.
blockEpochChan <- ctx.Lnd.Height + 2
expiryChan <- testTime
if IsTaprootSwap(&swap.SwapContract) {
preimage := <-server.preimagePush
require.Equal(t, swap.Preimage, preimage)
}
// Expect a signing request for the HTLC success transaction.
<-ctx.Lnd.SignOutputRawChannel
if !IsTaprootSwap(&swap.SwapContract) {
// This is the first time we have swept, so we expect our
// preimage revealed state to be set.
cfg.store.(*storeMock).assertLoopOutState(
loopdb.StatePreimageRevealed,
)
status := <-statusChan
require.Equal(
t, status.State, loopdb.StatePreimageRevealed,
)
}
// We expect the sweep tx to have been published.
ctx.ReceiveTx()
if !IsTaprootSwap(&swap.SwapContract) {
// Once we have published an on chain sweep, we expect a
// preimage to have been pushed to the server after the sweep.
preimage := <-server.preimagePush
require.Equal(t, swap.Preimage, preimage)
}
// To mock a server failure, we do not send a payment settled update
// for our off chain payment yet. We also do not confirm our sweep on
// chain yet so we can test our preimage push retry logic. Instead, we
// tick the expiry chan again to prompt another sweep.
expiryChan <- testTime
if IsTaprootSwap(&swap.SwapContract) {
preimage := <-server.preimagePush
require.Equal(t, swap.Preimage, preimage)
}
// We expect another signing request for out sweep, and publish of our
// sweep transaction.
<-ctx.Lnd.SignOutputRawChannel
ctx.ReceiveTx()
// Since we have not yet been notified of an off chain settle, and we
// have attempted to sweep again, we expect another preimage push
// attempt.
if !IsTaprootSwap(&swap.SwapContract) {
preimage := <-server.preimagePush
require.Equal(t, swap.Preimage, preimage)
}
// This time, we send a payment succeeded update into our payment stream
// to reflect that the server received our preimage push and settled off
// chain.
trackPayment.Updates <- lndclient.PaymentStatus{
State: lnrpc.Payment_SUCCEEDED,
}
// We tick one last time, this time expecting a sweep but no preimage
// push. The test's mocked preimage channel is un-buffered, so our test
// would hang if we pushed the preimage here.
expiryChan <- testTime
<-ctx.Lnd.SignOutputRawChannel
sweepTx := ctx.ReceiveTx()
// Finally, we put this swap out of its misery and notify a successful
// spend our our sweepTx and assert that the swap succeeds.
ctx.NotifySpend(sweepTx, 0)
cfg.store.(*storeMock).assertLoopOutState(loopdb.StateSuccess)
status := <-statusChan
require.Equal(
t, status.State, loopdb.StateSuccess,
)
require.NoError(t, <-errChan)
}
// TestExpiryBeforeReveal tests the case where the on-chain HTLC expires before
// we have revealed our preimage, demonstrating that we do not reveal our
// preimage once we've reached our expiry height.
func TestExpiryBeforeReveal(t *testing.T) {
t.Run("stable protocol", func(t *testing.T) {
testExpiryBeforeReveal(t)
})
// Note that there's no point of testing this case with the new
// protocol where we use taproot htlc and attempt MuSig2 sweep. The
// reason is that the preimage is revealed to the server once the
// htlc is confirmed in order to facilitate the cooperative signing of
// the sweep transaction.
}
func testExpiryBeforeReveal(t *testing.T) {
defer test.Guard(t)()
lnd := test.NewMockLnd()
ctx := test.NewContext(t, lnd)
server := newServerMock(lnd)
testReq := *testRequest
// Set on-chain HTLC CLTV.
testReq.Expiry = ctx.Lnd.Height + testLoopOutMinOnChainCltvDelta
// Set our fee estimate to higher than our max miner fee will allow.
lnd.SetFeeEstimate(testReq.SweepConfTarget, chainfee.SatPerKWeight(
testReq.MaxMinerFee*2,
))
// Setup the cfg using mock server and init a loop out request.
cfg := newSwapConfig(
&lnd.LndServices, newStoreMock(t), server,
)
initResult, err := newLoopOutSwap(
context.Background(), cfg, ctx.Lnd.Height, &testReq,
)
require.NoError(t, err)
swap := initResult.swap
// Set up the required dependencies to execute the swap.
sweeper := &sweep.Sweeper{Lnd: &lnd.LndServices}
blockEpochChan := make(chan interface{})
statusChan := make(chan SwapInfo)
expiryChan := make(chan time.Time)
timerFactory := func(_ time.Duration) <-chan time.Time {
return expiryChan
}
errChan := make(chan error)
go func() {
err := swap.execute(context.Background(), &executeConfig{
statusChan: statusChan,
blockEpochChan: blockEpochChan,
timerFactory: timerFactory,
sweeper: sweeper,
verifySchnorrSig: mockVerifySchnorrSigFail,
}, ctx.Lnd.Height)
if err != nil {
log.Error(err)
}
errChan <- err
}()
// The swap should be found in its initial state.
cfg.store.(*storeMock).assertLoopOutStored()
state := <-statusChan
require.Equal(t, loopdb.StateInitiated, state.State)
// We'll then pay both the swap and prepay invoice, which should trigger
// the server to publish the on-chain HTLC.
signalSwapPaymentResult := ctx.AssertPaid(swapInvoiceDesc)
signalPrepaymentResult := ctx.AssertPaid(prepayInvoiceDesc)
signalSwapPaymentResult(nil)
signalPrepaymentResult(nil)
// Notify the confirmation notification for the HTLC.
ctx.AssertRegisterConf(false, defaultConfirmations)
// Advance the block height to get the HTLC confirmed.
height := ctx.Lnd.Height + 1
blockEpochChan <- height
htlcTx := wire.NewMsgTx(2)
htlcTx.AddTxOut(&wire.TxOut{
Value: int64(swap.AmountRequested),
PkScript: swap.htlc.PkScript,
})
ctx.NotifyConf(htlcTx)
// The client should then register for a spend of the HTLC and attempt
// to sweep it using the custom confirmation target.
ctx.AssertRegisterSpendNtfn(swap.htlc.PkScript)
// Assert that we made a query to track our payment, as required for
// preimage push tracking.
ctx.AssertTrackPayment()
// Tick the expiry channel. Because our max miner fee is too high, we
// won't attempt a sweep at this point.
expiryChan <- testTime
// Since we don't have a reliable mechanism to non-intrusively avoid
// races by setting the fee estimate too soon, let's sleep here a bit
// to ensure the first sweep fails.
time.Sleep(500 * time.Millisecond)
// Now we decrease our conf target to less than our max miner fee.
lnd.SetFeeEstimate(testReq.SweepConfTarget, chainfee.SatPerKWeight(
testReq.MaxMinerFee/2,
))
// Advance the block height to the point where we would do timeout
// instead of pushing the preimage.
blockEpochChan <- testReq.Expiry + height
// Tick our expiry channel again to trigger another sweep attempt.
expiryChan <- testTime
// We should see our swap marked as failed.
cfg.store.(*storeMock).assertLoopOutState(
loopdb.StateFailTimeout,
)
status := <-statusChan
require.Equal(
t, status.State, loopdb.StateFailTimeout,
)
require.Nil(t, <-errChan)
}
// TestFailedOffChainCancelation tests sending of a cancelation message to
// the server when a swap fails due to off-chain routing.
func TestFailedOffChainCancelation(t *testing.T) {
t.Run("stable protocol", func(t *testing.T) {
testFailedOffChainCancelation(t)
})
t.Run("experimental protocol", func(t *testing.T) {
loopdb.EnableExperimentalProtocol()
defer loopdb.ResetCurrentProtocolVersion()
testFailedOffChainCancelation(t)
})
}
func testFailedOffChainCancelation(t *testing.T) {
defer test.Guard(t)()
lnd := test.NewMockLnd()
ctx := test.NewContext(t, lnd)
server := newServerMock(lnd)
testReq := *testRequest
testReq.Expiry = lnd.Height + 20
cfg := newSwapConfig(
&lnd.LndServices, newStoreMock(t), server,
)
initResult, err := newLoopOutSwap(
context.Background(), cfg, lnd.Height, &testReq,
)
require.NoError(t, err)
swap := initResult.swap
// Set up the required dependencies to execute the swap.
sweeper := &sweep.Sweeper{Lnd: &lnd.LndServices}
blockEpochChan := make(chan interface{})
statusChan := make(chan SwapInfo)
expiryChan := make(chan time.Time)
timerFactory := func(_ time.Duration) <-chan time.Time {
return expiryChan
}
errChan := make(chan error)
go func() {
cfg := &executeConfig{
statusChan: statusChan,
sweeper: sweeper,
blockEpochChan: blockEpochChan,
timerFactory: timerFactory,
cancelSwap: server.CancelLoopOutSwap,
verifySchnorrSig: mockVerifySchnorrSigFail,
}
err := swap.execute(context.Background(), cfg, ctx.Lnd.Height)
errChan <- err
}()
// The swap should be found in its initial state.
cfg.store.(*storeMock).assertLoopOutStored()
state := <-statusChan
require.Equal(t, loopdb.StateInitiated, state.State)
// Assert that we register for htlc confirmation notifications.
ctx.AssertRegisterConf(false, defaultConfirmations)
// We expect prepayment and invoice to be dispatched, order is unknown.
pmt1 := <-ctx.Lnd.RouterSendPaymentChannel
pmt2 := <-ctx.Lnd.RouterSendPaymentChannel
failUpdate := lndclient.PaymentStatus{
State: lnrpc.Payment_FAILED,
FailureReason: lnrpc.PaymentFailureReason_FAILURE_REASON_ERROR,
Htlcs: []*lndclient.HtlcAttempt{
{
// Include a non-failed htlc to test that we
// only report failed htlcs.
Status: lnrpc.HTLCAttempt_IN_FLIGHT,
},
// Add one htlc that failed within the server's
// infrastructure.
{
Status: lnrpc.HTLCAttempt_FAILED,
Route: &lnrpc.Route{
Hops: []*lnrpc.Hop{
{}, {}, {},
},
},
Failure: &lndclient.HtlcFailure{
FailureSourceIndex: 1,
},
},
// Add one htlc that failed in the network at wide.
{
Status: lnrpc.HTLCAttempt_FAILED,
Route: &lnrpc.Route{
Hops: []*lnrpc.Hop{
{}, {}, {}, {}, {},
},
},
Failure: &lndclient.HtlcFailure{
FailureSourceIndex: 1,
},
},
},
}
successUpdate := lndclient.PaymentStatus{
State: lnrpc.Payment_SUCCEEDED,
}
// We want to fail our swap payment and succeed the prepush, so we send
// a failure update to the payment that has the larger amount.
if pmt1.Amount > pmt2.Amount {
pmt1.TrackPaymentMessage.Updates <- failUpdate
pmt2.TrackPaymentMessage.Updates <- successUpdate
} else {
pmt1.TrackPaymentMessage.Updates <- successUpdate
pmt2.TrackPaymentMessage.Updates <- failUpdate
}
invoice, err := zpay32.Decode(
swap.LoopOutContract.SwapInvoice, lnd.ChainParams,
)
require.NoError(t, err)
require.NotNil(t, invoice.PaymentAddr)
swapCancelation := &outCancelDetails{
hash: swap.hash,