-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathservice.go
1041 lines (928 loc) · 29.3 KB
/
service.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 swap
import (
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"strings"
"sync"
"github.com/elementsproject/peerswap/log"
"github.com/elementsproject/peerswap/premium"
"github.com/elementsproject/peerswap/messages"
)
const (
PEERSWAP_PROTOCOL_VERSION = 5
)
var (
AllowedAssets = []string{"btc", "lbtc"}
ErrSwapDoesNotExist = errors.New("swap does not exist")
)
type ErrMinimumSwapSize uint64
func (u ErrMinimumSwapSize) Error() string {
return fmt.Sprintf("a minimum swap amount of %d msat is required", uint64(u))
}
type ErrUnknownSwapMessageType string
func (s ErrUnknownSwapMessageType) Error() string {
return fmt.Sprintf("message type %s is unknown to peerswap", string(s))
}
type PeerNotAllowedError string
func (s PeerNotAllowedError) Error() string {
return fmt.Sprintf("peer %s is not on allowlist", string(s))
}
type PeerIsSuspiciousError string
func (s PeerIsSuspiciousError) Error() string {
return fmt.Sprintf("peer %s is on suspicious peer list", string(s))
}
func ErrReceivedMessageFromUnexpectedPeer(peerId string, swapId *SwapId) error {
return fmt.Errorf("received a message from an unexpected peer, peerId: %s, swapId: %s", peerId, swapId.String())
}
// SwapService contains the logic for swaps
type SwapService struct {
swapServices *SwapServices
activeSwaps map[string]*SwapStateMachine
BitcoinEnabled bool
LiquidEnabled bool
sync.RWMutex
lastMsgLog map[string]string
}
func NewSwapService(services *SwapServices) *SwapService {
return &SwapService{
swapServices: services,
activeSwaps: map[string]*SwapStateMachine{},
LiquidEnabled: services.liquidEnabled,
BitcoinEnabled: services.bitcoinEnabled,
lastMsgLog: map[string]string{},
}
}
// Start adds callback to the messenger, txwatcher services and lightning client
func (s *SwapService) Start() error {
s.swapServices.toService = newTimeOutService(s.createTimeoutCallback)
s.swapServices.messenger.AddMessageHandler(s.OnMessageReceived)
if s.LiquidEnabled {
s.swapServices.liquidTxWatcher.AddConfirmationCallback(s.OnTxConfirmed)
s.swapServices.liquidTxWatcher.AddCsvCallback(s.OnCsvPassed)
}
if s.BitcoinEnabled {
s.swapServices.bitcoinTxWatcher.AddConfirmationCallback(s.OnTxConfirmed)
s.swapServices.bitcoinTxWatcher.AddCsvCallback(s.OnCsvPassed)
}
s.swapServices.lightning.AddPaymentCallback(s.OnPayment)
return nil
}
func (s *SwapService) HasActiveSwaps() (bool, error) {
swaps, err := s.swapServices.swapStore.ListAll()
if err != nil {
return false, err
}
for _, swap := range swaps {
if !swap.IsFinished() {
return true, nil
}
}
return false, nil
}
// RecoverSwaps tries to recover swaps that are not yet finished
func (s *SwapService) RecoverSwaps() error {
swaps, err := s.swapServices.swapStore.ListAll()
if err != nil {
return err
}
wg := &sync.WaitGroup{}
for _, sw := range swaps {
wg.Add(1)
go func(swap *SwapStateMachine) {
defer wg.Done()
if swap.IsFinished() {
return
}
if swap.Type == SWAPTYPE_IN && swap.Role == SWAPROLE_SENDER {
swap = swapInSenderFromStore(swap, s.swapServices)
} else if swap.Type == SWAPTYPE_IN && swap.Role == SWAPROLE_RECEIVER {
swap = swapInReceiverFromStore(swap, s.swapServices)
} else if swap.Type == SWAPTYPE_OUT && swap.Role == SWAPROLE_SENDER {
swap = swapOutSenderFromStore(swap, s.swapServices)
} else if swap.Type == SWAPTYPE_OUT && swap.Role == SWAPROLE_RECEIVER {
swap = swapOutReceiverFromStore(swap, s.swapServices)
}
swap.stateChange = sync.NewCond(&swap.stateMutex)
err := s.lockSwap(swap.SwapId.String(), swap.Data.GetScid(), swap)
if err != nil {
log.Infof("[%s]: error recovering swap: %v", swap.SwapId.String(), err)
return
}
done, err := swap.Recover()
if err != nil {
log.Infof("[%s]: error recovering swap: %v", swap.SwapId.String(), err)
return
}
if done {
s.RemoveActiveSwap(swap.SwapId.String())
}
}(sw)
}
log.Debugf("Waiting for all pending swaps to recover.")
wg.Wait()
return nil
}
func (s *SwapService) logMsg(swapId, peerId, msgTypeString string, payload []byte) {
s.Lock()
defer s.Unlock()
if lastMsgType, ok := s.lastMsgLog[swapId]; ok {
if lastMsgType == msgTypeString {
// We already logged this message, just tell that we received the
// last message again.
log.Debugf("[Messenger] From: %s got same message for swap: %s", peerId, swapId)
return
}
}
// We see the message type for this swap for the first time, we log the
// message.
s.lastMsgLog[swapId] = msgTypeString
// The payload is omitted because it includes the blinding key.
log.Debugf("[Messenger] From: %s got msgtype: %s for swap: %s", peerId, msgTypeString, swapId)
}
// OnMessageReceived handles incoming valid peermessages
func (s *SwapService) OnMessageReceived(peerId string, msgTypeString string, payload []byte) error {
if len(payload) > 100*1024 {
return errors.New("Payload is unexpectedly large")
}
msgType, err := messages.PeerswapCustomMessageType(msgTypeString)
if err != nil {
// Check for specific errors: even message type or message out of range
// message type that peerswap is not interested in.
if errors.Is(err, &messages.ErrNotPeerswapCustomMessage{}) {
// These errors are expected and can be handled gracefully
return nil
}
return err
}
msgBytes := []byte(payload)
switch msgType {
default:
// Do nothing here, as it will spam the cln log.
return nil
case messages.MESSAGETYPE_SWAPOUTREQUEST:
// s.logMsg(peerId, msgTypeString, payload)
var msg *SwapOutRequestMessage
err := json.Unmarshal(msgBytes, &msg)
if err != nil {
return err
}
s.logMsg(msg.SwapId.String(), peerId, msgTypeString, payload)
err = s.OnSwapOutRequestReceived(msg.SwapId, peerId, msg)
if err != nil {
return err
}
case messages.MESSAGETYPE_SWAPOUTAGREEMENT:
var msg *SwapOutAgreementMessage
err := json.Unmarshal(msgBytes, &msg)
if err != nil {
return err
}
s.logMsg(msg.SwapId.String(), peerId, msgTypeString, payload)
// Check if sender is expected swap partner peer.
ok, err := s.isMessageSenderExpectedPeer(peerId, msg.SwapId)
if err != nil {
return err
}
if !ok {
return ErrReceivedMessageFromUnexpectedPeer(peerId, msg.SwapId)
}
err = s.OnSwapOutAgreementReceived(msg)
if err != nil {
return err
}
case messages.MESSAGETYPE_OPENINGTXBROADCASTED:
var msg *OpeningTxBroadcastedMessage
err := json.Unmarshal(msgBytes, &msg)
if err != nil {
return err
}
s.logMsg(msg.SwapId.String(), peerId, msgTypeString, payload)
// Check if sender is expected swap partner peer.
ok, err := s.isMessageSenderExpectedPeer(peerId, msg.SwapId)
if err != nil {
return err
}
if !ok {
return ErrReceivedMessageFromUnexpectedPeer(peerId, msg.SwapId)
}
err = s.OnTxOpenedMessage(msg)
if err != nil {
return err
}
case messages.MESSAGETYPE_CANCELED:
var msg *CancelMessage
err := json.Unmarshal(msgBytes, &msg)
if err != nil {
return err
}
s.logMsg(msg.SwapId.String(), peerId, msgTypeString, payload)
// Check if sender is expected swap partner peer.
ok, err := s.isMessageSenderExpectedPeer(peerId, msg.SwapId)
if err != nil {
return err
}
if !ok {
return ErrReceivedMessageFromUnexpectedPeer(peerId, msg.SwapId)
}
err = s.OnCancelReceived(msg.SwapId, msg)
if err != nil {
return err
}
case messages.MESSAGETYPE_SWAPINREQUEST:
var msg *SwapInRequestMessage
err := json.Unmarshal(msgBytes, &msg)
if err != nil {
return err
}
s.logMsg(msg.SwapId.String(), peerId, msgTypeString, payload)
err = s.OnSwapInRequestReceived(msg.SwapId, peerId, msg)
if err != nil {
return err
}
case messages.MESSAGETYPE_SWAPINAGREEMENT:
var msg *SwapInAgreementMessage
err := json.Unmarshal(msgBytes, &msg)
if err != nil {
return err
}
s.logMsg(msg.SwapId.String(), peerId, msgTypeString, payload)
// Check if sender is expected swap partner peer.
ok, err := s.isMessageSenderExpectedPeer(peerId, msg.SwapId)
if err != nil {
return err
}
if !ok {
return ErrReceivedMessageFromUnexpectedPeer(peerId, msg.SwapId)
}
err = s.OnSwapInAgreementReceived(msg)
if err != nil {
return err
}
case messages.MESSAGETYPE_COOPCLOSE:
var msg *CoopCloseMessage
err := json.Unmarshal(msgBytes, &msg)
if err != nil {
return err
}
s.logMsg(msg.SwapId.String(), peerId, msgTypeString, payload)
// Check if sender is expected swap partner peer.
ok, err := s.isMessageSenderExpectedPeer(peerId, msg.SwapId)
if err != nil {
return err
}
if !ok {
return ErrReceivedMessageFromUnexpectedPeer(peerId, msg.SwapId)
}
err = s.OnCoopCloseReceived(msg.SwapId, msg)
if err != nil {
return err
}
}
return nil
}
// OnTxConfirmed sends the txconfirmed event to the corresponding swap
func (s *SwapService) OnTxConfirmed(swapId string, txHex string, gotErr error) error {
swap, err := s.GetActiveSwap(swapId)
if err != nil {
return err
}
// First check if we got an error!
if gotErr != nil {
swap.Data.LastErr = err
log.Infof("[%s]: got an error from the txwatcher, cancel swap: %v", swapId, err)
done, _ := swap.SendEvent(Event_ActionFailed, nil)
if done {
s.RemoveActiveSwap(swap.SwapId.String())
}
}
// todo move to eventctx
swap.Data.OpeningTxHex = txHex
done, err := swap.SendEvent(Event_OnTxConfirmed, nil)
if err == ErrEventRejected {
return nil
} else if err != nil {
return err
}
if done {
s.RemoveActiveSwap(swap.SwapId.String())
}
return nil
}
// OnCsvPassed sends the csvpassed event to the corresponding swap
func (s *SwapService) OnCsvPassed(swapId string) error {
swap, err := s.GetActiveSwap(swapId)
if errors.Is(err, ErrSwapDoesNotExist) {
return nil
}
if err != nil {
return err
}
done, err := swap.SendEvent(Event_OnCsvPassed, nil)
if err == ErrEventRejected {
return nil
} else if err != nil {
return err
}
if done {
s.RemoveActiveSwap(swap.SwapId.String())
}
return nil
}
// todo move wallet and chain / channel validation logic here
// SwapOut starts a new swap out process
func (s *SwapService) SwapOut(peer string, chain string, channelId string, initiator string, amtSat uint64, premiumLimitRatePpm int64) (*SwapStateMachine, error) {
if !s.swapServices.policy.NewSwapsAllowed() {
return nil, fmt.Errorf("swaps are disabled")
}
if s.swapServices.policy.IsPeerSuspicious(peer) {
return nil, PeerIsSuspiciousError(peer)
}
if amtSat*1000 < s.swapServices.policy.GetMinSwapAmountMsat() {
return nil, ErrMinimumSwapSize(s.swapServices.policy.GetMinSwapAmountMsat())
}
err := s.swapServices.lightning.CanSpend(amtSat * 1000)
if err != nil {
return nil, err
}
sp, err := s.swapServices.lightning.SpendableMsat(channelId)
if err != nil {
return nil, err
}
if sp < amtSat*1000 {
return nil, fmt.Errorf("exceeding spendable amount_msat: %d", sp)
}
swap := newSwapOutSenderFSM(s.swapServices, initiator, peer)
err = s.lockSwap(swap.SwapId.String(), channelId, swap)
if err != nil {
return nil, err
}
var bitcoinNetwork string
var elementsAsset string
if chain == l_btc_chain {
elementsAsset = s.swapServices.liquidWallet.GetAsset()
} else if chain == btc_chain {
bitcoinNetwork = s.swapServices.bitcoinWallet.GetNetwork()
} else {
return nil, errors.New("invalid chain")
}
request := &SwapOutRequestMessage{
ProtocolVersion: PEERSWAP_PROTOCOL_VERSION,
SwapId: swap.SwapId,
Asset: elementsAsset,
Network: bitcoinNetwork,
Scid: channelId,
Amount: amtSat,
Pubkey: hex.EncodeToString(swap.Data.GetPrivkey().PubKey().SerializeCompressed()),
PremiumLimit: premium.NewPPM(premiumLimitRatePpm).Compute(amtSat),
}
done, err := swap.SendEvent(Event_OnSwapOutStarted, request)
if err != nil {
return nil, err
}
if done {
s.RemoveActiveSwap(swap.SwapId.String())
}
return swap, nil
}
// todo check prerequisites
// SwapIn starts a new swap in process
func (s *SwapService) SwapIn(peer string, chain string, channelId string, initiator string, amtSat uint64, premiumLimitRatePPM int64) (*SwapStateMachine, error) {
if !s.swapServices.policy.NewSwapsAllowed() {
return nil, fmt.Errorf("swaps are disabled")
}
if s.swapServices.policy.IsPeerSuspicious(peer) {
return nil, PeerIsSuspiciousError(peer)
}
if amtSat*1000 < s.swapServices.policy.GetMinSwapAmountMsat() {
return nil, ErrMinimumSwapSize(s.swapServices.policy.GetMinSwapAmountMsat())
}
err := s.swapServices.lightning.CanSpend(amtSat * 1000)
if err != nil {
return nil, err
}
rs, err := s.swapServices.lightning.ReceivableMsat(channelId)
if err != nil {
return nil, err
}
if rs < amtSat*1000 {
return nil, fmt.Errorf("exceeding receivable amount_msat: %d", rs)
}
maximumSwapAmountSat, err := s.estimateMaximumSwapAmountSat(chain)
if err != nil {
return nil, err
}
if amtSat > maximumSwapAmountSat {
return nil, fmt.Errorf("exceeding maximum swap amount: %d", maximumSwapAmountSat)
}
var bitcoinNetwork string
var elementsAsset string
if chain == l_btc_chain {
elementsAsset = s.swapServices.liquidWallet.GetAsset()
} else if chain == btc_chain {
bitcoinNetwork = s.swapServices.bitcoinWallet.GetNetwork()
} else {
return nil, errors.New("invalid chain")
}
swap := newSwapInSenderFSM(s.swapServices, initiator, peer)
err = s.lockSwap(swap.SwapId.String(), channelId, swap)
if err != nil {
return nil, err
}
request := &SwapInRequestMessage{
ProtocolVersion: PEERSWAP_PROTOCOL_VERSION,
SwapId: swap.SwapId,
Asset: elementsAsset,
Network: bitcoinNetwork,
Scid: channelId,
Amount: amtSat,
Pubkey: hex.EncodeToString(swap.Data.GetPrivkey().PubKey().SerializeCompressed()),
PremiumLimit: premium.NewPPM(premiumLimitRatePPM).Compute(amtSat),
}
done, err := swap.SendEvent(Event_SwapInSender_OnSwapInRequested, request)
if err != nil {
return nil, err
}
if done {
s.RemoveActiveSwap(swap.SwapId.String())
}
return swap, nil
}
// estimateMaximumSwapAmountSat estimates the maximum swap amount
// in satoshis for the specified chain.
// This retrieves the on-chain balance and opening tx fee from the wallet,
// and calculates the maximum amount available for swapping.
func (s *SwapService) estimateMaximumSwapAmountSat(chain string) (uint64, error) {
if chain == l_btc_chain {
liquidBalance, err := s.swapServices.liquidWallet.GetOnchainBalance()
if err != nil {
return 0, err
}
// estimatedFee is the amount (in satoshis) of the fee for the opening transaction.
estimatedFee, err := s.swapServices.liquidWallet.GetFlatOpeningTXFee()
if err != nil {
return 0, err
}
// Calculate the available balance for swapping.
return liquidBalance - estimatedFee, nil
} else if chain == btc_chain {
bitcoinBalance, err := s.swapServices.bitcoinWallet.GetOnchainBalance()
if err != nil {
return 0, err
}
// estimatedFee is the amount (in satoshis) of the fee for the opening transaction.
estimatedFee, err := s.swapServices.bitcoinWallet.GetFlatOpeningTXFee()
if err != nil {
return 0, err
}
// Calculate the available balance for swapping.
return bitcoinBalance - estimatedFee, nil
}
return 0, errors.New("invalid chain")
}
// OnSwapInRequestReceived creates a new swap-in process and sends the event to the swap statemachine
func (s *SwapService) OnSwapInRequestReceived(swapId *SwapId, peerId string, message *SwapInRequestMessage) error {
var (
premiumValue int64
err error
)
// Network is the desired on-chain network to use. This can be:
// Bitcoin: mainnet, testnet, signet, regtest
// Liquid: The field is left blank as the asset id also defines the bitcoinNetwork.
if message.Network == "" {
premiumValue, err = s.swapServices.ps.Compute(peerId, premium.LBTC, premium.SwapIn, message.Amount)
if err != nil {
return err
}
} else {
premiumValue, err = s.swapServices.ps.Compute(peerId, premium.BTC, premium.SwapIn, message.Amount)
if err != nil {
return err
}
}
if premiumValue > message.PremiumLimit {
err := fmt.Errorf("unacceptable premium: %d, limit: %d", premiumValue, message.PremiumLimit)
msg := fmt.Sprintf("from the %s peer: %s", s.swapServices.lightning.Implementation(), err.Error())
// We want to tell our peer why we can not do this swap.
msgBytes, msgType, err := MarshalPeerswapMessage(&CancelMessage{
SwapId: swapId,
Message: msg,
})
s.swapServices.messenger.SendMessage(peerId, msgBytes, msgType)
return err
}
err = s.swapServices.lightning.CanSpend(message.Amount * 1000)
if err != nil {
msg := fmt.Sprintf("from the %s peer: %s", s.swapServices.lightning.Implementation(), err.Error())
// We want to tell our peer why we can not do this swap.
msgBytes, msgType, err := MarshalPeerswapMessage(&CancelMessage{
SwapId: swapId,
Message: msg,
})
s.swapServices.messenger.SendMessage(peerId, msgBytes, msgType)
return err
}
sp, err := s.swapServices.lightning.SpendableMsat(message.Scid)
if err != nil {
msg := fmt.Sprintf("from the %s peer: %s", s.swapServices.lightning.Implementation(), err.Error())
// We want to tell our peer why we can not do this swap.
msgBytes, msgType, err := MarshalPeerswapMessage(&CancelMessage{
SwapId: swapId,
Message: msg,
})
s.swapServices.messenger.SendMessage(peerId, msgBytes, msgType)
return err
}
if sp < message.Amount*1000 {
err = fmt.Errorf("exceeding spendable amount_msat: %d", sp)
msg := fmt.Sprintf("from the %s peer: %s", s.swapServices.lightning.Implementation(), err.Error())
// We want to tell our peer why we can not do this swap.
msgBytes, msgType, err := MarshalPeerswapMessage(&CancelMessage{
SwapId: swapId,
Message: msg,
})
s.swapServices.messenger.SendMessage(peerId, msgBytes, msgType)
return err
}
success, failureReason, err := s.swapServices.lightning.ProbePayment(message.Scid, message.Amount*1000)
if err != nil {
msg := fmt.Sprintf("from the %s peer: %s", s.swapServices.lightning.Implementation(), err.Error())
// We want to tell our peer why we can not do this swap.
msgBytes, msgType, err := MarshalPeerswapMessage(&CancelMessage{
SwapId: swapId,
Message: msg,
})
s.swapServices.messenger.SendMessage(peerId, msgBytes, msgType)
return err
}
if !success {
// We want to tell our peer why we can not do this swap.
msgBytes, msgType, err := MarshalPeerswapMessage(&CancelMessage{
SwapId: swapId,
Message: "The prepayment probe was unsuccessful." + failureReason,
})
s.swapServices.messenger.SendMessage(peerId, msgBytes, msgType)
return err
}
swap := newSwapInReceiverFSM(swapId, s.swapServices, peerId)
err = s.lockSwap(swap.SwapId.String(), message.Scid, swap)
if err != nil {
// If we already have an active swap on the same channel or can not lock
// in a new swap we want to tell it our peer.
msgBytes, msgType, err := MarshalPeerswapMessage(&CancelMessage{
SwapId: swapId,
Message: err.Error(),
})
s.swapServices.messenger.SendMessage(peerId, msgBytes, msgType)
return err
}
done, err := swap.SendEvent(Event_SwapInReceiver_OnRequestReceived, message)
if done {
s.RemoveActiveSwap(swap.SwapId.String())
}
return err
}
// OnSwapOutRequestReceived creates a new swap-out process and sends the event to the swap statemachine
func (s *SwapService) OnSwapOutRequestReceived(swapId *SwapId, peerId string, message *SwapOutRequestMessage) error {
var (
premiumValue int64
err error
)
// Network is the desired on-chain network to use. This can be:
// Bitcoin: mainnet, testnet, signet, regtest
// Liquid: The field is left blank as the asset id also defines the bitcoinNetwork.
if message.Network == "" {
premiumValue, err = s.swapServices.ps.Compute(peerId, premium.LBTC, premium.SwapOut, message.Amount)
if err != nil {
return err
}
} else {
premiumValue, err = s.swapServices.ps.Compute(peerId, premium.BTC, premium.SwapOut, message.Amount)
if err != nil {
return err
}
}
if premiumValue > message.PremiumLimit {
err := fmt.Errorf("unacceptable premium: %d, limit: %d", premiumValue, message.PremiumLimit)
msg := fmt.Sprintf("from the %s peer: %s", s.swapServices.lightning.Implementation(), err.Error())
// We want to tell our peer why we can not do this swap.
msgBytes, msgType, err := MarshalPeerswapMessage(&CancelMessage{
SwapId: swapId,
Message: msg,
})
s.swapServices.messenger.SendMessage(peerId, msgBytes, msgType)
return err
}
rs, err := s.swapServices.lightning.ReceivableMsat(message.Scid)
if err != nil {
msg := fmt.Sprintf("from the %s peer: %s", s.swapServices.lightning.Implementation(), err.Error())
// We want to tell our peer why we can not do this swap.
msgBytes, msgType, err := MarshalPeerswapMessage(&CancelMessage{
SwapId: swapId,
Message: msg,
})
s.swapServices.messenger.SendMessage(peerId, msgBytes, msgType)
return err
}
if rs < message.Amount*1000 {
err = fmt.Errorf("exceeding receivable amount_msat: %d", rs)
msg := fmt.Sprintf("from the %s peer: %s", s.swapServices.lightning.Implementation(), err.Error())
// We want to tell our peer why we can not do this swap.
msgBytes, msgType, err := MarshalPeerswapMessage(&CancelMessage{
SwapId: swapId,
Message: msg,
})
s.swapServices.messenger.SendMessage(peerId, msgBytes, msgType)
return err
}
swap := newSwapOutReceiverFSM(swapId, s.swapServices, peerId)
err = s.lockSwap(swap.SwapId.String(), message.Scid, swap)
if err != nil {
// If we already have an active swap on the same channel or can not lock
// in a new swap we want to tell it our peer.
msgBytes, msgType, err := MarshalPeerswapMessage(&CancelMessage{
SwapId: swapId,
Message: err.Error(),
})
s.swapServices.messenger.SendMessage(peerId, msgBytes, msgType)
return err
}
done, err := swap.SendEvent(Event_OnSwapOutRequestReceived, message)
if err != nil {
return err
}
if done {
s.RemoveActiveSwap(swap.SwapId.String())
}
return nil
}
// OnSwapInAgreementReceived sends the agreementreceived event to the corresponding swap state machine
func (s *SwapService) OnSwapInAgreementReceived(msg *SwapInAgreementMessage) error {
swap, err := s.GetActiveSwap(msg.SwapId.String())
if err != nil {
return err
}
done, err := swap.SendEvent(Event_SwapInSender_OnAgreementReceived, msg)
if err != nil {
return err
}
if done {
s.RemoveActiveSwap(swap.SwapId.String())
}
return nil
}
// OnSwapOutAgreementReceived sends the FeeInvoiceReceived event to the corresponding swap state machine
func (s *SwapService) OnSwapOutAgreementReceived(message *SwapOutAgreementMessage) error {
swap, err := s.GetActiveSwap(message.SwapId.String())
if err != nil {
return err
}
done, err := swap.SendEvent(Event_OnFeeInvoiceReceived, message)
if err != nil {
return err
}
if done {
s.RemoveActiveSwap(swap.SwapId.String())
}
return nil
}
// OnFeeInvoiceNotification sends the FeeInvoicePaid event to the corresponding swap state machine
func (s *SwapService) OnFeeInvoiceNotification(swapId *SwapId) error {
swap, err := s.GetActiveSwap(swapId.String())
if err != nil {
return err
}
done, err := swap.SendEvent(Event_OnFeeInvoicePaid, nil)
if err != nil {
return err
}
if done {
s.RemoveActiveSwap(swap.SwapId.String())
}
return nil
}
// OnClaimInvoiceNotification sends the ClaimInvoicePaid event to the corresponding swap state machine
func (s *SwapService) OnClaimInvoiceNotification(swapId *SwapId) error {
swap, err := s.GetActiveSwap(swapId.String())
if err != nil {
return err
}
done, err := swap.SendEvent(Event_OnClaimInvoicePaid, nil)
if err != nil {
return err
}
if done {
s.RemoveActiveSwap(swap.SwapId.String())
}
return nil
}
// OnTxOpenedMessage sends the TxOpenedMessage event to the corresponding swap state machine
func (s *SwapService) OnTxOpenedMessage(message *OpeningTxBroadcastedMessage) error {
swap, err := s.GetActiveSwap(message.SwapId.String())
if err != nil {
return err
}
done, err := swap.SendEvent(Event_OnTxOpenedMessage, message)
if err != nil {
return err
}
if done {
s.RemoveActiveSwap(swap.SwapId.String())
}
return nil
}
// OnTxOpenedMessage sends the TxConfirmed event to the corresponding swap state machine
func (s *SwapService) SenderOnTxConfirmed(swapId string) error {
swap, err := s.GetActiveSwap(swapId)
if err != nil {
return err
}
done, err := swap.SendEvent(Event_OnTxConfirmed, nil)
if err != nil {
return err
}
if done {
s.RemoveActiveSwap(swap.SwapId.String())
}
s.RemoveActiveSwap(swap.SwapId.String())
return nil
}
const PaymentLabelSeparator = "_"
func getPaymentLabel(description string) string {
parts := strings.SplitN(description, PaymentLabelSeparator, 2)
if len(parts) != 2 {
return ""
}
return parts[0]
}
// OnPayment handles incoming payments and if it corresponds to a claim or
// fee invoice passes the dater to the corresponding function
func (s *SwapService) OnPayment(swapIdStr string, invoiceType InvoiceType) {
swapId, err := ParseSwapIdFromString(swapIdStr)
if err != nil {
log.Infof("parse swapId error")
return
}
// Check for claim_ label
switch invoiceType {
case INVOICE_FEE:
if err := s.OnFeeInvoiceNotification(swapId); err != nil {
log.Infof("[SwapService] Error OnFeeInvoiceNotification: %v", err)
return
}
case INVOICE_CLAIM:
if err := s.OnClaimInvoiceNotification(swapId); err != nil {
log.Infof("[SwapService] Error OnClaimInvoiceNotification: %v", err)
return
}
default:
return
}
}
// OnCancelReceived sends the CancelReceived event to the corresponding swap state machine
func (s *SwapService) OnCancelReceived(swapId *SwapId, cancelMsg *CancelMessage) error {
swap, err := s.GetActiveSwap(swapId.String())
if err != nil {
return err
}
done, err := swap.SendEvent(Event_OnCancelReceived, cancelMsg)
if err != nil {
return err
}
if done {
s.RemoveActiveSwap(swap.SwapId.String())
}
return nil
}
// OnCoopCloseReceived sends the CoopMessage event to the corresponding swap state mahcine
func (s *SwapService) OnCoopCloseReceived(swapId *SwapId, coopCloseMessage *CoopCloseMessage) error {
swap, err := s.GetActiveSwap(swapId.String())
if err != nil {
return err
}
done, err := swap.SendEvent(Event_OnCoopCloseReceived, coopCloseMessage)
if err != nil {
return err
}
if done {
s.RemoveActiveSwap(swap.SwapId.String())
}
return nil
}
// ListSwaps returns all swaps stored
func (s *SwapService) ListSwaps() ([]*SwapStateMachine, error) {
return s.swapServices.swapStore.ListAll()
}
// ListSwapsByPeer only returns the swaps that are done with a specific peer
func (s *SwapService) ListSwapsByPeer(peer string) ([]*SwapStateMachine, error) {
return s.swapServices.swapStore.ListAllByPeer(peer)
}
func (s *SwapService) GetSwap(swapId string) (*SwapStateMachine, error) {
return s.swapServices.swapStore.GetData(swapId)
}
func (s *SwapService) ResendLastMessage(swapId string) error {
swap, err := s.GetActiveSwap(swapId)
if err != nil {
return err
}
action := &SendMessageAction{}
event := action.Execute(s.swapServices, swap.Data)
if event == Event_ActionFailed {
return swap.Data.LastErr
}
return nil
}
func (s *SwapService) ListActiveSwaps() ([]*SwapStateMachine, error) {
swaps, err := s.swapServices.swapStore.ListAll()
if err != nil {
return nil, err
}
activeSwaps := []*SwapStateMachine{}
for _, swap := range swaps {
if swap.IsFinished() {
continue
}
activeSwaps = append(activeSwaps, swap)
}
return activeSwaps, nil
}
// GetActiveSwap returns the active swap, or an error if it does not exist
func (s *SwapService) GetActiveSwap(swapId string) (*SwapStateMachine, error) {
s.RLock()
defer s.RUnlock()
if swap, ok := s.activeSwaps[swapId]; ok {
return swap, nil
}
return nil, ErrSwapDoesNotExist
}
// RemoveActiveSwap removes a swap from the active swap map
func (s *SwapService) RemoveActiveSwap(swapId string) {
s.Lock()
defer s.Unlock()
delete(s.lastMsgLog, swapId)
delete(s.activeSwaps, swapId)
}
// lockSwap locks in a swap. This function ensures that we only have one active
// swap on a channel as required by the protocol.
// Returns an error if the swap is already locked.
func (s *SwapService) lockSwap(swapId, channelId string, fsm *SwapStateMachine) error {
s.Lock()
defer s.Unlock()
// Check if we already have an active swap on the same channel
for id, swap := range s.activeSwaps {
if swap.Data.GetScid() == channelId {
return ActiveSwapError{channelId: channelId, swapId: id}
}
}
// Add active swap
s.activeSwaps[swapId] = fsm
return nil
}
type ActiveSwapError struct {
channelId string
swapId string
}
func (e ActiveSwapError) Error() string {
return fmt.Sprintf("already has an active swap on channel %s: %s", e.channelId, e.swapId)
}
type WrongAssetError string
func (e WrongAssetError) Error() string {
return fmt.Sprintf("unallowed asset: %s", string(e))
}