forked from lightningnetwork/lnd
-
Notifications
You must be signed in to change notification settings - Fork 24
/
interface_test.go
3106 lines (2782 loc) · 92.2 KB
/
interface_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 lnwallet_test
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net"
"os"
"path"
"path/filepath"
"reflect"
"runtime"
"strings"
"testing"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/decred/dcrlnd/chainntnfs/dcrdnotify"
"github.com/decred/slog"
bolt "go.etcd.io/bbolt"
_ "github.com/decred/dcrwallet/wallet/v3/drivers/bdb"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/chaincfg/v2"
"github.com/decred/dcrd/dcrec"
"github.com/decred/dcrd/dcrec/secp256k1/v2"
"github.com/decred/dcrd/dcrjson/v2"
"github.com/decred/dcrd/dcrutil/v2"
"github.com/decred/dcrd/rpcclient/v5"
"github.com/decred/dcrd/rpctest"
"github.com/decred/dcrd/txscript/v2"
"github.com/decred/dcrd/wire"
"github.com/decred/dcrlnd/chainntnfs"
"github.com/decred/dcrlnd/channeldb"
"github.com/decred/dcrlnd/input"
"github.com/decred/dcrlnd/keychain"
"github.com/decred/dcrlnd/lntest"
"github.com/decred/dcrlnd/lnwallet"
"github.com/decred/dcrlnd/lnwallet/dcrwallet"
"github.com/decred/dcrlnd/lnwallet/remotedcrwallet"
"github.com/decred/dcrlnd/lnwire"
)
var (
bobsPrivKey = []byte{
0x81, 0xb6, 0x37, 0xd8, 0xfc, 0xd2, 0xc6, 0xda,
0x63, 0x59, 0xe6, 0x96, 0x31, 0x13, 0xa1, 0x17,
0xd, 0xe7, 0x95, 0xe4, 0xb7, 0x25, 0xb8, 0x4d,
0x1e, 0xb, 0x4c, 0xfd, 0x9e, 0xc5, 0x8c, 0xe9,
}
// Use a hard-coded HD seed.
testHdSeed = chainhash.Hash{
0xb7, 0x94, 0x38, 0x5f, 0x2d, 0x1e, 0xf7, 0xab,
0x4d, 0x92, 0x73, 0xd1, 0x90, 0x63, 0x81, 0xb4,
0x4f, 0x2f, 0x6f, 0x25, 0x88, 0xa3, 0xef, 0xb9,
0x6a, 0x49, 0x18, 0x83, 0x31, 0x98, 0x47, 0x53,
}
aliceHDSeed = chainhash.Hash{
0xb7, 0x94, 0x38, 0x5f, 0x2d, 0x1e, 0xf7, 0xab,
0x4d, 0x92, 0x73, 0xd1, 0x90, 0x63, 0x81, 0xb4,
0x4f, 0x2f, 0x6f, 0x25, 0x18, 0xa3, 0xef, 0xb9,
0x64, 0x49, 0x18, 0x83, 0x31, 0x98, 0x47, 0x53,
}
bobHDSeed = chainhash.Hash{
0xb7, 0x94, 0x38, 0x5f, 0x2d, 0x1e, 0xf7, 0xab,
0x4d, 0x92, 0x73, 0xd1, 0x90, 0x63, 0x81, 0xb4,
0x4f, 0x2f, 0x6f, 0x25, 0x98, 0xa3, 0xef, 0xb9,
0x69, 0x49, 0x18, 0x83, 0x31, 0x98, 0x47, 0x53,
}
netParams = chaincfg.SimNetParams()
chainHash = &netParams.GenesisHash
// TODO(matheusd) Are these all?
scriptFlagsForTest = txscript.ScriptDiscourageUpgradableNops |
txscript.ScriptVerifyCleanStack |
txscript.ScriptVerifyCheckLockTimeVerify |
txscript.ScriptVerifyCheckSequenceVerify |
txscript.ScriptVerifySHA256
_, alicePub = secp256k1.PrivKeyFromBytes(testHdSeed[:])
_, bobPub = secp256k1.PrivKeyFromBytes(bobsPrivKey)
// The number of confirmations required to consider any created channel
// open.
numReqConfs uint16 = 1
csvDelay uint16 = 4
scriptVersion uint16 = 0
bobAddr, _ = net.ResolveTCPAddr("tcp", "10.0.0.2:9000")
aliceAddr, _ = net.ResolveTCPAddr("tcp", "10.0.0.3:9000")
defaultFeeRate = lnwallet.AtomPerKByte(1e4)
)
// assertProperBalance asserts than the total value of the unspent outputs
// within the wallet are *exactly* amount. If unable to retrieve the current
// balance, or the assertion fails, the test will halt with a fatal error.
func assertProperBalance(t *testing.T, lw *lnwallet.LightningWallet,
numConfirms int32, amount float64) {
balance, err := lw.ConfirmedBalance(numConfirms)
if err != nil {
t.Fatalf("unable to query for balance: %v", err)
}
if balance.ToCoin() != amount {
t.Fatalf("wallet credits not properly loaded, should have %v DCR, "+
"instead have %v", amount, balance)
}
}
func assertReservationDeleted(res *lnwallet.ChannelReservation, t *testing.T) {
if err := res.Cancel(); err == nil {
t.Fatalf("reservation wasn't deleted from wallet")
}
}
// mineAndAssertTxInBlock asserts that a transaction is included within the next
// block mined.
func mineAndAssertTxInBlock(t *testing.T, miner *rpctest.Harness,
vw *rpctest.VotingWallet, txid chainhash.Hash) {
t.Helper()
// First, we'll wait for the transaction to arrive in the mempool.
if err := waitForMempoolTx(miner, &txid); err != nil {
t.Fatalf("unable to find %v in the mempool: %v", txid, err)
}
// We'll mined a block to confirm it.
blockHashes, err := vw.GenerateBlocks(1)
if err != nil {
t.Fatalf("unable to generate new block: %v", err)
}
// Finally, we'll check it was actually mined in this block.
block, err := miner.Node.GetBlock(blockHashes[0])
if err != nil {
t.Fatalf("unable to get block %v: %v", blockHashes[0], err)
}
if len(block.Transactions) != 2 {
t.Fatalf("expected 2 transactions in block, found %d",
len(block.Transactions))
}
txHash := block.Transactions[1].TxHash()
if txHash != txid {
t.Fatalf("expected transaction %v to be mined, found %v", txid,
txHash)
}
}
// newPkScript generates a new public key script of the given address type.
func newPkScript(t *testing.T, w *lnwallet.LightningWallet,
addrType lnwallet.AddressType) []byte {
t.Helper()
addr, err := w.NewAddress(addrType, false)
if err != nil {
t.Fatalf("unable to create new address: %v", err)
}
pkScript, err := txscript.PayToAddrScript(addr)
if err != nil {
t.Fatalf("unable to create output script: %v", err)
}
// Wait for the wallet's address manager to close (see dcrwallet#1372).
time.Sleep(time.Millisecond * 50)
return pkScript
}
// sendCoins is a helper function that encompasses all the things needed for two
// parties to send on-chain funds to each other.
func sendCoins(t *testing.T, miner *rpctest.Harness, vw *rpctest.VotingWallet,
sender, receiver *lnwallet.LightningWallet, output *wire.TxOut,
feeRate lnwallet.AtomPerKByte) *wire.MsgTx {
t.Helper()
tx, err := sender.SendOutputs([]*wire.TxOut{output}, feeRate)
if err != nil {
t.Fatalf("unable to send transaction: %v", err)
}
mineAndAssertTxInBlock(t, miner, vw, tx.TxHash())
if err := waitForWalletSync(miner, sender); err != nil {
t.Fatalf("unable to sync alice: %v", err)
}
if err := waitForWalletSync(miner, receiver); err != nil {
t.Fatalf("unable to sync bob: %v", err)
}
return tx
}
// assertTxInWallet asserts that a transaction exists in the wallet with the
// expected confirmation status.
func assertTxInWallet(t *testing.T, w *lnwallet.LightningWallet,
txHash chainhash.Hash, confirmed bool) {
t.Helper()
// If the backend is Neutrino, then we can't determine unconfirmed
// transactions since it's not aware of the mempool.
if !confirmed && w.BackEnd() == "neutrino" {
return
}
// We'll fetch all of our transaction and go through each one until
// finding the expected transaction with its expected confirmation
// status.
txs, err := w.ListTransactionDetails()
if err != nil {
t.Fatalf("unable to retrieve transactions: %v", err)
}
for _, tx := range txs {
if tx.Hash != txHash {
continue
}
if tx.NumConfirmations <= 0 && confirmed {
t.Fatalf("expected transaction %v to be confirmed",
txHash)
}
if tx.NumConfirmations > 0 && !confirmed {
t.Fatalf("expected transaction %v to be unconfirmed",
txHash)
}
// We've found the transaction and it matches the desired
// confirmation status, so we can exit.
return
}
t.Fatalf("transaction %v not found", txHash)
}
func loadTestCredits(miner *rpctest.Harness, w *lnwallet.LightningWallet,
blockGenerator func(uint32) ([]*chainhash.Hash, error),
numOutputs int, dcrPerOutput float64) error {
// Using the mining node, spend from a coinbase output numOutputs to
// give us dcrPerOutput with each output.
atomsPerOutput, err := dcrutil.NewAmount(dcrPerOutput)
if err != nil {
return fmt.Errorf("unable to create amt: %v", err)
}
expectedBalance, err := w.ConfirmedBalance(1)
if err != nil {
return err
}
expectedBalance += dcrutil.Amount(int64(atomsPerOutput) * int64(numOutputs))
addrs := make([]dcrutil.Address, numOutputs)
for i := 0; i < numOutputs; i++ {
// Grab a fresh address from the wallet to house this output.
addrs[i], err = w.NewAddress(lnwallet.PubKeyHash, false)
if err != nil {
return err
}
}
// Sleep for a bit to allow the wallet to unlock the mutexes of the address
// manager and underlying database. This is needed to prevent a possible
// deadlock condition in the wallet when generating new addresses while
// processing a transaction (see
// https://github.com/decred/dcrwallet/issues/1372). This isn't pretty,
// but 200ms should be more than enough to prevent triggering this bug
// on most dev machines.
time.Sleep(time.Millisecond * 200)
for _, walletAddr := range addrs {
script, err := txscript.PayToAddrScript(walletAddr)
if err != nil {
return err
}
output := &wire.TxOut{
Value: int64(atomsPerOutput),
PkScript: script,
Version: scriptVersion,
}
if _, err := miner.SendOutputs([]*wire.TxOut{output}, 1e5); err != nil {
return err
}
}
// TODO(roasbeef): shouldn't hardcode 10, use config param that dictates
// how many confs we wait before opening a channel.
// Generate 10 blocks with the mining node, this should mine all
// numOutputs transactions created above. We generate 10 blocks here
// in order to give all the outputs a "sufficient" number of confirmations.
if _, err := blockGenerator(10); err != nil {
return err
}
time.Sleep(time.Millisecond * 200)
// Wait until the wallet has finished syncing up to the main chain.
ticker := time.NewTicker(100 * time.Millisecond)
timeout := time.After(30 * time.Second)
for range ticker.C {
balance, err := w.ConfirmedBalance(1)
if err != nil {
return err
}
if balance == expectedBalance {
break
}
select {
case <-timeout:
synced, _, err := w.IsSynced()
if err != nil {
return err
}
return fmt.Errorf("timed out after 30 seconds "+
"waiting for balance %v, current balance %v, "+
"synced: %t", expectedBalance, balance, synced)
default:
}
}
ticker.Stop()
return nil
}
// createTestWallet creates a test LightningWallet will a total of 20DCR
// available for funding channels.
func createTestWallet(cdb *channeldb.DB, miningNode *rpctest.Harness,
netParams *chaincfg.Params, notifier chainntnfs.ChainNotifier,
wc lnwallet.WalletController, keyRing keychain.SecretKeyRing,
signer input.Signer, bio lnwallet.BlockChainIO,
vw *rpctest.VotingWallet) (*lnwallet.LightningWallet, error) {
cfg := lnwallet.Config{
Database: cdb,
Notifier: notifier,
SecretKeyRing: keyRing,
WalletController: wc,
Signer: signer,
ChainIO: bio,
FeeEstimator: lnwallet.NewStaticFeeEstimator(defaultFeeRate, 0),
DefaultConstraints: channeldb.ChannelConstraints{
DustLimit: 500,
MaxPendingAmount: lnwire.NewMAtomsFromAtoms(dcrutil.AtomsPerCoin) * 100,
ChanReserve: 100,
MinHTLC: 400,
MaxAcceptedHtlcs: 900,
},
NetParams: *netParams,
}
wallet, err := lnwallet.NewLightningWallet(cfg)
if err != nil {
return nil, err
}
if err := wallet.Startup(); err != nil {
return nil, err
}
return wallet, nil
}
func testDualFundingReservationWorkflow(miner *rpctest.Harness,
vw *rpctest.VotingWallet, alice, bob *lnwallet.LightningWallet,
t *testing.T) {
fundingAmount, err := dcrutil.NewAmount(5)
if err != nil {
t.Fatalf("unable to create amt: %v", err)
}
// In this scenario, we'll test a dual funder reservation, with each
// side putting in 10 DCR.
// Alice initiates a channel funded with 5 DCR for each side, so 10 DCR
// total. She also generates 2 DCR in change.
feePerKB, err := alice.Cfg.FeeEstimator.EstimateFeePerKB(1)
if err != nil {
t.Fatalf("unable to query fee estimator: %v", err)
}
aliceReq := &lnwallet.InitFundingReserveMsg{
ChainHash: chainHash,
NodeID: bobPub,
NodeAddr: bobAddr,
LocalFundingAmt: fundingAmount,
RemoteFundingAmt: fundingAmount,
CommitFeePerKB: feePerKB,
FundingFeePerKB: feePerKB,
PushMAtoms: 0,
Flags: lnwire.FFAnnounceChannel,
}
aliceChanReservation, err := alice.InitChannelReservation(aliceReq)
if err != nil {
t.Fatalf("unable to initialize funding reservation: %v", err)
}
aliceChanReservation.SetNumConfsRequired(numReqConfs)
channelConstraints := &channeldb.ChannelConstraints{
DustLimit: lnwallet.DefaultDustLimit(),
ChanReserve: fundingAmount / 100,
MaxPendingAmount: lnwire.NewMAtomsFromAtoms(fundingAmount),
MinHTLC: 1,
MaxAcceptedHtlcs: input.MaxHTLCNumber / 2,
CsvDelay: csvDelay,
}
err = aliceChanReservation.CommitConstraints(channelConstraints)
if err != nil {
t.Fatalf("unable to verify constraints: %v", err)
}
// The channel reservation should now be populated with a multi-sig key
// from our HD chain, a change output with 3 DCR, and 2 outputs
// selected of 4 DCR each. Additionally, the rest of the items needed
// to fulfill a funding contribution should also have been filled in.
aliceContribution := aliceChanReservation.OurContribution()
if len(aliceContribution.Inputs) < 1 {
t.Fatalf("outputs for funding tx not properly selected, have %v "+
"outputs should at least 1", len(aliceContribution.Inputs))
}
if len(aliceContribution.ChangeOutputs) != 1 {
t.Fatalf("coin selection failed, should have one change outputs, "+
"instead have: %v", len(aliceContribution.ChangeOutputs))
}
assertContributionInitPopulated(t, aliceContribution)
// Bob does the same, generating his own contribution. He then also
// receives' Alice's contribution, and consumes that so we can continue
// the funding process.
bobReq := &lnwallet.InitFundingReserveMsg{
ChainHash: chainHash,
NodeID: alicePub,
NodeAddr: aliceAddr,
LocalFundingAmt: fundingAmount,
RemoteFundingAmt: fundingAmount,
CommitFeePerKB: feePerKB,
FundingFeePerKB: feePerKB,
PushMAtoms: 0,
Flags: lnwire.FFAnnounceChannel,
}
bobChanReservation, err := bob.InitChannelReservation(bobReq)
if err != nil {
t.Fatalf("bob unable to init channel reservation: %v", err)
}
err = bobChanReservation.CommitConstraints(channelConstraints)
if err != nil {
t.Fatalf("unable to verify constraints: %v", err)
}
bobChanReservation.SetNumConfsRequired(numReqConfs)
assertContributionInitPopulated(t, bobChanReservation.OurContribution())
err = bobChanReservation.ProcessContribution(aliceContribution)
if err != nil {
t.Fatalf("bob unable to process alice's contribution: %v", err)
}
assertContributionInitPopulated(t, bobChanReservation.TheirContribution())
bobContribution := bobChanReservation.OurContribution()
// Bob then sends over his contribution, which will be consumed by
// Alice. After this phase, Alice should have all the necessary
// material required to craft the funding transaction and commitment
// transactions.
err = aliceChanReservation.ProcessContribution(bobContribution)
if err != nil {
t.Fatalf("alice unable to process bob's contribution: %v", err)
}
assertContributionInitPopulated(t, aliceChanReservation.TheirContribution())
// At this point, all Alice's signatures should be fully populated.
aliceFundingSigs, aliceCommitSig := aliceChanReservation.OurSignatures()
if aliceFundingSigs == nil {
t.Fatalf("alice's funding signatures not populated")
}
if aliceCommitSig == nil {
t.Fatalf("alice's commit signatures not populated")
}
// Additionally, Bob's signatures should also be fully populated.
bobFundingSigs, bobCommitSig := bobChanReservation.OurSignatures()
if bobFundingSigs == nil {
t.Fatalf("bob's funding signatures not populated")
}
if bobCommitSig == nil {
t.Fatalf("bob's commit signatures not populated")
}
// To conclude, we'll consume first Alice's signatures with Bob, and
// then the other way around.
_, err = aliceChanReservation.CompleteReservation(
bobFundingSigs, bobCommitSig,
)
if err != nil {
for _, in := range aliceChanReservation.FinalFundingTx().TxIn {
fmt.Println(in.PreviousOutPoint.String())
}
t.Fatalf("unable to consume alice's sigs: %v", err)
}
_, err = bobChanReservation.CompleteReservation(
aliceFundingSigs, aliceCommitSig,
)
if err != nil {
t.Fatalf("unable to consume bob's sigs: %v", err)
}
// At this point, the funding tx should have been populated.
fundingTx := aliceChanReservation.FinalFundingTx()
if fundingTx == nil {
t.Fatalf("funding transaction never created!")
}
// The resulting active channel state should have been persisted to the
// DB.
fundingSha := fundingTx.TxHash()
aliceChannels, err := alice.Cfg.Database.FetchOpenChannels(bobPub)
if err != nil {
t.Fatalf("unable to retrieve channel from DB: %v", err)
}
if !bytes.Equal(aliceChannels[0].FundingOutpoint.Hash[:], fundingSha[:]) {
t.Fatalf("channel state not properly saved")
}
if aliceChannels[0].ChanType != channeldb.DualFunder {
t.Fatalf("channel not detected as dual funder")
}
bobChannels, err := bob.Cfg.Database.FetchOpenChannels(alicePub)
if err != nil {
t.Fatalf("unable to retrieve channel from DB: %v", err)
}
if !bytes.Equal(bobChannels[0].FundingOutpoint.Hash[:], fundingSha[:]) {
t.Fatalf("channel state not properly saved")
}
if bobChannels[0].ChanType != channeldb.DualFunder {
t.Fatalf("channel not detected as dual funder")
}
// Let Alice publish the funding transaction.
if err := alice.PublishTransaction(fundingTx); err != nil {
t.Fatalf("unable to publish funding tx: %v", err)
}
// Mine a single block, the funding transaction should be included
// within this block.
err = waitForMempoolTx(miner, &fundingSha)
if err != nil {
t.Fatalf("tx not relayed to miner: %v", err)
}
blockHashes, err := vw.GenerateBlocks(1)
if err != nil {
t.Fatalf("unable to generate block: %v", err)
}
block, err := miner.Node.GetBlock(blockHashes[0])
if err != nil {
t.Fatalf("unable to find block: %v", err)
}
if len(block.Transactions) != 2 {
t.Fatalf("funding transaction wasn't mined: %v", err)
}
blockTx := block.Transactions[1]
if blockTx.TxHash() != fundingSha {
t.Fatalf("incorrect transaction was mined")
}
assertReservationDeleted(aliceChanReservation, t)
assertReservationDeleted(bobChanReservation, t)
// Wait for wallets to catch up to prevent issues in subsequent tests.
err = waitForWalletSync(miner, alice)
if err != nil {
t.Fatalf("unable to sync alice: %v", err)
}
err = waitForWalletSync(miner, bob)
if err != nil {
t.Fatalf("unable to sync bob: %v", err)
}
}
func testFundingTransactionLockedOutputs(miner *rpctest.Harness,
vw *rpctest.VotingWallet, alice, _ *lnwallet.LightningWallet,
t *testing.T) {
// Create a single channel asking for 16 DCR total.
fundingAmount := dcrutil.Amount(8 * 1e8)
feePerKB, err := alice.Cfg.FeeEstimator.EstimateFeePerKB(1)
if err != nil {
t.Fatalf("unable to query fee estimator: %v", err)
}
req := &lnwallet.InitFundingReserveMsg{
ChainHash: chainHash,
NodeID: bobPub,
NodeAddr: bobAddr,
LocalFundingAmt: fundingAmount,
RemoteFundingAmt: 0,
CommitFeePerKB: feePerKB,
FundingFeePerKB: feePerKB,
PushMAtoms: 0,
Flags: lnwire.FFAnnounceChannel,
}
if _, err := alice.InitChannelReservation(req); err != nil {
t.Fatalf("unable to initialize funding reservation 1: %v", err)
}
// Now attempt to reserve funds for another channel, this time
// requesting 900 DCR. We only have around 64DCR worth of outpoints
// that aren't locked, so this should fail.
amt, err := dcrutil.NewAmount(900)
if err != nil {
t.Fatalf("unable to create amt: %v", err)
}
failedReq := &lnwallet.InitFundingReserveMsg{
ChainHash: chainHash,
NodeID: bobPub,
NodeAddr: bobAddr,
LocalFundingAmt: amt,
RemoteFundingAmt: 0,
CommitFeePerKB: feePerKB,
FundingFeePerKB: feePerKB,
PushMAtoms: 0,
Flags: lnwire.FFAnnounceChannel,
}
failedReservation, err := alice.InitChannelReservation(failedReq)
if err == nil {
t.Fatalf("not error returned, should fail on coin selection")
}
if _, ok := err.(*lnwallet.ErrInsufficientFunds); !ok {
t.Fatalf("error not coinselect error: %v", err)
}
if failedReservation != nil {
t.Fatalf("reservation should be nil")
}
}
func testFundingCancellationNotEnoughFunds(miner *rpctest.Harness,
vw *rpctest.VotingWallet, alice, _ *lnwallet.LightningWallet,
t *testing.T) {
feePerKB, err := alice.Cfg.FeeEstimator.EstimateFeePerKB(1)
if err != nil {
t.Fatalf("unable to query fee estimator: %v", err)
}
totalBalance, err := alice.ConfirmedBalance(0)
if err != nil {
t.Fatalf("unable to fetch confirmed balance: %v", err)
}
// Create a reservation for almost the entire wallet amount.
fundingAmount := totalBalance - dcrutil.AtomsPerCoin
req := &lnwallet.InitFundingReserveMsg{
ChainHash: chainHash,
NodeID: bobPub,
NodeAddr: bobAddr,
LocalFundingAmt: fundingAmount,
RemoteFundingAmt: 0,
CommitFeePerKB: feePerKB,
FundingFeePerKB: feePerKB,
PushMAtoms: 0,
Flags: lnwire.FFAnnounceChannel,
}
chanReservation, err := alice.InitChannelReservation(req)
if err != nil {
t.Fatalf("unable to initialize funding reservation: %v", err)
}
// Attempt to create another channel spending the same amount. This
// should fail.
_, err = alice.InitChannelReservation(req)
if _, ok := err.(*lnwallet.ErrInsufficientFunds); !ok {
t.Fatalf("coin selection succeeded should have insufficient funds: %v",
err)
}
// Now cancel that old reservation.
if err := chanReservation.Cancel(); err != nil {
t.Fatalf("unable to cancel reservation: %v", err)
}
// Those outpoints should no longer be locked.
lockedOutPoints := alice.LockedOutpoints()
if len(lockedOutPoints) != 0 {
t.Fatalf("outpoints still locked")
}
// Reservation ID should no longer be tracked.
numReservations := alice.ActiveReservations()
if len(alice.ActiveReservations()) != 0 {
t.Fatalf("should have 0 reservations, instead have %v",
numReservations)
}
// TODO(roasbeef): create method like Balance that ignores locked
// outpoints, will let us fail early/fast instead of querying and
// attempting coin selection.
// Request to fund a new channel should now succeed.
if _, err := alice.InitChannelReservation(req); err != nil {
t.Fatalf("unable to initialize funding reservation: %v", err)
}
}
func testCancelNonExistentReservation(miner *rpctest.Harness,
vw *rpctest.VotingWallet, alice, _ *lnwallet.LightningWallet,
t *testing.T) {
feePerKB, err := alice.Cfg.FeeEstimator.EstimateFeePerKB(1)
if err != nil {
t.Fatalf("unable to query fee estimator: %v", err)
}
// Create our own reservation, give it some ID.
res, err := lnwallet.NewChannelReservation(
20000, 20000, feePerKB, alice, 22, 10, &testHdSeed,
lnwire.FFAnnounceChannel, true,
)
if err != nil {
t.Fatalf("unable to create res: %v", err)
}
// Attempt to cancel this reservation. This should fail, we know
// nothing of it.
if err := res.Cancel(); err == nil {
t.Fatalf("canceled non-existent reservation")
}
}
func testReservationInitiatorBalanceBelowDustCancel(miner *rpctest.Harness,
vw *rpctest.VotingWallet, alice, _ *lnwallet.LightningWallet,
t *testing.T) {
// We'll attempt to create a new reservation with an extremely high
// commitment fee rate. This should push our balance into the negative
// and result in a failure to create the reservation.
const numDCR = 4
fundingAmount, err := dcrutil.NewAmount(numDCR)
if err != nil {
t.Fatalf("unable to create amt: %v", err)
}
FeePerKB := lnwallet.AtomPerKByte(
numDCR * numDCR * dcrutil.AtomsPerCoin,
)
req := &lnwallet.InitFundingReserveMsg{
ChainHash: chainHash,
NodeID: bobPub,
NodeAddr: bobAddr,
LocalFundingAmt: fundingAmount,
RemoteFundingAmt: 0,
CommitFeePerKB: FeePerKB,
FundingFeePerKB: 1000,
PushMAtoms: 0,
Flags: lnwire.FFAnnounceChannel,
Tweakless: true,
}
_, err = alice.InitChannelReservation(req)
switch {
case err == nil:
t.Fatalf("initialization should have failed due to " +
"insufficient local amount")
case !strings.Contains(err.Error(), "funder balance too small"):
t.Fatalf("incorrect error: %v", err)
}
}
func assertContributionInitPopulated(t *testing.T, c *lnwallet.ChannelContribution) {
_, _, line, _ := runtime.Caller(1)
if c.FirstCommitmentPoint == nil {
t.Fatalf("line #%v: commitment point not fond", line)
}
if c.CsvDelay == 0 {
t.Fatalf("line #%v: csv delay not set", line)
}
if c.MultiSigKey.PubKey == nil {
t.Fatalf("line #%v: multi-sig key not set", line)
}
if c.RevocationBasePoint.PubKey == nil {
t.Fatalf("line #%v: revocation key not set", line)
}
if c.PaymentBasePoint.PubKey == nil {
t.Fatalf("line #%v: payment key not set", line)
}
if c.DelayBasePoint.PubKey == nil {
t.Fatalf("line #%v: delay key not set", line)
}
if c.DustLimit == 0 {
t.Fatalf("line #%v: dust limit not set", line)
}
if c.MaxPendingAmount == 0 {
t.Fatalf("line #%v: max pending amt not set", line)
}
if c.ChanReserve == 0 {
t.Fatalf("line #%v: chan reserve not set", line)
}
if c.MinHTLC == 0 {
t.Fatalf("line #%v: min htlc not set", line)
}
if c.MaxAcceptedHtlcs == 0 {
t.Fatalf("line #%v: max accepted htlc's not set", line)
}
}
func testSingleFunderReservationWorkflow(miner *rpctest.Harness,
vw *rpctest.VotingWallet, alice, bob *lnwallet.LightningWallet,
t *testing.T, tweakless bool) {
// For this scenario, Alice will be the channel initiator while bob
// will act as the responder to the workflow.
// First, Alice will Initialize a reservation for a channel with 4 DCR
// funded solely by us. We'll also initially push 1 DCR of the channel
// towards Bob's side.
fundingAmt, err := dcrutil.NewAmount(4)
if err != nil {
t.Fatalf("unable to create amt: %v", err)
}
pushAmt := lnwire.NewMAtomsFromAtoms(dcrutil.AtomsPerCoin)
feePerKB, err := alice.Cfg.FeeEstimator.EstimateFeePerKB(1)
if err != nil {
t.Fatalf("unable to query fee estimator: %v", err)
}
aliceReq := &lnwallet.InitFundingReserveMsg{
ChainHash: chainHash,
NodeID: bobPub,
NodeAddr: bobAddr,
LocalFundingAmt: fundingAmt,
RemoteFundingAmt: 0,
CommitFeePerKB: feePerKB,
FundingFeePerKB: feePerKB,
PushMAtoms: pushAmt,
Flags: lnwire.FFAnnounceChannel,
Tweakless: tweakless,
}
aliceChanReservation, err := alice.InitChannelReservation(aliceReq)
if err != nil {
t.Fatalf("unable to init channel reservation: %v", err)
}
aliceChanReservation.SetNumConfsRequired(numReqConfs)
channelConstraints := &channeldb.ChannelConstraints{
DustLimit: lnwallet.DefaultDustLimit(),
ChanReserve: fundingAmt / 100,
MaxPendingAmount: lnwire.NewMAtomsFromAtoms(fundingAmt),
MinHTLC: 1,
MaxAcceptedHtlcs: input.MaxHTLCNumber / 2,
CsvDelay: csvDelay,
}
err = aliceChanReservation.CommitConstraints(channelConstraints)
if err != nil {
t.Fatalf("unable to verify constraints: %v", err)
}
// Verify all contribution fields have been set properly.
aliceContribution := aliceChanReservation.OurContribution()
if len(aliceContribution.Inputs) < 1 {
t.Fatalf("outputs for funding tx not properly selected, have %v "+
"outputs should at least 1", len(aliceContribution.Inputs))
}
if len(aliceContribution.ChangeOutputs) != 1 {
t.Fatalf("coin selection failed, should have one change outputs, "+
"instead have: %v", len(aliceContribution.ChangeOutputs))
}
assertContributionInitPopulated(t, aliceContribution)
// Next, Bob receives the initial request, generates a corresponding
// reservation initiation, then consume Alice's contribution.
bobReq := &lnwallet.InitFundingReserveMsg{
ChainHash: chainHash,
NodeID: alicePub,
NodeAddr: aliceAddr,
LocalFundingAmt: 0,
RemoteFundingAmt: fundingAmt,
CommitFeePerKB: feePerKB,
FundingFeePerKB: feePerKB,
PushMAtoms: pushAmt,
Flags: lnwire.FFAnnounceChannel,
Tweakless: tweakless,
}
bobChanReservation, err := bob.InitChannelReservation(bobReq)
if err != nil {
t.Fatalf("unable to create bob reservation: %v", err)
}
err = bobChanReservation.CommitConstraints(channelConstraints)
if err != nil {
t.Fatalf("unable to verify constraints: %v", err)
}
bobChanReservation.SetNumConfsRequired(numReqConfs)
// We'll ensure that Bob's contribution also gets generated properly.
bobContribution := bobChanReservation.OurContribution()
assertContributionInitPopulated(t, bobContribution)
// With his contribution generated, he can now process Alice's
// contribution.
err = bobChanReservation.ProcessSingleContribution(aliceContribution)
if err != nil {
t.Fatalf("bob unable to process alice's contribution: %v", err)
}
assertContributionInitPopulated(t, bobChanReservation.TheirContribution())
// Bob will next send over his contribution to Alice, we simulate this
// by having Alice immediately process his contribution.
err = aliceChanReservation.ProcessContribution(bobContribution)
if err != nil {
t.Fatalf("alice unable to process bob's contribution: %v", err)
}
assertContributionInitPopulated(t, bobChanReservation.TheirContribution())
// At this point, Alice should have generated all the signatures
// required for the funding transaction, as well as Alice's commitment
// signature to bob.
aliceRemoteContribution := aliceChanReservation.TheirContribution()
aliceFundingSigs, aliceCommitSig := aliceChanReservation.OurSignatures()
if aliceFundingSigs == nil {
t.Fatalf("funding sigs not found")
}
if aliceCommitSig == nil {
t.Fatalf("commitment sig not found")
}
// Additionally, the funding tx and the funding outpoint should have
// been populated.
if aliceChanReservation.FinalFundingTx() == nil {
t.Fatalf("funding transaction never created!")
}
if aliceChanReservation.FundingOutpoint() == nil {
t.Fatalf("funding outpoint never created!")
}
// Their funds should also be filled in.
if len(aliceRemoteContribution.Inputs) != 0 {
t.Fatalf("bob shouldn't have any inputs, instead has %v",
len(aliceRemoteContribution.Inputs))
}
if len(aliceRemoteContribution.ChangeOutputs) != 0 {
t.Fatalf("bob shouldn't have any change outputs, instead "+
"has %v",
aliceRemoteContribution.ChangeOutputs[0].Value)
}
// Next, Alice will send over her signature for Bob's commitment
// transaction, as well as the funding outpoint.
fundingPoint := aliceChanReservation.FundingOutpoint()
_, err = bobChanReservation.CompleteReservationSingle(
fundingPoint, aliceCommitSig,
)
if err != nil {
t.Fatalf("bob unable to consume single reservation: %v", err)
}
// Finally, we'll conclude the reservation process by sending over
// Bob's commitment signature, which is the final thing Alice needs to
// be able to safely broadcast the funding transaction.
_, bobCommitSig := bobChanReservation.OurSignatures()
if bobCommitSig == nil {
t.Fatalf("bob failed to generate commitment signature: %v", err)
}
_, err = aliceChanReservation.CompleteReservation(
nil, bobCommitSig,
)
if err != nil {
t.Fatalf("alice unable to complete reservation: %v", err)
}
// The resulting active channel state should have been persisted to the
// DB for both Alice and Bob.
fundingTx := aliceChanReservation.FinalFundingTx()
fundingSha := fundingTx.TxHash()
aliceChannels, err := alice.Cfg.Database.FetchOpenChannels(bobPub)
if err != nil {
t.Fatalf("unable to retrieve channel from DB: %v", err)
}
if len(aliceChannels) != 1 {
t.Fatalf("alice didn't save channel state: %v", err)
}
if !bytes.Equal(aliceChannels[0].FundingOutpoint.Hash[:], fundingSha[:]) {
t.Fatalf("channel state not properly saved: %v vs %v",
hex.EncodeToString(aliceChannels[0].FundingOutpoint.Hash[:]),
hex.EncodeToString(fundingSha[:]))
}
if !aliceChannels[0].IsInitiator {
t.Fatalf("alice not detected as channel initiator")
}
if !aliceChannels[0].ChanType.IsSingleFunder() {
t.Fatalf("channel type is incorrect, expected %v instead got %v",
channeldb.SingleFunder, aliceChannels[0].ChanType)
}