forked from lightningnetwork/lnd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lnd_funding_test.go
1491 lines (1272 loc) · 51.8 KB
/
lnd_funding_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 itest
import (
"context"
"fmt"
"testing"
"time"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/lightningnetwork/lnd/chainreg"
"github.com/lightningnetwork/lnd/fn"
"github.com/lightningnetwork/lnd/funding"
"github.com/lightningnetwork/lnd/input"
"github.com/lightningnetwork/lnd/labels"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/lightningnetwork/lnd/lnrpc/signrpc"
"github.com/lightningnetwork/lnd/lntest"
"github.com/lightningnetwork/lnd/lntest/node"
"github.com/lightningnetwork/lnd/lnwallet/chainfee"
"github.com/lightningnetwork/lnd/lnwire"
"github.com/stretchr/testify/require"
)
// testBasicChannelFunding performs a test exercising expected behavior from a
// basic funding workflow. The test creates a new channel between Alice and
// Bob, then immediately closes the channel after asserting some expected post
// conditions. Finally, the chain itself is checked to ensure the closing
// transaction was mined.
func testBasicChannelFunding(ht *lntest.HarnessTest) {
// Run through the test with combinations of all the different
// commitment types.
allTypes := []lnrpc.CommitmentType{
lnrpc.CommitmentType_STATIC_REMOTE_KEY,
lnrpc.CommitmentType_ANCHORS,
lnrpc.CommitmentType_SIMPLE_TAPROOT,
}
// testFunding is a function closure that takes Carol and Dave's
// commitment types and test the funding flow.
testFunding := func(ht *lntest.HarnessTest, carolCommitType,
daveCommitType lnrpc.CommitmentType) {
// Based on the current tweak variable for Carol, we'll
// preferentially signal the legacy commitment format. We do
// the same for Dave shortly below.
carolArgs := lntest.NodeArgsForCommitType(carolCommitType)
carol := ht.NewNode("Carol", carolArgs)
// Each time, we'll send Carol a new set of coins in order to
// fund the channel.
ht.FundCoins(btcutil.SatoshiPerBitcoin, carol)
daveArgs := lntest.NodeArgsForCommitType(daveCommitType)
dave := ht.NewNode("Dave", daveArgs)
// Before we start the test, we'll ensure both sides are
// connected to the funding flow can properly be executed.
ht.EnsureConnected(carol, dave)
var privateChan bool
// If this is to be a taproot channel type, then it needs to be
// private, otherwise it'll be rejected by Dave.
//
// TODO(roasbeef): lift after gossip 1.75
if carolCommitType == lnrpc.CommitmentType_SIMPLE_TAPROOT {
privateChan = true
}
// If carol wants taproot, but dave wants something
// else, then we'll assert that the channel negotiation
// attempt fails.
if carolCommitType == lnrpc.CommitmentType_SIMPLE_TAPROOT &&
daveCommitType != lnrpc.CommitmentType_SIMPLE_TAPROOT {
expectedErr := fmt.Errorf("requested channel type " +
"not supported")
amt := funding.MaxBtcFundingAmount
ht.OpenChannelAssertErr(
carol, dave, lntest.OpenChannelParams{
Private: privateChan,
Amt: amt,
CommitmentType: carolCommitType,
}, expectedErr,
)
return
}
carolChan, daveChan, closeChan := basicChannelFundingTest(
ht, carol, dave, nil, privateChan, &carolCommitType,
)
// Both nodes should report the same commitment
// type.
chansCommitType := carolChan.CommitmentType
require.Equal(ht, chansCommitType, daveChan.CommitmentType,
"commit types don't match")
// Now check that the commitment type reported by both nodes is
// what we expect. It will be the minimum of the two nodes'
// preference, in the order Legacy, Tweakless, Anchors.
expType := carolCommitType
switch daveCommitType {
// Dave supports taproot, type will be what Carol supports.
case lnrpc.CommitmentType_SIMPLE_TAPROOT:
// Dave supports anchors, type will be what Carol supports.
case lnrpc.CommitmentType_ANCHORS:
// However if Alice wants taproot chans, then we
// downgrade to anchors as this is still using implicit
// negotiation.
if expType == lnrpc.CommitmentType_SIMPLE_TAPROOT {
expType = lnrpc.CommitmentType_ANCHORS
}
// Dave only supports tweakless, channel will be downgraded to
// this type if Carol supports anchors.
case lnrpc.CommitmentType_STATIC_REMOTE_KEY:
switch expType {
case lnrpc.CommitmentType_ANCHORS:
expType = lnrpc.CommitmentType_STATIC_REMOTE_KEY
case lnrpc.CommitmentType_SIMPLE_TAPROOT:
expType = lnrpc.CommitmentType_STATIC_REMOTE_KEY
}
// Dave only supports legacy type, channel will be downgraded
// to this type.
case lnrpc.CommitmentType_LEGACY:
expType = lnrpc.CommitmentType_LEGACY
default:
ht.Fatalf("invalid commit type %v", daveCommitType)
}
// Check that the signalled type matches what we expect.
switch {
case expType == lnrpc.CommitmentType_ANCHORS &&
chansCommitType == lnrpc.CommitmentType_ANCHORS:
case expType == lnrpc.CommitmentType_STATIC_REMOTE_KEY &&
chansCommitType == lnrpc.CommitmentType_STATIC_REMOTE_KEY: //nolint:lll
case expType == lnrpc.CommitmentType_LEGACY &&
chansCommitType == lnrpc.CommitmentType_LEGACY:
case expType == lnrpc.CommitmentType_SIMPLE_TAPROOT &&
chansCommitType == lnrpc.CommitmentType_SIMPLE_TAPROOT:
default:
ht.Fatalf("expected nodes to signal "+
"commit type %v, instead got "+
"%v", expType, chansCommitType)
}
// As we've concluded this sub-test case we'll now close out
// the channel for both sides.
closeChan()
}
test:
// We'll test all possible combinations of the feature bit presence
// that both nodes can signal for this new channel type. We'll make a
// new Carol+Dave for each test instance as well.
for _, carolCommitType := range allTypes {
for _, daveCommitType := range allTypes {
cc := carolCommitType
dc := daveCommitType
testName := fmt.Sprintf(
"carol_commit=%v,dave_commit=%v", cc, dc,
)
success := ht.Run(testName, func(t *testing.T) {
st := ht.Subtest(t)
testFunding(st, cc, dc)
})
if !success {
break test
}
}
}
}
// basicChannelFundingTest is a sub-test of the main testBasicChannelFunding
// test. Given two nodes: Alice and Bob, it'll assert proper channel creation,
// then return a function closure that should be called to assert proper
// channel closure.
func basicChannelFundingTest(ht *lntest.HarnessTest,
alice, bob *node.HarnessNode, fundingShim *lnrpc.FundingShim,
privateChan bool, commitType *lnrpc.CommitmentType) (*lnrpc.Channel,
*lnrpc.Channel, func()) {
chanAmt := funding.MaxBtcFundingAmount
pushAmt := btcutil.Amount(100000)
satPerVbyte := btcutil.Amount(1)
// Record nodes' channel balance before testing.
aliceChannelBalance := alice.RPC.ChannelBalance()
bobChannelBalance := bob.RPC.ChannelBalance()
// Creates a helper closure to be used below which asserts the proper
// response to a channel balance RPC.
checkChannelBalance := func(node *node.HarnessNode,
oldChannelBalance *lnrpc.ChannelBalanceResponse,
local, remote btcutil.Amount) {
newResp := oldChannelBalance
newResp.LocalBalance.Sat += uint64(local)
newResp.LocalBalance.Msat += uint64(
lnwire.NewMSatFromSatoshis(local),
)
newResp.RemoteBalance.Sat += uint64(remote)
newResp.RemoteBalance.Msat += uint64(
lnwire.NewMSatFromSatoshis(remote),
)
// Deprecated fields.
newResp.Balance += int64(local)
ht.AssertChannelBalanceResp(node, newResp)
}
// For taproot channels, the only way we can negotiate is using the
// explicit commitment type. This allows us to continue supporting the
// existing min version comparison for implicit negotiation.
var commitTypeParam lnrpc.CommitmentType
if commitType != nil &&
*commitType == lnrpc.CommitmentType_SIMPLE_TAPROOT {
commitTypeParam = *commitType
}
// First establish a channel with a capacity of 0.5 BTC between Alice
// and Bob with Alice pushing 100k satoshis to Bob's side during
// funding. This function will block until the channel itself is fully
// open or an error occurs in the funding process. A series of
// assertions will be executed to ensure the funding process completed
// successfully.
chanPoint := ht.OpenChannel(alice, bob, lntest.OpenChannelParams{
Private: privateChan,
Amt: chanAmt,
PushAmt: pushAmt,
FundingShim: fundingShim,
SatPerVByte: satPerVbyte,
CommitmentType: commitTypeParam,
})
cType := ht.GetChannelCommitType(alice, chanPoint)
// With the channel open, ensure that the amount specified above has
// properly been pushed to Bob.
aliceLocalBalance := chanAmt - pushAmt - lntest.CalcStaticFee(cType, 0)
checkChannelBalance(
alice, aliceChannelBalance, aliceLocalBalance, pushAmt,
)
checkChannelBalance(
bob, bobChannelBalance, pushAmt, aliceLocalBalance,
)
aliceChannel := ht.GetChannelByChanPoint(alice, chanPoint)
bobChannel := ht.GetChannelByChanPoint(bob, chanPoint)
closeChan := func() {
// Finally, immediately close the channel. This function will
// also block until the channel is closed and will additionally
// assert the relevant channel closing post conditions.
ht.CloseChannel(alice, chanPoint)
}
return aliceChannel, bobChannel, closeChan
}
// testUnconfirmedChannelFunding tests that our unconfirmed change outputs can
// be used to fund channels.
func testUnconfirmedChannelFunding(ht *lntest.HarnessTest) {
const (
chanAmt = funding.MaxBtcFundingAmount
pushAmt = btcutil.Amount(100000)
)
// We'll start off by creating a node for Carol.
carol := ht.NewNode("Carol", nil)
alice := ht.Alice
// We'll send her some unconfirmed funds.
ht.FundCoinsUnconfirmed(2*chanAmt, carol)
// For neutrino backend, we will confirm the coins sent above and let
// Carol send all her funds to herself to create unconfirmed output.
if ht.IsNeutrinoBackend() {
// Confirm the above coins.
ht.MineBlocksAndAssertNumTxes(1, 1)
// Create a new address and send to herself.
resp := carol.RPC.NewAddress(&lnrpc.NewAddressRequest{
Type: lnrpc.AddressType_TAPROOT_PUBKEY,
})
// Once sent, Carol would have one unconfirmed UTXO.
carol.RPC.SendCoins(&lnrpc.SendCoinsRequest{
Addr: resp.Address,
SendAll: true,
})
}
// Now, we'll connect her to Alice so that they can open a channel
// together. The funding flow should select Carol's unconfirmed output
// as she doesn't have any other funds since it's a new node.
ht.ConnectNodes(carol, alice)
chanOpenUpdate := ht.OpenChannelAssertStream(
carol, alice, lntest.OpenChannelParams{
Amt: chanAmt,
PushAmt: pushAmt,
SpendUnconfirmed: true,
},
)
// Creates a helper closure to be used below which asserts the proper
// response to a channel balance RPC.
checkChannelBalance := func(node *node.HarnessNode,
local, remote, pendingLocal, pendingRemote btcutil.Amount) {
expectedResponse := &lnrpc.ChannelBalanceResponse{
LocalBalance: &lnrpc.Amount{
Sat: uint64(local),
Msat: uint64(lnwire.NewMSatFromSatoshis(
local,
)),
},
RemoteBalance: &lnrpc.Amount{
Sat: uint64(remote),
Msat: uint64(lnwire.NewMSatFromSatoshis(
remote,
)),
},
PendingOpenLocalBalance: &lnrpc.Amount{
Sat: uint64(pendingLocal),
Msat: uint64(lnwire.NewMSatFromSatoshis(
pendingLocal,
)),
},
PendingOpenRemoteBalance: &lnrpc.Amount{
Sat: uint64(pendingRemote),
Msat: uint64(lnwire.NewMSatFromSatoshis(
pendingRemote,
)),
},
UnsettledLocalBalance: &lnrpc.Amount{},
UnsettledRemoteBalance: &lnrpc.Amount{},
// Deprecated fields.
Balance: int64(local),
PendingOpenBalance: int64(pendingLocal),
}
ht.AssertChannelBalanceResp(node, expectedResponse)
}
// As the channel is pending open, it's expected Carol has both zero
// local and remote balances, and pending local/remote should not be
// zero.
//
// Note that atm we haven't obtained the chanPoint yet, so we use the
// type directly.
cType := lnrpc.CommitmentType_STATIC_REMOTE_KEY
carolLocalBalance := chanAmt - pushAmt - lntest.CalcStaticFee(cType, 0)
checkChannelBalance(carol, 0, 0, carolLocalBalance, pushAmt)
// For Alice, her local/remote balances should be zero, and the
// local/remote balances are the mirror of Carol's.
checkChannelBalance(alice, 0, 0, pushAmt, carolLocalBalance)
// Confirm the channel and wait for it to be recognized by both
// parties. For neutrino backend, the funding transaction should be
// mined. Otherwise, two transactions should be mined, the unconfirmed
// spend and the funding tx.
ht.MineBlocksAndAssertNumTxes(6, 2)
chanPoint := ht.WaitForChannelOpenEvent(chanOpenUpdate)
// With the channel open, we'll check the balances on each side of the
// channel as a sanity check to ensure things worked out as intended.
checkChannelBalance(carol, carolLocalBalance, pushAmt, 0, 0)
checkChannelBalance(alice, pushAmt, carolLocalBalance, 0, 0)
// TODO(yy): remove the sleep once the following bug is fixed.
//
// We may get the error `unable to gracefully close channel while peer
// is offline (try force closing it instead): channel link not found`.
// This happens because the channel link hasn't been added yet but we
// now proceed to closing the channel. We may need to revisit how the
// channel open event is created and make sure the event is only sent
// after all relevant states have been updated.
time.Sleep(2 * time.Second)
// Now that we're done with the test, the channel can be closed.
ht.CloseChannel(carol, chanPoint)
}
// testChannelFundingInputTypes tests that any type of supported input type can
// be used to fund channels.
func testChannelFundingInputTypes(ht *lntest.HarnessTest) {
// We'll start off by creating a node for Carol.
carol := ht.NewNode("Carol", nil)
// Now, we'll connect her to Alice so that they can open a
// channel together.
ht.ConnectNodes(carol, ht.Alice)
runChannelFundingInputTypes(ht, ht.Alice, carol)
}
// runChannelFundingInputTypes tests that any type of supported input type can
// be used to fund channels.
func runChannelFundingInputTypes(ht *lntest.HarnessTest, alice,
carol *node.HarnessNode) {
const (
chanAmt = funding.MaxBtcFundingAmount
burnAddr = "bcrt1qxsnqpdc842lu8c0xlllgvejt6rhy49u6fmpgyz"
)
fundMixed := func(amt btcutil.Amount, target *node.HarnessNode) {
ht.FundCoins(amt/5, target)
ht.FundCoins(amt/5, target)
ht.FundCoinsP2TR(amt/5, target)
ht.FundCoinsP2TR(amt/5, target)
ht.FundCoinsP2TR(amt/5, target)
}
fundMultipleP2TR := func(amt btcutil.Amount, target *node.HarnessNode) {
ht.FundCoinsP2TR(amt/4, target)
ht.FundCoinsP2TR(amt/4, target)
ht.FundCoinsP2TR(amt/4, target)
ht.FundCoinsP2TR(amt/4, target)
}
fundWithTypes := []func(amt btcutil.Amount, target *node.HarnessNode){
ht.FundCoins, ht.FundCoinsNP2WKH, ht.FundCoinsP2TR, fundMixed,
fundMultipleP2TR,
}
// Creates a helper closure to be used below which asserts the
// proper response to a channel balance RPC.
checkChannelBalance := func(node *node.HarnessNode, local,
remote, pendingLocal, pendingRemote btcutil.Amount) {
expectedResponse := &lnrpc.ChannelBalanceResponse{
LocalBalance: &lnrpc.Amount{
Sat: uint64(local),
Msat: uint64(lnwire.NewMSatFromSatoshis(local)),
},
RemoteBalance: &lnrpc.Amount{
Sat: uint64(remote),
Msat: uint64(lnwire.NewMSatFromSatoshis(
remote,
)),
},
PendingOpenLocalBalance: &lnrpc.Amount{
Sat: uint64(pendingLocal),
Msat: uint64(lnwire.NewMSatFromSatoshis(
pendingLocal,
)),
},
PendingOpenRemoteBalance: &lnrpc.Amount{
Sat: uint64(pendingRemote),
Msat: uint64(lnwire.NewMSatFromSatoshis(
pendingRemote,
)),
},
UnsettledLocalBalance: &lnrpc.Amount{},
UnsettledRemoteBalance: &lnrpc.Amount{},
// Deprecated fields.
Balance: int64(local),
PendingOpenBalance: int64(pendingLocal),
}
ht.AssertChannelBalanceResp(node, expectedResponse)
}
for _, funder := range fundWithTypes {
// We'll send her some confirmed funds. We send 10% more than
// we need to account for fees.
funder((chanAmt*11)/10, carol)
chanOpenUpdate := ht.OpenChannelAssertStream(
carol, alice, lntest.OpenChannelParams{
Amt: chanAmt,
},
)
// As the channel is pending open, it's expected Carol has both
// zero local and remote balances, and pending local/remote
// should not be zero.
//
// Note that atm we haven't obtained the chanPoint yet, so we
// use the type directly.
cType := lnrpc.CommitmentType_STATIC_REMOTE_KEY
carolLocalBalance := chanAmt - lntest.CalcStaticFee(cType, 0)
checkChannelBalance(carol, 0, 0, carolLocalBalance, 0)
// For Alice, her local/remote balances should be zero, and the
// local/remote balances are the mirror of Carol's.
checkChannelBalance(alice, 0, 0, 0, carolLocalBalance)
// Confirm the channel and wait for it to be recognized by both
// parties. Two transactions should be mined, the unconfirmed
// spend and the funding tx.
ht.MineBlocksAndAssertNumTxes(1, 1)
chanPoint := ht.WaitForChannelOpenEvent(chanOpenUpdate)
// With the channel open, we'll check the balances on each side
// of the channel as a sanity check to ensure things worked out
// as intended.
checkChannelBalance(carol, carolLocalBalance, 0, 0, 0)
checkChannelBalance(alice, 0, carolLocalBalance, 0, 0)
// TODO(yy): remove the sleep once the following bug is fixed.
//
// We may get the error `unable to gracefully close channel
// while peer is offline (try force closing it instead):
// channel link not found`. This happens because the channel
// link hasn't been added yet but we now proceed to closing the
// channel. We may need to revisit how the channel open event
// is created and make sure the event is only sent after all
// relevant states have been updated.
time.Sleep(2 * time.Second)
// Now that we're done with the test, the channel can be closed.
ht.CloseChannel(carol, chanPoint)
// Empty out the wallet so there aren't any lingering coins.
sendAllCoinsConfirm(ht, carol, burnAddr)
}
}
// sendAllCoinsConfirm sends all coins of the node's wallet to the given address
// and awaits one confirmation.
func sendAllCoinsConfirm(ht *lntest.HarnessTest, node *node.HarnessNode,
addr string) {
sweepReq := &lnrpc.SendCoinsRequest{
Addr: addr,
SendAll: true,
TargetConf: 6,
}
node.RPC.SendCoins(sweepReq)
ht.MineBlocksAndAssertNumTxes(1, 1)
}
// testExternalFundingChanPoint tests that we're able to carry out a normal
// channel funding workflow given a channel point that was constructed outside
// the main daemon.
func testExternalFundingChanPoint(ht *lntest.HarnessTest) {
runExternalFundingScriptEnforced(ht)
runExternalFundingTaproot(ht)
}
// runExternalFundingChanPoint runs the actual test that tests we're able to
// carry out a normal channel funding workflow given a channel point that was
// constructed outside the main daemon for the script enforced channel type.
func runExternalFundingScriptEnforced(ht *lntest.HarnessTest) {
// First, we'll create two new nodes that we'll use to open channel
// between for this test.
carol := ht.NewNode("carol", nil)
dave := ht.NewNode("dave", nil)
commitmentType := lnrpc.CommitmentType_SCRIPT_ENFORCED_LEASE
// Carol will be funding the channel, so we'll send some coins over to
// her and ensure they have enough confirmations before we proceed.
ht.FundCoins(btcutil.SatoshiPerBitcoin, carol)
// Before we start the test, we'll ensure both sides are connected to
// the funding flow can properly be executed.
ht.EnsureConnected(carol, dave)
// At this point, we're ready to simulate our external channel funding
// flow. To start with, we'll create a pending channel with a shim for
// a transaction that will never be published.
const thawHeight uint32 = 10
const chanSize = funding.MaxBtcFundingAmount
fundingShim1, chanPoint1 := deriveFundingShim(
ht, carol, dave, chanSize, thawHeight, false, commitmentType,
)
ht.OpenChannelAssertPending(
carol, dave, lntest.OpenChannelParams{
Amt: chanSize,
FundingShim: fundingShim1,
},
)
ht.AssertNodesNumPendingOpenChannels(carol, dave, 1)
// That channel is now pending forever and normally would saturate the
// max pending channel limit for both nodes. But because the channel is
// externally funded, we should still be able to open another one. Let's
// do exactly that now. For this one we publish the transaction so we
// can mine it later.
fundingShim2, chanPoint2 := deriveFundingShim(
ht, carol, dave, chanSize, thawHeight, true, commitmentType,
)
// At this point, we'll now carry out the normal basic channel funding
// test as everything should now proceed as normal (a regular channel
// funding flow).
carolChan, daveChan, _ := basicChannelFundingTest(
ht, carol, dave, fundingShim2, false, nil,
)
// Both channels should be marked as frozen with the proper thaw
// height.
require.Equal(ht, thawHeight, carolChan.ThawHeight,
"thaw height unmatched")
require.Equal(ht, thawHeight, daveChan.ThawHeight,
"thaw height unmatched")
// Next, to make sure the channel functions as normal, we'll make some
// payments within the channel.
payAmt := btcutil.Amount(100000)
invoice := &lnrpc.Invoice{
Memo: "new chans",
Value: int64(payAmt),
}
resp := dave.RPC.AddInvoice(invoice)
ht.CompletePaymentRequests(carol, []string{resp.PaymentRequest})
// Now that the channels are open, and we've confirmed that they're
// operational, we'll now ensure that the channels are frozen as
// intended (if requested).
//
// First, we'll try to close the channel as Carol, the initiator. This
// should fail as a frozen channel only allows the responder to
// initiate a channel close.
err := ht.CloseChannelAssertErr(carol, chanPoint2, false)
require.Contains(ht, err.Error(), "cannot co-op close frozen channel")
// Before Dave closes the channel, he needs to check the invoice is
// settled to avoid an error saying cannot close channel due to active
// HTLCs.
ht.AssertInvoiceSettled(dave, resp.PaymentAddr)
// TODO(yy): remove the sleep once the following bug is fixed.
// When the invoice is reported settled, the commitment dance is not
// yet finished, which can cause an error when closing the channel,
// saying there's active HTLCs. We need to investigate this issue and
// reverse the order to, first finish the commitment dance, then report
// the invoice as settled.
time.Sleep(2 * time.Second)
// Next we'll try but this time with Dave (the responder) as the
// initiator. This time the channel should be closed as normal.
ht.CloseChannel(dave, chanPoint2)
// As a last step, we check if we still have the pending channel
// hanging around because we never published the funding TX.
ht.AssertNodesNumPendingOpenChannels(carol, dave, 1)
// Let's make sure we can abandon it.
carol.RPC.AbandonChannel(&lnrpc.AbandonChannelRequest{
ChannelPoint: chanPoint1,
PendingFundingShimOnly: true,
})
dave.RPC.AbandonChannel(&lnrpc.AbandonChannelRequest{
ChannelPoint: chanPoint1,
PendingFundingShimOnly: true,
})
// It should now not appear in the pending channels anymore.
ht.AssertNodesNumPendingOpenChannels(carol, dave, 0)
}
// runExternalFundingTaproot runs the actual test that tests we're able to carry
// out a normal channel funding workflow given a channel point that was
// constructed outside the main daemon for the taproot channel type.
func runExternalFundingTaproot(ht *lntest.HarnessTest) {
// First, we'll create two new nodes that we'll use to open channel
// between for this test.
commitmentType := lnrpc.CommitmentType_SIMPLE_TAPROOT
args := lntest.NodeArgsForCommitType(commitmentType)
carol := ht.NewNode("carol", args)
// We'll attempt two channels, so Dave will need to accept two pending
// ones.
dave := ht.NewNode("dave", append(args, "--maxpendingchannels=2"))
// Carol will be funding the channel, so we'll send some coins over to
// her and ensure they have enough confirmations before we proceed.
ht.FundCoins(btcutil.SatoshiPerBitcoin, carol)
// Before we start the test, we'll ensure both sides are connected to
// the funding flow can properly be executed.
ht.EnsureConnected(carol, dave)
// At this point, we're ready to simulate our external channel funding
// flow. To start with, we'll create a pending channel with a shim for
// a transaction that will never be published.
const thawHeight uint32 = 10
const chanSize = funding.MaxBtcFundingAmount
fundingShim1, chanPoint1 := deriveFundingShim(
ht, carol, dave, chanSize, thawHeight, false, commitmentType,
)
ht.OpenChannelAssertPending(carol, dave, lntest.OpenChannelParams{
Amt: chanSize,
FundingShim: fundingShim1,
CommitmentType: commitmentType,
Private: true,
})
ht.AssertNodesNumPendingOpenChannels(carol, dave, 1)
// That channel is now pending forever and normally would saturate the
// max pending channel limit for both nodes. But because the channel is
// externally funded, we should still be able to open another one. Let's
// do exactly that now. For this one we publish the transaction so we
// can mine it later.
fundingShim2, chanPoint2 := deriveFundingShim(
ht, carol, dave, chanSize, thawHeight, true, commitmentType,
)
// At this point, we'll now carry out the normal basic channel funding
// test as everything should now proceed as normal (a regular channel
// funding flow).
carolChan, daveChan, _ := basicChannelFundingTest(
ht, carol, dave, fundingShim2, true, &commitmentType,
)
// The itest harness doesn't mine blocks for private channels, so we
// want to make sure the channel with the published and mined
// transaction leaves the pending state.
ht.MineBlocks(6)
rpcChanPointToStr := func(cp *lnrpc.ChannelPoint) string {
txid, err := chainhash.NewHash(cp.GetFundingTxidBytes())
require.NoError(ht, err)
return fmt.Sprintf("%v:%d", txid.String(), cp.OutputIndex)
}
pendingCarol := carol.RPC.PendingChannels().PendingOpenChannels
require.Len(ht, pendingCarol, 1)
require.Equal(
ht, rpcChanPointToStr(chanPoint1),
pendingCarol[0].Channel.ChannelPoint,
)
openCarol := carol.RPC.ListChannels(&lnrpc.ListChannelsRequest{
ActiveOnly: true,
PrivateOnly: true,
})
require.Len(ht, openCarol.Channels, 1)
require.Equal(
ht, rpcChanPointToStr(chanPoint2),
openCarol.Channels[0].ChannelPoint,
)
pendingDave := dave.RPC.PendingChannels().PendingOpenChannels
require.Len(ht, pendingDave, 1)
require.Equal(
ht, rpcChanPointToStr(chanPoint1),
pendingDave[0].Channel.ChannelPoint,
)
openDave := dave.RPC.ListChannels(&lnrpc.ListChannelsRequest{
ActiveOnly: true,
PrivateOnly: true,
})
require.Len(ht, openDave.Channels, 1)
require.Equal(
ht, rpcChanPointToStr(chanPoint2),
openDave.Channels[0].ChannelPoint,
)
// Both channels should be marked as frozen with the proper thaw height.
require.EqualValues(ht, thawHeight, carolChan.ThawHeight, "thaw height")
require.EqualValues(ht, thawHeight, daveChan.ThawHeight, "thaw height")
// Next, to make sure the channel functions as normal, we'll make some
// payments within the channel.
payAmt := btcutil.Amount(100000)
invoice := &lnrpc.Invoice{
Memo: "new chans",
Value: int64(payAmt),
}
resp := dave.RPC.AddInvoice(invoice)
ht.CompletePaymentRequests(carol, []string{resp.PaymentRequest})
// Now that the channels are open, and we've confirmed that they're
// operational, we'll now ensure that the channels are frozen as
// intended (if requested).
//
// First, we'll try to close the channel as Carol, the initiator. This
// should fail as a frozen channel only allows the responder to
// initiate a channel close.
err := ht.CloseChannelAssertErr(carol, chanPoint2, false)
require.Contains(ht, err.Error(), "cannot co-op close frozen channel")
// Before Dave closes the channel, he needs to check the invoice is
// settled to avoid an error saying cannot close channel due to active
// HTLCs.
ht.AssertInvoiceSettled(dave, resp.PaymentAddr)
// TODO(yy): remove the sleep once the following bug is fixed.
// When the invoice is reported settled, the commitment dance is not
// yet finished, which can cause an error when closing the channel,
// saying there's active HTLCs. We need to investigate this issue and
// reverse the order to, first finish the commitment dance, then report
// the invoice as settled.
time.Sleep(2 * time.Second)
// Next we'll try but this time with Dave (the responder) as the
// initiator. This time the channel should be closed as normal.
ht.CloseChannel(dave, chanPoint2)
// Let's make sure we can abandon it.
carol.RPC.AbandonChannel(&lnrpc.AbandonChannelRequest{
ChannelPoint: chanPoint1,
PendingFundingShimOnly: true,
})
dave.RPC.AbandonChannel(&lnrpc.AbandonChannelRequest{
ChannelPoint: chanPoint1,
PendingFundingShimOnly: true,
})
// It should now not appear in the pending channels anymore.
ht.AssertNodesNumPendingOpenChannels(carol, dave, 0)
}
// testFundingPersistence is intended to ensure that the Funding Manager
// persists the state of new channels prior to broadcasting the channel's
// funding transaction. This ensures that the daemon maintains an up-to-date
// representation of channels if the system is restarted or disconnected.
// testFundingPersistence mirrors testBasicChannelFunding, but adds restarts
// and checks for the state of channels with unconfirmed funding transactions.
func testChannelFundingPersistence(ht *lntest.HarnessTest) {
chanAmt := funding.MaxBtcFundingAmount
pushAmt := btcutil.Amount(0)
// As we need to create a channel that requires more than 1
// confirmation before it's open, with the current set of defaults,
// we'll need to create a new node instance.
const numConfs = 5
carolArgs := []string{
fmt.Sprintf("--bitcoin.defaultchanconfs=%v", numConfs),
}
carol := ht.NewNode("Carol", carolArgs)
alice := ht.Alice
ht.ConnectNodes(alice, carol)
// Create a new channel that requires 5 confs before it's considered
// open, then broadcast the funding transaction
param := lntest.OpenChannelParams{
Amt: chanAmt,
PushAmt: pushAmt,
}
update := ht.OpenChannelAssertPending(alice, carol, param)
// At this point, the channel's funding transaction will have been
// broadcast, but not confirmed. Alice and Bob's nodes should reflect
// this when queried via RPC.
ht.AssertNumPendingOpenChannels(alice, 1)
ht.AssertNumPendingOpenChannels(carol, 1)
// Restart both nodes to test that the appropriate state has been
// persisted and that both nodes recover gracefully.
ht.RestartNode(alice)
ht.RestartNode(carol)
fundingTxID, err := chainhash.NewHash(update.Txid)
require.NoError(ht, err, "unable to convert funding txid "+
"into chainhash.Hash")
// Mine a block, then wait for Alice's node to notify us that the
// channel has been opened. The funding transaction should be found
// within the newly mined block.
block := ht.MineBlocksAndAssertNumTxes(1, 1)[0]
ht.AssertTxInBlock(block, *fundingTxID)
// Get the height that our transaction confirmed at.
height := int32(ht.CurrentHeight())
// Restart both nodes to test that the appropriate state has been
// persisted and that both nodes recover gracefully.
ht.RestartNode(alice)
ht.RestartNode(carol)
// The following block ensures that after both nodes have restarted,
// they have reconnected before the execution of the next test.
ht.EnsureConnected(alice, carol)
// Next, mine enough blocks s.t the channel will open with a single
// additional block mined.
ht.MineBlocks(3)
// Assert that our wallet has our opening transaction with a label
// that does not have a channel ID set yet, because we have not
// reached our required confirmations.
tx := ht.AssertTxAtHeight(alice, height, fundingTxID)
// At this stage, we expect the transaction to be labelled, but not with
// our channel ID because our transaction has not yet confirmed.
label := labels.MakeLabel(labels.LabelTypeChannelOpen, nil)
require.Equal(ht, label, tx.Label, "open channel label wrong")
// Both nodes should still show a single channel as pending.
ht.AssertNumPendingOpenChannels(alice, 1)
ht.AssertNumPendingOpenChannels(carol, 1)
// Finally, mine the last block which should mark the channel as open.
ht.MineBlocks(1)
// At this point, the channel should be fully opened and there should
// be no pending channels remaining for either node.
ht.AssertNumPendingOpenChannels(alice, 0)
ht.AssertNumPendingOpenChannels(carol, 0)
// The channel should be listed in the peer information returned by
// both peers.
chanPoint := lntest.ChanPointFromPendingUpdate(update)
// Re-lookup our transaction in the block that it confirmed in.
tx = ht.AssertTxAtHeight(alice, height, fundingTxID)
// Check both nodes to ensure that the channel is ready for operation.
chanAlice := ht.AssertChannelExists(alice, chanPoint)
ht.AssertChannelExists(carol, chanPoint)
// Make sure Alice and Carol have seen the channel in their network
// topology.
ht.AssertChannelInGraph(alice, chanPoint)
ht.AssertChannelInGraph(carol, chanPoint)
// Create an additional check for our channel assertion that will
// check that our label is as expected.
shortChanID := lnwire.NewShortChanIDFromInt(chanAlice.ChanId)
label = labels.MakeLabel(labels.LabelTypeChannelOpen, &shortChanID)
require.Equal(ht, label, tx.Label, "open channel label not updated")
// Finally, immediately close the channel. This function will also
// block until the channel is closed and will additionally assert the
// relevant channel closing post conditions.
ht.CloseChannel(alice, chanPoint)
}
// testBatchChanFunding makes sure multiple channels can be opened in one batch
// transaction in an atomic way.
func testBatchChanFunding(ht *lntest.HarnessTest) {
// First, we'll create two new nodes that we'll use to open channels
// to during this test. Carol has a high minimum funding amount that
// we'll use to trigger an error during the batch channel open.
carol := ht.NewNode("carol", []string{"--minchansize=200000"})
dave := ht.NewNode("dave", nil)
// Next we create a node that will receive a zero-conf channel open from
// Alice. We'll create the node with the required parameters.
scidAliasArgs := []string{
"--protocol.option-scid-alias",
"--protocol.zero-conf",
"--protocol.anchors",
}
eve := ht.NewNode("eve", scidAliasArgs)
alice, bob := ht.Alice, ht.Bob
ht.RestartNodeWithExtraArgs(alice, scidAliasArgs)
// Before we start the test, we'll ensure Alice is connected to Carol
// and Dave, so she can open channels to both of them (and Bob).
ht.EnsureConnected(alice, bob)
ht.EnsureConnected(alice, carol)
ht.EnsureConnected(alice, dave)
ht.EnsureConnected(alice, eve)
expectedFeeRate := chainfee.SatPerKWeight(2500)
// We verify that the channel opening uses the correct fee rate.
ht.SetFeeEstimateWithConf(expectedFeeRate, 3)
// Let's create our batch TX request. This first one should fail as we
// open a channel to Carol that is too small for her min chan size.
batchReq := &lnrpc.BatchOpenChannelRequest{
TargetConf: 3,
MinConfs: 1,
Channels: []*lnrpc.BatchOpenChannel{{
NodePubkey: bob.PubKey[:],
LocalFundingAmount: 100_000,
BaseFee: 1337,
UseBaseFee: true,
}, {
NodePubkey: carol.PubKey[:],
LocalFundingAmount: 100_000,
FeeRate: 1337,
UseFeeRate: true,
}, {
NodePubkey: dave.PubKey[:],
LocalFundingAmount: 100_000,
BaseFee: 1337,
UseBaseFee: true,
FeeRate: 1337,
UseFeeRate: true,
}, {