-
Notifications
You must be signed in to change notification settings - Fork 100
/
Copy pathassets_test.go
2211 lines (1800 loc) · 60.8 KB
/
assets_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 (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"os"
"testing"
"time"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/schnorr"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew"
tapfn "github.com/lightninglabs/taproot-assets/fn"
"github.com/lightninglabs/taproot-assets/itest"
"github.com/lightninglabs/taproot-assets/proof"
"github.com/lightninglabs/taproot-assets/rfq"
"github.com/lightninglabs/taproot-assets/rfqmath"
"github.com/lightninglabs/taproot-assets/rfqmsg"
"github.com/lightninglabs/taproot-assets/tapfreighter"
"github.com/lightninglabs/taproot-assets/taprpc"
"github.com/lightninglabs/taproot-assets/taprpc/assetwalletrpc"
"github.com/lightninglabs/taproot-assets/taprpc/mintrpc"
"github.com/lightninglabs/taproot-assets/taprpc/rfqrpc"
tchrpc "github.com/lightninglabs/taproot-assets/taprpc/tapchannelrpc"
"github.com/lightninglabs/taproot-assets/taprpc/tapdevrpc"
"github.com/lightninglabs/taproot-assets/taprpc/universerpc"
"github.com/lightninglabs/taproot-assets/tapscript"
"github.com/lightningnetwork/lnd/fn"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/lightningnetwork/lnd/lnrpc/invoicesrpc"
"github.com/lightningnetwork/lnd/lnrpc/routerrpc"
"github.com/lightningnetwork/lnd/lntest/rpc"
"github.com/lightningnetwork/lnd/lntest/wait"
"github.com/lightningnetwork/lnd/lntypes"
"github.com/lightningnetwork/lnd/lnwire"
"github.com/lightningnetwork/lnd/macaroons"
"github.com/lightningnetwork/lnd/record"
"github.com/stretchr/testify/require"
"golang.org/x/exp/maps"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"gopkg.in/macaroon.v2"
)
// PaymentTimeout is the default payment timeout we use in our tests.
const (
PaymentTimeout = 12 * time.Second
DefaultPushSat int64 = 1062
)
// nolint: lll
var (
failureNoBalance = lnrpc.PaymentFailureReason_FAILURE_REASON_INSUFFICIENT_BALANCE
failureNoRoute = lnrpc.PaymentFailureReason_FAILURE_REASON_NO_ROUTE
failureIncorrectDetails = lnrpc.PaymentFailureReason_FAILURE_REASON_INCORRECT_PAYMENT_DETAILS
failureTimeout = lnrpc.PaymentFailureReason_FAILURE_REASON_TIMEOUT
failureNone = lnrpc.PaymentFailureReason_FAILURE_REASON_NONE
)
// createTestAssetNetwork sends asset funds from Charlie to Dave and Erin, so
// they can fund asset channels with Yara and Fabia, respectively. So the asset
// channels created are Charlie->Dave, Dave->Yara, Erin->Fabia. The channels
// are then confirmed and balances asserted.
func createTestAssetNetwork(t *harnessTest, net *NetworkHarness, charlieTap,
daveTap, erinTap, fabiaTap, yaraTap, universeTap *tapClient,
mintedAsset *taprpc.Asset, assetSendAmount, charlieFundingAmount,
daveFundingAmount,
erinFundingAmount uint64, pushSat int64) (*lnrpc.ChannelPoint,
*lnrpc.ChannelPoint, *lnrpc.ChannelPoint) {
ctxb := context.Background()
assetID := mintedAsset.AssetGenesis.AssetId
var groupKey []byte
if mintedAsset.AssetGroup != nil {
groupKey = mintedAsset.AssetGroup.TweakedGroupKey
}
fundingScriptTree := tapscript.NewChannelFundingScriptTree()
fundingScriptKey := fundingScriptTree.TaprootKey
fundingScriptTreeBytes := fundingScriptKey.SerializeCompressed()
// We need to send some assets to Dave, so he can fund an asset channel
// with Yara.
daveAddr, err := daveTap.NewAddr(ctxb, &taprpc.NewAddrRequest{
Amt: assetSendAmount,
AssetId: assetID,
ProofCourierAddr: fmt.Sprintf(
"%s://%s", proof.UniverseRpcCourierType,
charlieTap.node.Cfg.LitAddr(),
),
})
require.NoError(t.t, err)
t.Logf("Sending %v asset units to Dave...", assetSendAmount)
// Send the assets to Dave.
itest.AssertAddrCreated(t.t, daveTap, mintedAsset, daveAddr)
sendResp, err := charlieTap.SendAsset(ctxb, &taprpc.SendAssetRequest{
TapAddrs: []string{daveAddr.Encoded},
})
require.NoError(t.t, err)
itest.ConfirmAndAssertOutboundTransfer(
t.t, t.lndHarness.Miner.Client, charlieTap, sendResp, assetID,
[]uint64{mintedAsset.Amount - assetSendAmount, assetSendAmount},
0, 1,
)
itest.AssertNonInteractiveRecvComplete(t.t, daveTap, 1)
// We need to send some assets to Erin, so he can fund an asset channel
// with Fabia.
erinAddr, err := erinTap.NewAddr(ctxb, &taprpc.NewAddrRequest{
Amt: assetSendAmount,
AssetId: assetID,
ProofCourierAddr: fmt.Sprintf(
"%s://%s", proof.UniverseRpcCourierType,
charlieTap.node.Cfg.LitAddr(),
),
})
require.NoError(t.t, err)
t.Logf("Sending %v asset units to Erin...", assetSendAmount)
// Send the assets to Erin.
itest.AssertAddrCreated(t.t, erinTap, mintedAsset, erinAddr)
sendResp, err = charlieTap.SendAsset(ctxb, &taprpc.SendAssetRequest{
TapAddrs: []string{erinAddr.Encoded},
})
require.NoError(t.t, err)
itest.ConfirmAndAssertOutboundTransfer(
t.t, t.lndHarness.Miner.Client, charlieTap, sendResp, assetID,
[]uint64{
mintedAsset.Amount - 2*assetSendAmount, assetSendAmount,
}, 1, 2,
)
itest.AssertNonInteractiveRecvComplete(t.t, erinTap, 1)
t.Logf("Opening asset channels...")
// The first channel we create has a push amount, so Charlie can receive
// payments immediately and not run into the channel reserve issue.
fundRespCD, err := charlieTap.FundChannel(
ctxb, &tchrpc.FundChannelRequest{
AssetAmount: charlieFundingAmount,
AssetId: assetID,
PeerPubkey: daveTap.node.PubKey[:],
FeeRateSatPerVbyte: 5,
PushSat: pushSat,
},
)
require.NoError(t.t, err)
t.Logf("Funded channel between Charlie and Dave: %v", fundRespCD)
fundRespDY, err := daveTap.FundChannel(
ctxb, &tchrpc.FundChannelRequest{
AssetAmount: daveFundingAmount,
AssetId: assetID,
PeerPubkey: yaraTap.node.PubKey[:],
FeeRateSatPerVbyte: 5,
},
)
require.NoError(t.t, err)
t.Logf("Funded channel between Dave and Yara: %v", fundRespDY)
fundRespEF, err := erinTap.FundChannel(
ctxb, &tchrpc.FundChannelRequest{
AssetAmount: erinFundingAmount,
AssetId: assetID,
PeerPubkey: fabiaTap.node.PubKey[:],
FeeRateSatPerVbyte: 5,
PushSat: pushSat,
},
)
require.NoError(t.t, err)
t.Logf("Funded channel between Erin and Fabia: %v", fundRespEF)
// Make sure the pending channel shows up in the list and has the
// custom records set as JSON.
assertPendingChannels(
t.t, charlieTap.node, mintedAsset, 1, charlieFundingAmount, 0,
)
assertPendingChannels(
t.t, daveTap.node, mintedAsset, 2, daveFundingAmount,
charlieFundingAmount,
)
assertPendingChannels(
t.t, erinTap.node, mintedAsset, 1, erinFundingAmount, 0,
)
// Now that we've looked at the pending channels, let's actually confirm
// all three of them.
mineBlocks(t, net, 6, 3)
// We'll be tracking the expected asset balances throughout the test, so
// we can assert it after each action.
charlieAssetBalance := mintedAsset.Amount - 2*assetSendAmount -
charlieFundingAmount
daveAssetBalance := assetSendAmount - daveFundingAmount
erinAssetBalance := assetSendAmount - erinFundingAmount
// After opening the channels, the asset balance of the funding nodes
// should have been decreased with the funding amount. The asset with
// the funding output was imported into the asset DB but are kept out of
// the balance reporting by tapd.
assertAssetBalance(t.t, charlieTap, assetID, charlieAssetBalance)
assertAssetBalance(t.t, daveTap, assetID, daveAssetBalance)
assertAssetBalance(t.t, erinTap, assetID, erinAssetBalance)
// There should only be a single asset piece for Charlie, the one in the
// channel.
assertNumAssetOutputs(t.t, charlieTap, assetID, 1)
assertAssetExists(
t.t, charlieTap, assetID, charlieFundingAmount,
fundingScriptKey, false, true, true,
)
// Dave should just have one asset piece, since we used the full amount
// for the channel opening.
assertNumAssetOutputs(t.t, daveTap, assetID, 1)
assertAssetExists(
t.t, daveTap, assetID, daveFundingAmount, fundingScriptKey,
false, true, true,
)
// Erin should just have two equally sized asset pieces, the change and
// the funding transaction.
assertNumAssetOutputs(t.t, erinTap, assetID, 2)
assertAssetExists(
t.t, erinTap, assetID, assetSendAmount-erinFundingAmount, nil,
true, false, false,
)
assertAssetExists(
t.t, erinTap, assetID, erinFundingAmount, fundingScriptKey,
false, true, true,
)
// Assert that the proofs for both channels has been uploaded to the
// designated Universe server.
assertUniverseProofExists(
t.t, universeTap, assetID, groupKey, fundingScriptTreeBytes,
fmt.Sprintf("%v:%v", fundRespCD.Txid, fundRespCD.OutputIndex),
)
assertUniverseProofExists(
t.t, universeTap, assetID, groupKey, fundingScriptTreeBytes,
fmt.Sprintf("%v:%v", fundRespDY.Txid, fundRespDY.OutputIndex),
)
assertUniverseProofExists(
t.t, universeTap, assetID, groupKey, fundingScriptTreeBytes,
fmt.Sprintf("%v:%v", fundRespEF.Txid, fundRespEF.OutputIndex),
)
// Make sure the channel shows the correct asset information.
assertAssetChan(
t.t, charlieTap.node, daveTap.node, charlieFundingAmount,
mintedAsset,
)
assertAssetChan(
t.t, daveTap.node, yaraTap.node, daveFundingAmount, mintedAsset,
)
assertAssetChan(
t.t, erinTap.node, fabiaTap.node, erinFundingAmount,
mintedAsset,
)
chanPointCD := &lnrpc.ChannelPoint{
OutputIndex: uint32(fundRespCD.OutputIndex),
FundingTxid: &lnrpc.ChannelPoint_FundingTxidStr{
FundingTxidStr: fundRespCD.Txid,
},
}
chanPointDY := &lnrpc.ChannelPoint{
OutputIndex: uint32(fundRespDY.OutputIndex),
FundingTxid: &lnrpc.ChannelPoint_FundingTxidStr{
FundingTxidStr: fundRespDY.Txid,
},
}
chanPointEF := &lnrpc.ChannelPoint{
OutputIndex: uint32(fundRespEF.OutputIndex),
FundingTxid: &lnrpc.ChannelPoint_FundingTxidStr{
FundingTxidStr: fundRespEF.Txid,
},
}
return chanPointCD, chanPointDY, chanPointEF
}
func assertNumAssetUTXOs(t *testing.T, tapdClient *tapClient,
numUTXOs int) *taprpc.ListUtxosResponse {
ctxb := context.Background()
var clientUTXOs *taprpc.ListUtxosResponse
err := wait.NoError(func() error {
var err error
clientUTXOs, err = tapdClient.ListUtxos(
ctxb, &taprpc.ListUtxosRequest{},
)
if err != nil {
return err
}
if len(clientUTXOs.ManagedUtxos) != numUTXOs {
return fmt.Errorf("expected %v UTXO, got %d", numUTXOs,
len(clientUTXOs.ManagedUtxos))
}
return nil
}, defaultTimeout)
require.NoErrorf(t, err, "failed to assert UTXOs: %v, last state: %v",
err, clientUTXOs)
return clientUTXOs
}
func locateAssetTransfers(t *testing.T, tapdClient *tapClient,
txid chainhash.Hash) *taprpc.AssetTransfer {
var transfer *taprpc.AssetTransfer
err := wait.NoError(func() error {
ctxb := context.Background()
forceCloseTransfer, err := tapdClient.ListTransfers(
ctxb, &taprpc.ListTransfersRequest{
AnchorTxid: txid.String(),
},
)
if err != nil {
return fmt.Errorf("unable to list %v transfers: %w",
tapdClient.node.Name(), err)
}
if len(forceCloseTransfer.Transfers) != 1 {
return fmt.Errorf("%v is missing force close "+
"transfer", tapdClient.node.Name())
}
transfer = forceCloseTransfer.Transfers[0]
if transfer.AnchorTxBlockHash == nil {
return fmt.Errorf("missing anchor block hash, " +
"transfer not confirmed")
}
return nil
}, defaultTimeout)
require.NoError(t, err)
return transfer
}
func connectAllNodes(t *testing.T, net *NetworkHarness, nodes []*HarnessNode) {
for i, node := range nodes {
for j := i + 1; j < len(nodes); j++ {
peer := nodes[j]
net.ConnectNodesPerm(t, node, peer)
}
}
}
func fundAllNodes(t *testing.T, net *NetworkHarness, nodes []*HarnessNode) {
for _, node := range nodes {
net.SendCoins(t, btcutil.SatoshiPerBitcoin, node)
}
}
func syncUniverses(t *testing.T, universe *tapClient, nodes ...*HarnessNode) {
ctxb := context.Background()
ctxt, cancel := context.WithTimeout(ctxb, defaultTimeout)
defer cancel()
for _, node := range nodes {
nodeTapClient := newTapClient(t, node)
universeHostAddr := universe.node.Cfg.LitAddr()
t.Logf("Syncing node %v with universe %v", node.Cfg.Name,
universeHostAddr)
itest.SyncUniverses(
ctxt, t, nodeTapClient, universe, universeHostAddr,
defaultTimeout,
)
}
}
func assertUniverseProofExists(t *testing.T, universe *tapClient,
assetID, groupKey, scriptKey []byte, outpoint string) *taprpc.Asset {
t.Logf("Asserting proof outpoint=%v, script_key=%x", outpoint,
scriptKey)
req := &universerpc.UniverseKey{
Id: &universerpc.ID{
ProofType: universerpc.ProofType_PROOF_TYPE_TRANSFER,
},
LeafKey: &universerpc.AssetKey{
Outpoint: &universerpc.AssetKey_OpStr{
OpStr: outpoint,
},
ScriptKey: &universerpc.AssetKey_ScriptKeyBytes{
ScriptKeyBytes: scriptKey,
},
},
}
switch {
case len(groupKey) > 0:
req.Id.Id = &universerpc.ID_GroupKey{
GroupKey: groupKey,
}
case len(assetID) > 0:
req.Id.Id = &universerpc.ID_AssetId{
AssetId: assetID,
}
default:
t.Fatalf("Need either asset ID or group key")
}
ctxb := context.Background()
var proofResp *universerpc.AssetProofResponse
err := wait.NoError(func() error {
var pErr error
proofResp, pErr = universe.QueryProof(ctxb, req)
return pErr
}, defaultTimeout)
require.NoError(
t, err, "%v: outpoint=%v, script_key=%x", err, outpoint,
scriptKey,
)
if len(groupKey) > 0 {
require.NotNil(t, proofResp.AssetLeaf.Asset.AssetGroup)
require.Equal(
t, proofResp.AssetLeaf.Asset.AssetGroup.TweakedGroupKey,
groupKey,
)
} else {
require.Equal(
t, proofResp.AssetLeaf.Asset.AssetGenesis.AssetId,
assetID,
)
}
a := proofResp.AssetLeaf.Asset
t.Logf("Proof found for scriptKey=%x, amount=%d", a.ScriptKey, a.Amount)
return a
}
func assertPendingChannels(t *testing.T, node *HarnessNode,
mintedAsset *taprpc.Asset, numChannels int, localSum,
remoteSum uint64) {
ctxb := context.Background()
ctxt, cancel := context.WithTimeout(ctxb, defaultTimeout)
defer cancel()
pendingChannelsResp, err := node.PendingChannels(
ctxt, &lnrpc.PendingChannelsRequest{},
)
require.NoError(t, err)
require.Len(t, pendingChannelsResp.PendingOpenChannels, numChannels)
pendingChan := pendingChannelsResp.PendingOpenChannels[0]
var pendingJSON rfqmsg.JsonAssetChannel
err = json.Unmarshal(
pendingChan.Channel.CustomChannelData, &pendingJSON,
)
require.NoError(t, err)
require.Len(t, pendingJSON.Assets, 1)
require.NotZero(t, pendingJSON.Assets[0].Capacity)
// Check the decimal display of the channel funding blob. If no explicit
// value was set, we assume and expect the value of 0.
var expectedDecimalDisplay uint8
if mintedAsset.DecimalDisplay != nil {
expectedDecimalDisplay = uint8(
mintedAsset.DecimalDisplay.DecimalDisplay,
)
}
require.Equal(
t, expectedDecimalDisplay,
pendingJSON.Assets[0].AssetInfo.DecimalDisplay,
)
// Check the balance of the pending channel.
assetID := mintedAsset.AssetGenesis.AssetId
pendingLocalBalance, pendingRemoteBalance, _, _ :=
getAssetChannelBalance(
t, node, assetID, true,
)
require.EqualValues(t, localSum, pendingLocalBalance)
require.EqualValues(t, remoteSum, pendingRemoteBalance)
}
func assertAssetChan(t *testing.T, src, dst *HarnessNode, fundingAmount uint64,
mintedAsset *taprpc.Asset) {
assetID := mintedAsset.AssetGenesis.AssetId
assetIDStr := hex.EncodeToString(assetID)
err := wait.NoError(func() error {
a, err := getChannelCustomData(src, dst)
if err != nil {
return err
}
if a.AssetInfo.AssetGenesis.AssetID != assetIDStr {
return fmt.Errorf("expected asset ID %s, got %s",
assetIDStr, a.AssetInfo.AssetGenesis.AssetID)
}
if a.Capacity != fundingAmount {
return fmt.Errorf("expected capacity %d, got %d",
fundingAmount, a.Capacity)
}
// Check the decimal display of the channel funding blob. If no
// explicit value was set, we assume and expect the value of 0.
var expectedDecimalDisplay uint8
if mintedAsset.DecimalDisplay != nil {
expectedDecimalDisplay = uint8(
mintedAsset.DecimalDisplay.DecimalDisplay,
)
}
if a.AssetInfo.DecimalDisplay != expectedDecimalDisplay {
return fmt.Errorf("expected decimal display %d, got %d",
expectedDecimalDisplay,
a.AssetInfo.DecimalDisplay)
}
return nil
}, defaultTimeout)
require.NoError(t, err)
}
func assertChannelKnown(t *testing.T, node *HarnessNode,
chanPoint *lnrpc.ChannelPoint) {
ctxb := context.Background()
ctxt, cancel := context.WithTimeout(ctxb, defaultTimeout)
defer cancel()
txid, err := chainhash.NewHash(chanPoint.GetFundingTxidBytes())
require.NoError(t, err)
targetChanPoint := fmt.Sprintf(
"%v:%d", txid.String(), chanPoint.OutputIndex,
)
err = wait.NoError(func() error {
graphResp, err := node.DescribeGraph(
ctxt, &lnrpc.ChannelGraphRequest{},
)
if err != nil {
return err
}
found := false
for _, edge := range graphResp.Edges {
if edge.ChanPoint == targetChanPoint {
found = true
break
}
}
if !found {
return fmt.Errorf("channel %v not found",
targetChanPoint)
}
return nil
}, defaultTimeout)
require.NoError(t, err)
}
func getChannelCustomData(src, dst *HarnessNode) (*rfqmsg.JsonAssetChanInfo,
error) {
ctxb := context.Background()
ctxt, cancel := context.WithTimeout(ctxb, defaultTimeout)
defer cancel()
srcDestChannels, err := src.ListChannels(
ctxt, &lnrpc.ListChannelsRequest{
Peer: dst.PubKey[:],
},
)
if err != nil {
return nil, err
}
assetChannels := fn.Filter(func(c *lnrpc.Channel) bool {
return len(c.CustomChannelData) > 0
}, srcDestChannels.Channels)
if len(assetChannels) != 1 {
return nil, fmt.Errorf("expected 1 asset channel, got %d: %v",
len(assetChannels), spew.Sdump(assetChannels))
}
targetChan := assetChannels[0]
var assetData rfqmsg.JsonAssetChannel
err = json.Unmarshal(targetChan.CustomChannelData, &assetData)
if err != nil {
return nil, fmt.Errorf("unable to unmarshal asset data: %w",
err)
}
if len(assetData.Assets) != 1 {
return nil, fmt.Errorf("expected 1 asset, got %d",
len(assetData.Assets))
}
return &assetData.Assets[0], nil
}
func getAssetChannelBalance(t *testing.T, node *HarnessNode, assetID []byte,
pending bool) (uint64, uint64, uint64, uint64) {
ctxb := context.Background()
ctxt, cancel := context.WithTimeout(ctxb, defaultTimeout)
defer cancel()
balance, err := node.ChannelBalance(
ctxt, &lnrpc.ChannelBalanceRequest{},
)
require.NoError(t, err)
var assetBalance rfqmsg.JsonAssetChannelBalances
err = json.Unmarshal(balance.CustomChannelData, &assetBalance)
require.NoError(t, err)
balances := assetBalance.OpenChannels
if pending {
balances = assetBalance.PendingChannels
}
var localSum, remoteSum uint64
for assetIDString := range balances {
if assetIDString != hex.EncodeToString(assetID) {
continue
}
localSum += balances[assetIDString].LocalBalance
remoteSum += balances[assetIDString].RemoteBalance
}
return localSum, remoteSum, balance.LocalBalance.Sat,
balance.RemoteBalance.Sat
}
func fetchChannel(t *testing.T, node *HarnessNode,
chanPoint *lnrpc.ChannelPoint) *lnrpc.Channel {
ctxb := context.Background()
ctxt, cancel := context.WithTimeout(ctxb, defaultTimeout)
defer cancel()
channelResp, err := node.ListChannels(ctxt, &lnrpc.ListChannelsRequest{
ActiveOnly: true,
})
require.NoError(t, err)
chanFundingHash, err := lnrpc.GetChanPointFundingTxid(chanPoint)
require.NoError(t, err)
chanPointStr := fmt.Sprintf("%v:%v", chanFundingHash,
chanPoint.OutputIndex)
var targetChan *lnrpc.Channel
for _, channel := range channelResp.Channels {
if channel.ChannelPoint == chanPointStr {
targetChan = channel
break
}
}
require.NotNil(t, targetChan)
return targetChan
}
func assertChannelSatBalance(t *testing.T, node *HarnessNode,
chanPoint *lnrpc.ChannelPoint, local, remote int64) {
targetChan := fetchChannel(t, node, chanPoint)
require.InDelta(t, local, targetChan.LocalBalance, 1)
require.InDelta(t, remote, targetChan.RemoteBalance, 1)
}
func assertChannelAssetBalance(t *testing.T, node *HarnessNode,
chanPoint *lnrpc.ChannelPoint, local, remote uint64) {
targetChan := fetchChannel(t, node, chanPoint)
var assetBalance rfqmsg.JsonAssetChannel
err := json.Unmarshal(targetChan.CustomChannelData, &assetBalance)
require.NoError(t, err)
require.Len(t, assetBalance.Assets, 1)
require.InDelta(t, local, assetBalance.Assets[0].LocalBalance, 1)
require.InDelta(t, remote, assetBalance.Assets[0].RemoteBalance, 1)
}
// addRoutingFee adds the default routing fee (1 part per million fee rate plus
// 1000 milli-satoshi base fee) to the given milli-satoshi amount.
func addRoutingFee(amt lnwire.MilliSatoshi) lnwire.MilliSatoshi {
return amt + (amt / 1000_000) + 1000
}
func sendAssetKeySendPayment(t *testing.T, src, dst *HarnessNode, amt uint64,
assetID []byte, btcAmt fn.Option[int64], opts ...payOpt) {
cfg := defaultPayConfig()
for _, opt := range opts {
opt(cfg)
}
ctxb := context.Background()
ctxt, cancel := context.WithTimeout(ctxb, defaultTimeout)
defer cancel()
srcTapd := newTapClient(t, src)
// Read out the custom preimage for the keysend payment.
var preimage lntypes.Preimage
_, err := rand.Read(preimage[:])
require.NoError(t, err)
hash := preimage.Hash()
// Set the preimage. If the user supplied a preimage with the data
// flag, the preimage that is set here will be overwritten later.
customRecords := make(map[uint64][]byte)
customRecords[record.KeySendType] = preimage[:]
sendReq := &routerrpc.SendPaymentRequest{
Dest: dst.PubKey[:],
Amt: btcAmt.UnwrapOr(500),
DestCustomRecords: customRecords,
PaymentHash: hash[:],
TimeoutSeconds: int32(PaymentTimeout.Seconds()),
}
stream, err := srcTapd.SendPayment(ctxt, &tchrpc.SendPaymentRequest{
AssetId: assetID,
AssetAmount: amt,
PaymentRequest: sendReq,
})
require.NoError(t, err)
result, err := getAssetPaymentResult(stream, false)
require.NoError(t, err)
if result.Status == lnrpc.Payment_FAILED {
t.Logf("Failure reason: %v", result.FailureReason)
}
require.Equal(t, cfg.payStatus, result.Status)
require.Equal(t, cfg.failureReason, result.FailureReason)
}
func sendKeySendPayment(t *testing.T, src, dst *HarnessNode,
amt btcutil.Amount) {
ctxb := context.Background()
ctxt, cancel := context.WithTimeout(ctxb, defaultTimeout)
defer cancel()
// Read out the custom preimage for the keysend payment.
var preimage lntypes.Preimage
_, err := rand.Read(preimage[:])
require.NoError(t, err)
hash := preimage.Hash()
// Set the preimage. If the user supplied a preimage with the data
// flag, the preimage that is set here will be overwritten later.
customRecords := make(map[uint64][]byte)
customRecords[record.KeySendType] = preimage[:]
req := &routerrpc.SendPaymentRequest{
Dest: dst.PubKey[:],
Amt: int64(amt),
DestCustomRecords: customRecords,
PaymentHash: hash[:],
TimeoutSeconds: int32(PaymentTimeout.Seconds()),
}
stream, err := src.RouterClient.SendPaymentV2(ctxt, req)
require.NoError(t, err)
result, err := getPaymentResult(stream)
require.NoError(t, err)
require.Equal(t, lnrpc.Payment_SUCCEEDED, result.Status)
}
func createAndPayNormalInvoiceWithBtc(t *testing.T, src, dst *HarnessNode,
amountSat btcutil.Amount) {
ctxb := context.Background()
ctxt, cancel := context.WithTimeout(ctxb, defaultTimeout)
defer cancel()
expirySeconds := 10
invoiceResp, err := dst.AddInvoice(ctxt, &lnrpc.Invoice{
Value: int64(amountSat),
Memo: "normal invoice",
Expiry: int64(expirySeconds),
})
require.NoError(t, err)
payInvoiceWithSatoshi(t, src, invoiceResp)
}
func createNormalInvoice(t *testing.T, dst *HarnessNode,
amountSat btcutil.Amount) *lnrpc.AddInvoiceResponse {
ctxb := context.Background()
ctxt, cancel := context.WithTimeout(ctxb, defaultTimeout)
defer cancel()
expirySeconds := 10
invoiceResp, err := dst.AddInvoice(ctxt, &lnrpc.Invoice{
Value: int64(amountSat),
Memo: "normal invoice",
Expiry: int64(expirySeconds),
})
require.NoError(t, err)
return invoiceResp
}
func createAndPayNormalInvoice(t *testing.T, src, rfqPeer, dst *HarnessNode,
amountSat btcutil.Amount, assetID []byte, opts ...payOpt) uint64 {
invoiceResp := createNormalInvoice(t, dst, amountSat)
numUnits, _ := payInvoiceWithAssets(
t, src, rfqPeer, invoiceResp.PaymentRequest, assetID, opts...,
)
return numUnits
}
func payInvoiceWithSatoshi(t *testing.T, payer *HarnessNode,
invoice *lnrpc.AddInvoiceResponse, opts ...payOpt) {
cfg := defaultPayConfig()
for _, opt := range opts {
opt(cfg)
}
ctxb := context.Background()
ctxt, cancel := context.WithTimeout(ctxb, defaultTimeout)
defer cancel()
sendReq := &routerrpc.SendPaymentRequest{
PaymentRequest: invoice.PaymentRequest,
TimeoutSeconds: int32(PaymentTimeout.Seconds()),
MaxShardSizeMsat: 80_000_000,
FeeLimitMsat: 1_000_000,
}
stream, err := payer.RouterClient.SendPaymentV2(ctxt, sendReq)
require.NoError(t, err)
result, err := getPaymentResult(stream)
if cfg.errSubStr != "" {
require.ErrorContains(t, err, cfg.errSubStr)
} else {
require.NoError(t, err)
require.Equal(t, cfg.payStatus, result.Status)
require.Equal(t, cfg.failureReason, result.FailureReason)
}
}
func payInvoiceWithSatoshiLastHop(t *testing.T, payer *HarnessNode,
invoice *lnrpc.AddInvoiceResponse, hops [][]byte, opts ...payOpt) {
cfg := defaultPayConfig()
for _, opt := range opts {
opt(cfg)
}
ctxb := context.Background()
ctxt, cancel := context.WithTimeout(ctxb, defaultTimeout)
defer cancel()
decodedInvoice, err := payer.DecodePayReq(ctxt, &lnrpc.PayReqString{
PayReq: invoice.PaymentRequest,
})
require.NoError(t, err)
routeRes, err := payer.RouterClient.BuildRoute(
ctxb, &routerrpc.BuildRouteRequest{
AmtMsat: decodedInvoice.NumMsat,
PaymentAddr: invoice.PaymentAddr,
HopPubkeys: hops,
},
)
require.NoError(t, err)
res, err := payer.RouterClient.SendToRouteV2(
ctxt, &routerrpc.SendToRouteRequest{
PaymentHash: invoice.RHash,
Route: routeRes.Route,
},
)
require.NoError(t, err)
switch cfg.payStatus {
case lnrpc.Payment_FAILED:
require.NoError(t, err)
require.Equal(t, lnrpc.HTLCAttempt_FAILED, res.Status)
require.NotNil(t, res.Failure)
require.Nil(t, res.Preimage)
case lnrpc.Payment_SUCCEEDED:
require.NoError(t, err)
require.Equal(t, lnrpc.HTLCAttempt_SUCCEEDED, res.Status)
}
}
type payConfig struct {
smallShards bool
errSubStr string
allowOverpay bool
feeLimit lnwire.MilliSatoshi
destCustomRecords map[uint64][]byte
payStatus lnrpc.Payment_PaymentStatus
failureReason lnrpc.PaymentFailureReason
rfq fn.Option[rfqmsg.ID]
}
func defaultPayConfig() *payConfig {
return &payConfig{
smallShards: false,
errSubStr: "",
feeLimit: 1_000_000,
payStatus: lnrpc.Payment_SUCCEEDED,
failureReason: lnrpc.PaymentFailureReason_FAILURE_REASON_NONE,
}
}
type payOpt func(*payConfig)
func withSmallShards() payOpt {
return func(c *payConfig) {
c.smallShards = true
}
}
func withPayErrSubStr(errSubStr string) payOpt {
return func(c *payConfig) {
c.errSubStr = errSubStr
}
}
func withFailure(status lnrpc.Payment_PaymentStatus,
reason lnrpc.PaymentFailureReason) payOpt {
return func(c *payConfig) {
c.payStatus = status
c.failureReason = reason
}
}
func withRFQ(rfqID rfqmsg.ID) payOpt {
return func(c *payConfig) {
c.rfq = fn.Some(rfqID)
}
}
func withFeeLimit(limit lnwire.MilliSatoshi) payOpt {
return func(c *payConfig) {
c.feeLimit = limit
}
}
func withDestCustomRecords(records map[uint64][]byte) payOpt {
return func(c *payConfig) {
c.destCustomRecords = records
}
}
func withAllowOverpay() payOpt {
return func(c *payConfig) {
c.allowOverpay = true
}
}
func payInvoiceWithAssets(t *testing.T, payer, rfqPeer *HarnessNode,
payReq string, assetID []byte,
opts ...payOpt) (uint64, rfqmath.BigIntFixedPoint) {