-
Notifications
You must be signed in to change notification settings - Fork 128
Expand file tree
/
Copy pathswapclient_server.go
More file actions
2762 lines (2294 loc) · 75.4 KB
/
swapclient_server.go
File metadata and controls
2762 lines (2294 loc) · 75.4 KB
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 loopd
import (
"bytes"
"cmp"
"context"
"encoding/hex"
"errors"
"fmt"
"reflect"
"slices"
"sort"
"strings"
"sync"
"time"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/wire"
"github.com/lightninglabs/aperture/l402"
"github.com/lightninglabs/lndclient"
"github.com/lightninglabs/loop"
"github.com/lightninglabs/loop/assets"
"github.com/lightninglabs/loop/fsm"
"github.com/lightninglabs/loop/instantout"
"github.com/lightninglabs/loop/instantout/reservation"
"github.com/lightninglabs/loop/labels"
"github.com/lightninglabs/loop/liquidity"
"github.com/lightninglabs/loop/loopdb"
"github.com/lightninglabs/loop/looprpc"
"github.com/lightninglabs/loop/staticaddr/address"
"github.com/lightninglabs/loop/staticaddr/deposit"
"github.com/lightninglabs/loop/staticaddr/loopin"
"github.com/lightninglabs/loop/staticaddr/openchannel"
"github.com/lightninglabs/loop/staticaddr/staticutil"
"github.com/lightninglabs/loop/staticaddr/withdraw"
"github.com/lightninglabs/loop/swap"
"github.com/lightninglabs/loop/swapserverrpc"
"github.com/lightninglabs/taproot-assets/rfqmath"
"github.com/lightningnetwork/lnd/lnrpc/walletrpc"
"github.com/lightningnetwork/lnd/lntypes"
"github.com/lightningnetwork/lnd/queue"
"github.com/lightningnetwork/lnd/routing/route"
"github.com/lightningnetwork/lnd/zpay32"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
completedSwapsCount = 5
// minConfTarget is the minimum confirmation target we'll allow clients
// to specify. This is driven by the minimum confirmation target allowed
// by the backing fee estimator.
minConfTarget = 2
defaultLoopdInitiator = "loopd"
)
var (
// errIncorrectChain is returned when the format of the
// destination address provided does not match the active chain.
errIncorrectChain = errors.New("invalid address format for the " +
"active chain")
// errConfTargetTooLow is returned when the chosen confirmation target
// is below the allowed minimum.
errConfTargetTooLow = errors.New("confirmation target too low")
// errBalanceTooLow is returned when the loop out amount can't be
// satisfied given total balance of the selection of channels to loop
// out on.
errBalanceTooLow = errors.New(
"channel balance too low for loop out amount",
)
// errInvalidAddress is returned when the destination address is of
// an unsupported format such as P2PK or P2TR addresses.
errInvalidAddress = errors.New(
"invalid or unsupported address",
)
)
// swapClientServer implements the grpc service exposed by loopd.
type swapClientServer struct {
// Required by the grpc-gateway/v2 library for forward compatibility.
looprpc.UnimplementedSwapClientServer
looprpc.UnimplementedDebugServer
config *Config
network lndclient.Network
impl *loop.Client
liquidityMgr *liquidity.Manager
lnd *lndclient.LndServices
reservationManager *reservation.Manager
instantOutManager *instantout.Manager
staticAddressManager *address.Manager
depositManager *deposit.Manager
withdrawalManager *withdraw.Manager
staticLoopInManager *loopin.Manager
openChannelManager *openchannel.Manager
assetClient *assets.TapdClient
swaps map[lntypes.Hash]loop.SwapInfo
subscribers map[int]chan<- any
statusChan chan loop.SwapInfo
nextSubscriberID int
swapsLock sync.Mutex
mainCtx context.Context
// stopDaemon is invoked to trigger a graceful shutdown of the daemon.
stopDaemon func()
}
// LoopOut initiates a loop out swap with the given parameters. The call returns
// after the swap has been set up with the swap server. From that point onwards,
// progress can be tracked via the LoopOutStatus stream that is returned from
// Monitor().
func (s *swapClientServer) LoopOut(ctx context.Context,
in *looprpc.LoopOutRequest) (
*looprpc.SwapResponse, error) {
infof("Loop out request received")
// Note that LoopOutRequest.PaymentTimeout is unsigned and therefore
// cannot be negative.
paymentTimeout := time.Duration(in.PaymentTimeout) * time.Second
// Make sure we don't exceed the total allowed payment timeout.
if paymentTimeout > s.config.TotalPaymentTimeout {
return nil, fmt.Errorf("payment timeout %v exceeds maximum "+
"allowed timeout of %v", paymentTimeout,
s.config.TotalPaymentTimeout)
}
var sweepAddr btcutil.Address
var isExternalAddr bool
var err error
//nolint:lll
switch {
case in.Dest != "" && in.Account != "":
return nil, fmt.Errorf("destination address and external " +
"account address cannot be set at the same time")
case in.Dest != "":
// Decode the client provided destination address for the loop
// out sweep.
sweepAddr, err = btcutil.DecodeAddress(
in.Dest, s.lnd.ChainParams,
)
if err != nil {
return nil, fmt.Errorf("decode address: %v", err)
}
isExternalAddr = true
case in.Account != "" && in.AccountAddrType == looprpc.AddressType_ADDRESS_TYPE_UNKNOWN:
return nil, liquidity.ErrAccountAndAddrType
case in.Account != "":
// Derive a new receiving address from the stated account.
addrType, err := toWalletAddrType(in.AccountAddrType)
if err != nil {
return nil, err
}
// Check if account with address type exists.
if !s.accountExists(ctx, in.Account, addrType) {
return nil, fmt.Errorf("the provided account does " +
"not exist")
}
sweepAddr, err = s.lnd.WalletKit.NextAddr(
ctx, in.Account, addrType, false,
)
if err != nil {
return nil, fmt.Errorf("NextAddr from account error: "+
"%v", err)
}
isExternalAddr = true
default:
// Generate sweep address if none specified.
sweepAddr, err = s.lnd.WalletKit.NextAddr(
context.Background(), "",
walletrpc.AddressType_WITNESS_PUBKEY_HASH, false,
)
if err != nil {
return nil, fmt.Errorf("NextAddr error: %v", err)
}
}
sweepConfTarget, err := validateLoopOutRequest(
ctx, s.lnd.Client, s.lnd.ChainParams, in, sweepAddr,
s.impl.LoopOutMaxParts,
)
if err != nil {
return nil, err
}
// Infer if the publication deadline is set in milliseconds.
publicationDeadline := getPublicationDeadline(in.SwapPublicationDeadline)
req := &loop.OutRequest{
Amount: btcutil.Amount(in.Amt),
DestAddr: sweepAddr,
IsExternalAddr: isExternalAddr,
MaxMinerFee: btcutil.Amount(in.MaxMinerFee),
MaxPrepayAmount: btcutil.Amount(in.MaxPrepayAmt),
MaxPrepayRoutingFee: btcutil.Amount(in.MaxPrepayRoutingFee),
MaxSwapRoutingFee: btcutil.Amount(in.MaxSwapRoutingFee),
MaxSwapFee: btcutil.Amount(in.MaxSwapFee),
SweepConfTarget: sweepConfTarget,
HtlcConfirmations: in.HtlcConfirmations,
SwapPublicationDeadline: publicationDeadline,
Label: in.Label,
Initiator: in.Initiator,
PaymentTimeout: paymentTimeout,
}
// If the asset id is set, we need to set the asset amount and asset id
// in the request.
if in.AssetInfo != nil {
if len(in.AssetInfo.AssetId) != 0 &&
len(in.AssetInfo.AssetId) != 32 {
return nil, fmt.Errorf(
"asset id must be set to a 32 byte value",
)
}
if len(in.AssetRfqInfo.PrepayRfqId) != 0 &&
len(in.AssetRfqInfo.PrepayRfqId) != 32 {
return nil, fmt.Errorf(
"prepay rfq id must be set to a 32 byte value",
)
}
if len(in.AssetRfqInfo.SwapRfqId) != 0 &&
len(in.AssetRfqInfo.SwapRfqId) != 32 {
return nil, fmt.Errorf(
"swap rfq id must be set to a 32 byte value",
)
}
req.AssetId = in.AssetInfo.AssetId
req.AssetPrepayRfqId = in.AssetRfqInfo.PrepayRfqId
req.AssetSwapRfqId = in.AssetRfqInfo.SwapRfqId
}
switch {
case in.LoopOutChannel != 0 && len(in.OutgoingChanSet) > 0: // nolint:staticcheck
return nil, errors.New("loop_out_channel and outgoing_" +
"chan_ids are mutually exclusive")
case in.LoopOutChannel != 0: // nolint:staticcheck
req.OutgoingChanSet = loopdb.ChannelSet{in.LoopOutChannel} // nolint:staticcheck
default:
req.OutgoingChanSet = in.OutgoingChanSet
}
info, err := s.impl.LoopOut(ctx, req)
if err != nil {
errorf("LoopOut: %v", err)
return nil, err
}
htlcAddress := info.HtlcAddress.String()
resp := &looprpc.SwapResponse{
Id: info.SwapHash.String(),
IdBytes: info.SwapHash[:],
HtlcAddress: htlcAddress,
ServerMessage: info.ServerMessage,
}
if loopdb.CurrentProtocolVersion() < loopdb.ProtocolVersionHtlcV3 {
resp.HtlcAddressP2Wsh = htlcAddress
} else {
resp.HtlcAddressP2Tr = htlcAddress
}
return resp, nil
}
// accountExists returns true if account under the address type exists in the
// backing lnd instance and false otherwise.
func (s *swapClientServer) accountExists(ctx context.Context, account string,
addrType walletrpc.AddressType) bool {
accounts, err := s.lnd.WalletKit.ListAccounts(ctx, account, addrType)
if err != nil {
return false
}
for _, a := range accounts {
if a.Name == account {
return true
}
}
return false
}
func toWalletAddrType(addrType looprpc.AddressType) (walletrpc.AddressType,
error) {
switch addrType {
case looprpc.AddressType_TAPROOT_PUBKEY:
return walletrpc.AddressType_TAPROOT_PUBKEY, nil
default:
return walletrpc.AddressType_UNKNOWN,
fmt.Errorf("unknown address type")
}
}
func (s *swapClientServer) marshallSwap(ctx context.Context,
loopSwap *loop.SwapInfo) (*looprpc.SwapStatus, error) {
var (
state looprpc.SwapState
failureReason = looprpc.FailureReason_FAILURE_REASON_NONE
)
// Set our state var for non-failure states. If we get a failure, we
// will update our failure reason. To remain backwards compatible with
// previous versions where we squashed all failure reasons to a single
// failure state, we set a failure reason for all our different failure
// states, and set our failed state for all of them.
switch loopSwap.State {
case loopdb.StateInitiated:
state = looprpc.SwapState_INITIATED
case loopdb.StatePreimageRevealed:
state = looprpc.SwapState_PREIMAGE_REVEALED
case loopdb.StateHtlcPublished:
state = looprpc.SwapState_HTLC_PUBLISHED
case loopdb.StateInvoiceSettled:
state = looprpc.SwapState_INVOICE_SETTLED
case loopdb.StateSuccess:
state = looprpc.SwapState_SUCCESS
case loopdb.StateFailOffchainPayments:
failureReason = looprpc.FailureReason_FAILURE_REASON_OFFCHAIN
case loopdb.StateFailTimeout:
failureReason = looprpc.FailureReason_FAILURE_REASON_TIMEOUT
case loopdb.StateFailSweepTimeout:
failureReason = looprpc.FailureReason_FAILURE_REASON_SWEEP_TIMEOUT
case loopdb.StateFailInsufficientValue:
failureReason = looprpc.FailureReason_FAILURE_REASON_INSUFFICIENT_VALUE
case loopdb.StateFailTemporary:
failureReason = looprpc.FailureReason_FAILURE_REASON_TEMPORARY
case loopdb.StateFailIncorrectHtlcAmt:
failureReason = looprpc.FailureReason_FAILURE_REASON_INCORRECT_AMOUNT
case loopdb.StateFailAbandoned:
failureReason = looprpc.FailureReason_FAILURE_REASON_ABANDONED
case loopdb.StateFailInsufficientConfirmedBalance:
failureReason = looprpc.FailureReason_FAILURE_REASON_INSUFFICIENT_CONFIRMED_BALANCE
case loopdb.StateFailIncorrectHtlcAmtSwept:
failureReason = looprpc.FailureReason_FAILURE_REASON_INCORRECT_HTLC_AMT_SWEPT
default:
return nil, fmt.Errorf("unknown swap state: %v", loopSwap.State)
}
// If we have a failure reason, we have a failure state, so should use
// our catchall failed state.
if failureReason != looprpc.FailureReason_FAILURE_REASON_NONE {
state = looprpc.SwapState_FAILED
}
var swapType looprpc.SwapType
var (
htlcAddress string
htlcAddressP2TR string
htlcAddressP2WSH string
)
var outGoingChanSet []uint64
var lastHop []byte
var assetInfo *looprpc.AssetLoopOutInfo
switch loopSwap.SwapType {
case swap.TypeIn:
swapType = looprpc.SwapType_LOOP_IN
if loopSwap.HtlcAddressP2TR != nil {
htlcAddressP2TR = loopSwap.HtlcAddressP2TR.EncodeAddress()
htlcAddress = htlcAddressP2TR
} else {
htlcAddressP2WSH =
loopSwap.HtlcAddressP2WSH.EncodeAddress()
htlcAddress = htlcAddressP2WSH
}
if loopSwap.LastHop != nil {
lastHop = loopSwap.LastHop[:]
}
case swap.TypeOut:
swapType = looprpc.SwapType_LOOP_OUT
if loopSwap.HtlcAddressP2WSH != nil {
htlcAddressP2WSH = loopSwap.HtlcAddressP2WSH.EncodeAddress()
htlcAddress = htlcAddressP2WSH
} else {
htlcAddressP2TR = loopSwap.HtlcAddressP2TR.EncodeAddress()
htlcAddress = htlcAddressP2TR
}
outGoingChanSet = loopSwap.OutgoingChanSet
if loopSwap.AssetSwapInfo != nil {
var (
// Default the asset name to "N/A" in case we
// can't fetch it due to the asset client not
// being set.
assetName string = "N/A"
err error
)
if s.assetClient != nil {
assetName, err = s.assetClient.GetAssetName(
ctx, loopSwap.AssetSwapInfo.AssetId,
)
if err != nil {
return nil, err
}
}
assetInfo = &looprpc.AssetLoopOutInfo{
AssetId: hex.EncodeToString(loopSwap.AssetSwapInfo.AssetId), // nolint:lll
AssetCostOffchain: loopSwap.AssetSwapInfo.PrepayPaidAmt +
loopSwap.AssetSwapInfo.SwapPaidAmt, // nolint:lll
AssetName: assetName,
}
}
default:
return nil, errors.New("unknown swap type")
}
return &looprpc.SwapStatus{
Amt: int64(loopSwap.AmountRequested),
Id: loopSwap.SwapHash.String(),
IdBytes: loopSwap.SwapHash[:],
State: state,
FailureReason: failureReason,
InitiationTime: loopSwap.InitiationTime.UnixNano(),
LastUpdateTime: loopSwap.LastUpdate.UnixNano(),
HtlcAddress: htlcAddress,
HtlcAddressP2Tr: htlcAddressP2TR,
HtlcAddressP2Wsh: htlcAddressP2WSH,
Type: swapType,
CostServer: int64(loopSwap.Cost.Server),
CostOnchain: int64(loopSwap.Cost.Onchain),
CostOffchain: int64(loopSwap.Cost.Offchain),
Label: loopSwap.Label,
LastHop: lastHop,
OutgoingChanSet: outGoingChanSet,
AssetInfo: assetInfo,
}, nil
}
// Monitor will return a stream of swap updates for currently active swaps.
func (s *swapClientServer) Monitor(in *looprpc.MonitorRequest,
server looprpc.SwapClient_MonitorServer) error {
infof("Monitor request received")
send := func(info loop.SwapInfo) error {
rpcSwap, err := s.marshallSwap(server.Context(), &info)
if err != nil {
return err
}
return server.Send(rpcSwap)
}
// Start a notification queue for this subscriber.
queue := queue.NewConcurrentQueue(20)
queue.Start()
// Add this subscriber to the global subscriber list. Also create a
// snapshot of all pending and completed swaps within the lock, to
// prevent subscribers from receiving duplicate updates.
s.swapsLock.Lock()
id := s.nextSubscriberID
s.nextSubscriberID++
s.subscribers[id] = queue.ChanIn()
var pendingSwaps, completedSwaps []loop.SwapInfo
for _, swap := range s.swaps {
if swap.State.Type() == loopdb.StateTypePending {
pendingSwaps = append(pendingSwaps, swap)
} else {
completedSwaps = append(completedSwaps, swap)
}
}
s.swapsLock.Unlock()
defer func() {
s.swapsLock.Lock()
delete(s.subscribers, id)
s.swapsLock.Unlock()
queue.Stop()
}()
// Sort completed swaps new to old.
sort.Slice(completedSwaps, func(i, j int) bool {
return completedSwaps[i].LastUpdate.After(
completedSwaps[j].LastUpdate,
)
})
// Discard all but top x latest.
if len(completedSwaps) > completedSwapsCount {
completedSwaps = completedSwaps[:completedSwapsCount]
}
// Concatenate both sets.
filteredSwaps := append(pendingSwaps, completedSwaps...) // nolint: gocritic
// Sort again, but this time old to new.
sort.Slice(filteredSwaps, func(i, j int) bool {
return filteredSwaps[i].LastUpdate.Before(
filteredSwaps[j].LastUpdate,
)
})
// Return swaps to caller.
for _, swap := range filteredSwaps {
if err := send(swap); err != nil {
return err
}
}
// As long as the client is connected, keep passing through swap
// updates.
for {
select {
case queueItem, ok := <-queue.ChanOut():
if !ok {
return nil
}
swap := queueItem.(loop.SwapInfo)
if err := send(swap); err != nil {
return err
}
// The client cancels the subscription.
case <-server.Context().Done():
return nil
// The server is shutting down.
case <-s.mainCtx.Done():
return fmt.Errorf("server is shutting down")
}
}
}
// ListSwaps returns a list of all currently known swaps and their current
// status.
func (s *swapClientServer) ListSwaps(ctx context.Context,
req *looprpc.ListSwapsRequest) (*looprpc.ListSwapsResponse, error) {
var (
rpcSwaps = []*looprpc.SwapStatus{}
swapInfos = []*loop.SwapInfo{}
maxSwaps = int(req.MaxSwaps)
nextStartTime = int64(0)
canPage = false
)
s.swapsLock.Lock()
defer s.swapsLock.Unlock()
// We can just use the server's in-memory cache as that contains the
// most up-to-date state including temporary failures which aren't
// persisted to disk. The swaps field is a map, that's why we need an
// additional index.
for _, swp := range s.swaps {
// Filter the swap based on the provided filter.
if !filterSwap(&swp, req.ListSwapFilter) {
continue
}
swapInfos = append(swapInfos, &swp)
}
// Sort the swaps by initiation time in ascending order (oldest first).
slices.SortFunc(swapInfos, func(a, b *loop.SwapInfo) int {
return cmp.Compare(
a.InitiationTime.UnixNano(),
b.InitiationTime.UnixNano(),
)
})
// Apply the maxSwaps limit if specified.
if maxSwaps > 0 && len(swapInfos) > maxSwaps {
canPage = true
swapInfos = swapInfos[:maxSwaps]
}
// Marshal the filtered and limited swaps.
for _, swp := range swapInfos {
rpcSwap, err := s.marshallSwap(ctx, swp)
if err != nil {
return nil, err
}
rpcSwaps = append(rpcSwaps, rpcSwap)
}
// Set the next start time for pagination if needed.
if canPage && len(rpcSwaps) > 0 {
// Use the initiation time of the last swap plus 1 nanosecond.
nextStartTime = rpcSwaps[len(rpcSwaps)-1].InitiationTime + 1
}
response := looprpc.ListSwapsResponse{
Swaps: rpcSwaps,
NextStartTime: nextStartTime,
}
return &response, nil
}
// filterSwap filters the given swap based on the provided filter.
func filterSwap(swapInfo *loop.SwapInfo, filter *looprpc.ListSwapsFilter) bool {
if filter == nil {
return true
}
// If the swap type filter is set, we only return swaps that match the
// filter.
if filter.SwapType != looprpc.ListSwapsFilter_ANY {
switch filter.SwapType {
case looprpc.ListSwapsFilter_LOOP_IN:
if swapInfo.SwapType != swap.TypeIn {
return false
}
case looprpc.ListSwapsFilter_LOOP_OUT:
if swapInfo.SwapType != swap.TypeOut {
return false
}
}
}
// If the pending only filter is set, we only return pending swaps.
if filter.PendingOnly && !swapInfo.State.IsPending() {
return false
}
// If timestamp filters are set, only return swaps within the specified time range.
if filter.StartTimestampNs > 0 &&
swapInfo.InitiationTime.UnixNano() < filter.StartTimestampNs {
return false
}
// If the swap is of type loop out and the outgoing channel filter is
// set, we only return swaps that match the filter.
if swapInfo.SwapType == swap.TypeOut && filter.OutgoingChanSet != nil {
// First we sort both channel sets to make sure we can compare
// them.
slices.Sort(swapInfo.OutgoingChanSet)
slices.Sort(filter.OutgoingChanSet)
// Compare the outgoing channel set by using reflect.DeepEqual
// which compares the underlying arrays.
if !reflect.DeepEqual(swapInfo.OutgoingChanSet,
filter.OutgoingChanSet) {
return false
}
}
// If the swap is of type loop in and the last hop filter is set, we
// only return swaps that match the filter.
if swapInfo.SwapType == swap.TypeIn && filter.LoopInLastHop != nil {
// Compare the last hop by using reflect.DeepEqual which
// compares the underlying arrays.
if !reflect.DeepEqual(swapInfo.LastHop, filter.LoopInLastHop) {
return false
}
}
// If a label filter is set, we only return swaps that softly match the
// filter.
if filter.Label != "" {
if !strings.Contains(swapInfo.Label, filter.Label) {
return false
}
}
// If we only want to return asset swaps, we only return swaps that have
// an asset id set.
if filter.AssetSwapOnly && swapInfo.AssetSwapInfo == nil {
return false
}
return true
}
// SwapInfo returns all known details about a single swap.
func (s *swapClientServer) SwapInfo(ctx context.Context,
req *looprpc.SwapInfoRequest) (*looprpc.SwapStatus, error) {
swapHash, err := lntypes.MakeHash(req.Id)
if err != nil {
return nil, fmt.Errorf("error parsing swap hash: %v", err)
}
// Just return the server's in-memory cache here too as we also want to
// return temporary failures to the client.
swp, ok := s.swaps[swapHash]
if !ok {
return nil, fmt.Errorf("swap with hash %s not found", req.Id)
}
return s.marshallSwap(ctx, &swp)
}
// AbandonSwap requests the server to abandon a swap with the given hash.
func (s *swapClientServer) AbandonSwap(ctx context.Context,
req *looprpc.AbandonSwapRequest) (*looprpc.AbandonSwapResponse,
error) {
if !req.IKnowWhatIAmDoing {
return nil, fmt.Errorf("please read the AbandonSwap API " +
"documentation")
}
swapHash, err := lntypes.MakeHash(req.Id)
if err != nil {
return nil, fmt.Errorf("error parsing swap hash: %v", err)
}
s.swapsLock.Lock()
swap, ok := s.swaps[swapHash]
s.swapsLock.Unlock()
if !ok {
return nil, fmt.Errorf("swap with hash %s not found", req.Id)
}
if swap.SwapType.IsOut() {
return nil, fmt.Errorf("abandoning loop out swaps is not " +
"supported yet")
}
// If the swap is in a final state, we cannot abandon it.
if swap.State.IsFinal() {
return nil, fmt.Errorf("cannot abandon swap in final state, "+
"state = %s, hash = %s", swap.State.String(), swapHash)
}
err = s.impl.AbandonSwap(ctx, &loop.AbandonSwapRequest{
SwapHash: swapHash,
})
if err != nil {
return nil, fmt.Errorf("error abandoning swap: %v", err)
}
return &looprpc.AbandonSwapResponse{}, nil
}
// LoopOutTerms returns the terms that the server enforces for loop out swaps.
func (s *swapClientServer) LoopOutTerms(ctx context.Context,
_ *looprpc.TermsRequest) (*looprpc.OutTermsResponse, error) {
infof("Loop out terms request received")
terms, err := s.impl.LoopOutTerms(ctx, defaultLoopdInitiator)
if err != nil {
errorf("Terms request: %v", err)
return nil, err
}
return &looprpc.OutTermsResponse{
MinSwapAmount: int64(terms.MinSwapAmount),
MaxSwapAmount: int64(terms.MaxSwapAmount),
MinCltvDelta: terms.MinCltvDelta,
MaxCltvDelta: terms.MaxCltvDelta,
}, nil
}
// LoopOutQuote returns a quote for a loop out swap with the provided
// parameters.
func (s *swapClientServer) LoopOutQuote(ctx context.Context,
req *looprpc.QuoteRequest) (*looprpc.OutQuoteResponse, error) {
confTarget, err := validateConfTarget(
req.ConfTarget, loop.DefaultSweepConfTarget,
)
if err != nil {
return nil, err
}
publicactionDeadline := getPublicationDeadline(
req.SwapPublicationDeadline,
)
loopOutQuoteReq := &loop.LoopOutQuoteRequest{
Amount: btcutil.Amount(req.Amt),
SweepConfTarget: confTarget,
SwapPublicationDeadline: publicactionDeadline,
Initiator: defaultLoopdInitiator,
}
if req.AssetInfo != nil {
if req.AssetInfo.AssetId == nil ||
req.AssetInfo.AssetEdgeNode == nil {
return nil, fmt.Errorf(
"asset id and edge node must both be set")
}
loopOutQuoteReq.AssetRFQRequest = &loop.AssetRFQRequest{
AssetId: req.AssetInfo.AssetId,
AssetEdgeNode: req.AssetInfo.AssetEdgeNode,
Expiry: req.AssetInfo.Expiry,
MaxLimitMultiplier: req.AssetInfo.MaxLimitMultiplier,
}
}
quote, err := s.impl.LoopOutQuote(ctx, loopOutQuoteReq)
if err != nil {
return nil, err
}
response := &looprpc.OutQuoteResponse{
HtlcSweepFeeSat: int64(quote.MinerFee),
PrepayAmtSat: int64(quote.PrepayAmount),
SwapFeeSat: int64(quote.SwapFee),
SwapPaymentDest: quote.SwapPaymentDest[:],
ConfTarget: confTarget,
}
if quote.LoopOutRfq != nil {
response.AssetRfqInfo = &looprpc.AssetRfqInfo{
PrepayRfqId: quote.LoopOutRfq.PrepayRfqId,
MaxPrepayAssetAmt: quote.LoopOutRfq.MaxPrepayAssetAmt,
PrepayAssetRate: marshalFixedPoint(
quote.LoopOutRfq.PrepayAssetRate,
),
SwapRfqId: quote.LoopOutRfq.SwapRfqId,
MaxSwapAssetAmt: quote.LoopOutRfq.MaxSwapAssetAmt,
SwapAssetRate: marshalFixedPoint(
quote.LoopOutRfq.SwapAssetRate,
),
AssetName: quote.LoopOutRfq.AssetName,
}
}
return response, nil
}
// GetLoopInTerms returns the terms that the server enforces for swaps.
func (s *swapClientServer) GetLoopInTerms(ctx context.Context,
_ *looprpc.TermsRequest) (*looprpc.InTermsResponse, error) {
infof("Loop in terms request received")
terms, err := s.impl.LoopInTerms(ctx, defaultLoopdInitiator)
if err != nil {
errorf("Terms request: %v", err)
return nil, err
}
return &looprpc.InTermsResponse{
MinSwapAmount: int64(terms.MinSwapAmount),
MaxSwapAmount: int64(terms.MaxSwapAmount),
}, nil
}
// GetLoopInQuote returns a quote for a swap with the provided parameters.
func (s *swapClientServer) GetLoopInQuote(ctx context.Context,
req *looprpc.QuoteRequest) (*looprpc.InQuoteResponse, error) {
infof("Loop in quote request received")
var (
selectedAmount = btcutil.Amount(req.Amt)
totalDepositAmount btcutil.Amount
autoSelectDeposits = req.AutoSelectDeposits
err error
)
htlcConfTarget, err := validateLoopInRequest(
req.ConfTarget, req.ExternalHtlc,
uint32(len(req.DepositOutpoints)), selectedAmount,
autoSelectDeposits,
)
if err != nil {
return nil, err
}
// The fast flag is only available for static loop in quote requests.
if req.Fast {
if !autoSelectDeposits && len(req.DepositOutpoints) == 0 {
return nil, fmt.Errorf("fast flag is only " +
"available for static address requests")
}
}
// If deposits should be automatically selected, we do so and count the
// number of deposits to quote for.
numDeposits := 0
if autoSelectDeposits {
deposits, err := s.depositManager.GetActiveDepositsInState(
deposit.Deposited,
)
if err != nil {
return nil, fmt.Errorf("unable to retrieve all "+
"deposits: %w", err)
}
// TODO(hieblmi): add params to deposit for multi-address
// support.
params, err := s.staticAddressManager.GetStaticAddressParameters(
ctx,
)
if err != nil {
return nil, fmt.Errorf("unable to retrieve static "+
"address parameters: %w", err)
}
info, err := s.lnd.Client.GetInfo(ctx)
if err != nil {
return nil, fmt.Errorf("unable to get lnd info: %w",
err)
}
selectedDeposits, err := loopin.SelectDeposits(
selectedAmount, deposits, params.Expiry,
info.BlockHeight,
)
if err != nil {
return nil, fmt.Errorf("unable to select deposits: %w",
err)
}
numDeposits = len(selectedDeposits)
} else if len(req.DepositOutpoints) > 0 {
// If deposits are selected, we need to retrieve them to
// calculate the total value which we request a quote for.
depositList, err := s.ListStaticAddressDeposits(
ctx, &looprpc.ListStaticAddressDepositsRequest{
Outpoints: req.DepositOutpoints,
},
)
if err != nil {
return nil, err
}
if depositList == nil {
return nil, fmt.Errorf("no summary returned for " +
"deposit outpoints")
}
if len(req.DepositOutpoints) !=
len(depositList.FilteredDeposits) {
return nil, fmt.Errorf("expected %d deposits, got %d",
len(req.DepositOutpoints),
len(depositList.FilteredDeposits))
} else {
numDeposits = len(depositList.FilteredDeposits)
}
// In case we quote for deposits, we send the server both the
// selected value and the number of deposits. This is so the
// server can probe the selected value and calculate the per
// input fee.
for _, deposit := range depositList.FilteredDeposits {
totalDepositAmount += btcutil.Amount(
deposit.Value,
)
}
// If a fractional amount is also selected, we check if it
// leads to a dust change output.
selectedAmount, err = loopin.DeduceSwapAmount(
totalDepositAmount, selectedAmount,
)
if err != nil {
return nil, fmt.Errorf("error calculating "+
"swap amount from selected amount: %v",