-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathSwaps.ts
1643 lines (1497 loc) · 61.2 KB
/
Swaps.ts
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
import assert from 'assert';
import poissonQuantile from 'distributions-poisson-quantile';
import { EventEmitter } from 'events';
import { ReputationEvent, SwapFailureReason, SwapPhase, SwapRole, SwapState } from '../constants/enums';
import { Models } from '../db/DB';
import { SwapDealInstance } from '../db/types';
import Logger from '../Logger';
import { OwnOrder, PeerOrder } from '../orderbook/types';
import { PacketType } from '../p2p/packets';
import * as packets from '../p2p/packets/types';
import Peer from '../p2p/Peer';
import Pool from '../p2p/Pool';
import { generatePreimageAndHash } from '../utils/cryptoUtils';
import { UnitConverter } from '../utils/UnitConverter';
import { setTimeoutPromise } from '../utils/utils';
import { MAX_PAYMENT_TIME } from './consts';
import errors, { errorCodes } from './errors';
import SwapClient, { PaymentState } from './SwapClient';
import SwapClientManager from './SwapClientManager';
import SwapRecovery from './SwapRecovery';
import SwapRepository from './SwapRepository';
import { ResolveRequest, Route, SanitySwap, SwapAccepted, SwapDeal, SwapSuccess } from './types';
export type OrderToAccept = Pick<SwapDeal, 'quantity' | 'price' | 'localId' | 'isBuy'> & {
quantity: number;
};
interface Swaps {
on(event: 'swap.accepted', listener: (swapSuccess: SwapAccepted) => void): this;
on(event: 'swap.paid', listener: (swapSuccess: SwapSuccess) => void): this;
on(event: 'swap.failed', listener: (deal: SwapDeal) => void): this;
on(event: 'swap.recovered', listener: (recoveredSwap: SwapDealInstance) => void): this;
emit(event: 'swap.accepted', swapSuccess: SwapAccepted): boolean;
emit(event: 'swap.paid', swapSuccess: SwapSuccess): boolean;
emit(event: 'swap.failed', deal: SwapDeal): boolean;
emit(event: 'swap.recovered', recoveredSwap: SwapDealInstance): boolean;
}
class Swaps extends EventEmitter {
public swapClientManager: SwapClientManager;
/** A map between payment hashes and pending sanity swaps. */
private sanitySwaps = new Map<string, SanitySwap>();
private logger: Logger;
private models: Models;
private pool: Pool;
private strict: boolean;
/** A map between payment hashes and swap deals. */
private deals = new Map<string, SwapDeal>();
private swapRecovery: SwapRecovery;
/** A map between payment hashes and timeouts for swaps. */
private timeouts = new Map<string, number>();
private usedHashes = new Set<string>();
private repository: SwapRepository;
private unitConverter: UnitConverter;
/** The maximum time in milliseconds we will wait for a swap to be accepted before failing it. */
private static readonly SWAP_ACCEPT_TIMEOUT = 10000;
/** The maximum time in milliseconds we will wait for a swap to be completed before failing it. */
private static readonly SWAP_COMPLETE_TIMEOUT = MAX_PAYMENT_TIME;
/**
* Additional time that the maker will wait for a swap to be completed before considering it timed
* out. This exists because the maker starts timing sooner and ends timing later than the taker.
* The maker starts timing as soon as it sends its SwapAccepted packet, but taker starts upon
* receiving that packet some short time later. Furthermore, the taker stops the timer as soon as
* it reveals the preimage and settles its incoming payment, whereas the maker doesn't stop until
* it receives the preimage.
*/
private static readonly SWAP_COMPLETE_MAKER_BUFFER = 5000;
/**
* The time threshold in milliseconds after which we consider a counterparty abusive if they
* settle payment for a timed out swap.
*/
private static readonly SWAP_ABUSE_TIME_LIMIT = 60000;
/** The maximum time in milliseconds we will wait to receive an expected sanity swap init packet. */
private static readonly SANITY_SWAP_INIT_TIMEOUT = 3000;
/** The maximum time in milliseconds we will wait for a swap to be completed before failing it. */
private static readonly SANITY_SWAP_COMPLETE_TIMEOUT = 10000;
constructor({
logger,
models,
pool,
swapClientManager,
unitConverter,
strict = true,
}: {
logger: Logger;
models: Models;
pool: Pool;
swapClientManager: SwapClientManager;
unitConverter: UnitConverter;
strict?: boolean;
}) {
super();
this.logger = logger;
this.models = models;
this.pool = pool;
this.swapClientManager = swapClientManager;
this.unitConverter = unitConverter;
this.strict = strict;
this.swapRecovery = new SwapRecovery(swapClientManager, logger.createSubLogger('RECOVERY'));
this.repository = new SwapRepository(this.models);
this.bind();
}
/**
* Checks if a swap request is valid. This is a shallow check that only detects critical
* inconsistencies and verifies only whether the request can possibly lead to a successful swap.
* @returns `true` if the request is valid, otherwise `false`
*/
public static validateSwapRequest = ({ proposedQuantity, rHash }: packets.SwapRequestPacketBody) => {
// proposed quantity must be a positive number
// rHash must be exactly 64 characters
return proposedQuantity > 0 && rHash.length === 64;
};
/**
* Calculates the minimum expected lock delta for the final hop of the first leg to ensure a
* very high probability that it won't expire before the second leg payment. We use a Poisson
* distribution to model the possible block times of two independent chains, first calculating
* a probabilistic upper bound for the lock time in minuntes of the second leg then a
* probabilistic lower bound for the number of blocks for the lock time extended to the final
* hop of the first leg.
* @param secondLegLockDuration The lock duration (aka time lock or cltv delta) of the second
* leg (maker to taker) denominated in blocks of that chain.
* @returns A number of blocks for the chain of the first leg that is highly likely to take
* more time in minutes than the provided second leg lock duration.
*/
private static calculateLockBuffer = (
secondLegLockDuration: number,
secondLegMinutesPerBlock: number,
firstLegMinutesPerBlock: number,
) => {
/** A probabilistic upper bound for the time it will take for the second leg route time lock to expire. */
const secondLegLockMinutes = poissonQuantile(0.9999, { lambda: secondLegLockDuration }) * secondLegMinutesPerBlock;
const firstLegLockBuffer = poissonQuantile(0.9999, { lambda: secondLegLockMinutes / firstLegMinutesPerBlock });
return firstLegLockBuffer;
};
/**
* Calculates the currencies and amounts of subunits/satoshis each side of a swap should receive.
* @param quantity The quantity being swapped
* @param price The price for the swap
* @param isBuy Whether the maker order in the swap is a buy
* @returns An object with the calculated maker and taker values.
*/
private calculateMakerTakerAmounts = (quantity: number, price: number, isBuy: boolean, pairId: string) => {
const {
inboundCurrency,
inboundAmount,
inboundUnits,
outboundCurrency,
outboundAmount,
outboundUnits,
} = this.unitConverter.calculateInboundOutboundAmounts(quantity, price, isBuy, pairId);
return {
makerCurrency: inboundCurrency,
makerAmount: inboundAmount,
makerUnits: inboundUnits,
takerCurrency: outboundCurrency,
takerAmount: outboundAmount,
takerUnits: outboundUnits,
};
};
public init = async () => {
// update pool with current lnd & connext pubkeys
this.swapClientManager.getLndClientsMap().forEach(({ pubKey, chain, currency, uris }) => {
if (pubKey && chain) {
this.pool.updateLndState({
currency,
pubKey,
chain,
uris,
});
}
});
if (this.swapClientManager.connextClient) {
this.pool.updateConnextState(
this.swapClientManager.connextClient.tokenAddresses,
this.swapClientManager.connextClient.publicIdentifier,
);
}
this.swapRecovery.beginTimer();
const swapDealInstances = await this.repository.getSwapDeals();
swapDealInstances.forEach((deal: SwapDealInstance) => {
this.usedHashes.add(deal.rHash);
if (deal.state === SwapState.Active) {
this.swapRecovery.recoverDeal(deal).catch(this.logger.error);
}
});
};
private bind() {
this.pool.on('packet.sanitySwapInit', async (packet, peer) => {
const { currency, rHash } = packet.body!;
const sanitySwap: SanitySwap = {
currency,
rHash,
peerPubKey: peer.nodePubKey!,
};
this.sanitySwaps.set(rHash, sanitySwap);
const swapClient = this.swapClientManager.get(currency)!;
try {
await swapClient.addInvoice({ rHash, units: 1n });
} catch (err) {
this.logger.error('could not add invoice for sanity swap', err);
return;
}
await peer.sendPacket(new packets.SanitySwapAckPacket(undefined, packet.header.id));
// set timeout limit for sanity swap to complete, fail it if it stalls
await setTimeoutPromise(Swaps.SANITY_SWAP_COMPLETE_TIMEOUT);
if (this.sanitySwaps.delete(rHash)) {
// if we're here, it means the sanity swap has not completed within the time limit
swapClient.removeInvoice(rHash).catch(this.logger.error);
}
});
this.pool.on('packet.swapAccepted', this.handleSwapAccepted);
this.pool.on('packet.swapFailed', this.handleSwapFailed);
this.swapClientManager.on('htlcAccepted', this.handleHtlcAccepted);
this.swapClientManager.on('lndUpdate', this.pool.updateLndState);
this.swapClientManager.on('connextUpdate', this.pool.updateConnextState);
this.swapRecovery.on('recovered', (recoveredSwap) => {
this.emit('swap.recovered', recoveredSwap);
});
}
/**
* Checks if there are connected swap clients for both currencies in a given trading pair.
* @returns `undefined` if both currencies are active, otherwise the ticker symbol for an inactive currency.
*/
public checkInactiveCurrencyClients = (pairId: string): string | undefined => {
// TODO: these checks are happening on a per-swap basis, it would be more efficient to
// check up front and disable currencies for inactive swap clients when we detect they
// become disconnected, then re-enable once they reconnect.
const [baseCurrency, quoteCurrency] = pairId.split('/');
const baseCurrencyClient = this.swapClientManager.get(baseCurrency);
if (baseCurrencyClient === undefined || !baseCurrencyClient.isConnected()) {
return baseCurrency;
}
const quoteCurrencyClient = this.swapClientManager.get(quoteCurrency);
if (quoteCurrencyClient === undefined || !quoteCurrencyClient.isConnected()) {
return quoteCurrency;
}
return undefined;
};
/**
* Sends a swap failed packet to the counterparty peer in a swap with details about the error
* that caused the failure. Sets reqId if packet is a response to a request.
*/
private sendErrorToPeer = async ({
peer,
rHash,
failureReason = SwapFailureReason.UnknownError,
errorMessage,
reqId,
}: {
peer: Peer;
rHash: string;
failureReason?: SwapFailureReason;
errorMessage?: string;
reqId?: string;
}) => {
const errorBody: packets.SwapFailedPacketBody = {
rHash,
failureReason,
errorMessage,
};
this.logger.debug(
`Sending ${SwapFailureReason[errorBody.failureReason]} error to peer: ${JSON.stringify(errorBody)}`,
);
await peer.sendPacket(new packets.SwapFailedPacket(errorBody, reqId));
};
/**
* Saves deal to database and deletes it from memory if it is no longer active.
* @param deal The deal to persist.
*/
private persistDeal = async (deal: SwapDeal) => {
await this.repository.saveSwapDeal(deal);
if (deal.state !== SwapState.Active) {
this.deals.delete(deal.rHash);
}
};
public getPendingSwapHashes = () => {
return this.swapRecovery.getPendingSwapHashes();
};
/**
* Gets a deal by its rHash value.
* @param rHash The rHash value of the deal to get.
* @returns A deal if one is found, otherwise undefined.
*/
public getDeal = (rHash: string): SwapDeal | undefined => {
return this.deals.get(rHash);
};
public addDeal = (deal: SwapDeal) => {
this.deals.set(deal.rHash, deal);
this.usedHashes.add(deal.rHash);
this.logger.debug(
`New deal: ${JSON.stringify({
...deal,
makerUnits: deal.makerUnits.toString(),
takerUnits: deal.takerUnits.toString(),
})}`,
);
};
/**
* Checks if a swap for two given orders can be executed by ensuring both swap clients are active
* and if there exists a route to the maker.
* @param maker maker order
* @param taker taker order
* @returns `void` if the swap can be executed, throws a [[SwapFailureReason]] otherwise
*/
private verifyExecution = async (maker: PeerOrder, taker: OwnOrder): Promise<void> => {
if (maker.pairId !== taker.pairId) {
throw SwapFailureReason.InvalidOrders;
}
if (this.checkInactiveCurrencyClients(maker.pairId)) {
throw SwapFailureReason.SwapClientNotSetup;
}
const { makerCurrency, makerUnits } = this.calculateMakerTakerAmounts(
taker.quantity,
maker.price,
maker.isBuy,
maker.pairId,
);
const swapClient = this.swapClientManager.get(makerCurrency)!;
const peer = this.pool.getPeer(maker.peerPubKey);
const destination = peer.getIdentifier(swapClient.type, makerCurrency);
if (!destination) {
throw SwapFailureReason.SwapClientNotSetup;
}
let route: Route | undefined;
try {
route = await swapClient.getRoute(makerUnits, destination, makerCurrency);
} catch (err) {
if (err === errors.INSUFFICIENT_BALANCE) {
throw SwapFailureReason.InsufficientBalance;
}
throw SwapFailureReason.UnexpectedClientError;
}
if (!route) {
throw SwapFailureReason.NoRouteFound;
}
};
/**
* A promise wrapper for a swap procedure
* @param maker the remote maker order we are filling
* @param taker our local taker order
* @returns A promise that resolves to a [[SwapSuccess]] once the swap is completed, throws a [[SwapFailureReason]] if it fails
*/
public executeSwap = async (maker: PeerOrder, taker: OwnOrder): Promise<SwapSuccess> => {
await this.verifyExecution(maker, taker);
const rHash = await this.beginSwap(maker, taker);
return new Promise<SwapSuccess>((resolve, reject) => {
const cleanup = () => {
this.removeListener('swap.paid', onPaid);
this.removeListener('swap.failed', onFailed);
};
const onPaid = (swapSuccess: SwapSuccess) => {
if (swapSuccess.rHash === rHash) {
cleanup();
resolve(swapSuccess);
}
};
const onFailed = (deal: SwapDeal) => {
if (deal.rHash === rHash) {
cleanup();
reject(deal.failureReason!);
}
};
this.on('swap.paid', onPaid);
this.on('swap.failed', onFailed);
});
};
/**
* Executes a sanity swap with a peer for a specified currency.
* @returns `true` if the swap succeeds, otherwise `false`
*/
public executeSanitySwap = async (currency: string, peer: Peer) => {
const { rPreimage, rHash } = await generatePreimageAndHash();
const peerPubKey = peer.nodePubKey!;
const swapClient = this.swapClientManager.get(currency);
if (!swapClient) {
return false;
}
const destination = peer.getIdentifier(swapClient.type, currency);
if (!destination) {
return false;
}
const sanitySwap: SanitySwap = {
rHash,
rPreimage,
currency,
peerPubKey,
};
this.sanitySwaps.set(rHash, sanitySwap);
const sanitySwapInitPacket = new packets.SanitySwapInitPacket({
currency,
rHash,
});
try {
await Promise.all([
swapClient.addInvoice({ rHash, units: 1n }),
peer.sendPacket(sanitySwapInitPacket),
peer.wait(sanitySwapInitPacket.header.id, PacketType.SanitySwapAck, Swaps.SANITY_SWAP_INIT_TIMEOUT),
]);
} catch (err) {
this.logger.warn(`sanity swap could not be initiated for ${currency} using rHash ${rHash}: ${err.message}`);
swapClient.removeInvoice(rHash).catch(this.logger.error);
return false;
}
try {
await swapClient.sendSmallestAmount(rHash, destination, currency);
this.logger.debug(
`performed successful sanity swap with peer ${peerPubKey} for ${currency} using rHash ${rHash}`,
);
return true;
} catch (err) {
this.logger.warn(
`got payment error during sanity swap with ${peerPubKey} for ${currency} using rHash ${rHash}: ${err.message}`,
);
swapClient.removeInvoice(rHash).catch(this.logger.error);
return false;
}
};
/**
* Begins a swap to fill an order by sending a [[SwapRequestPacket]] to the maker.
* @param maker The remote maker order we are filling
* @param taker Our local taker order
* @returns The rHash for the swap, or a [[SwapFailureReason]] if the swap could not be initiated
*/
private beginSwap = async (maker: PeerOrder, taker: OwnOrder): Promise<string> => {
const peer = this.pool.getPeer(maker.peerPubKey);
const quantity = Math.min(maker.quantity, taker.quantity);
const {
makerCurrency,
makerAmount,
makerUnits,
takerCurrency,
takerAmount,
takerUnits,
} = this.calculateMakerTakerAmounts(quantity, maker.price, maker.isBuy, maker.pairId);
const clientType = this.swapClientManager.get(makerCurrency)!.type;
const destination = peer.getIdentifier(clientType, makerCurrency)!;
const takerCltvDelta = this.swapClientManager.get(takerCurrency)!.finalLock;
const { rPreimage, rHash } = await generatePreimageAndHash();
const swapRequestBody: packets.SwapRequestPacketBody = {
takerCltvDelta,
rHash,
orderId: maker.id,
pairId: maker.pairId,
proposedQuantity: taker.quantity,
};
const deal: SwapDeal = {
...swapRequestBody,
rPreimage,
takerCurrency,
makerCurrency,
takerAmount,
makerAmount,
takerUnits,
makerUnits,
destination,
peerPubKey: peer.nodePubKey!,
localId: taker.localId,
price: maker.price,
isBuy: maker.isBuy,
phase: SwapPhase.SwapCreated,
state: SwapState.Active,
role: SwapRole.Taker,
createTime: Date.now(),
};
this.addDeal(deal);
// Make sure we are connected to both swap clients
const inactiveCurrency = this.checkInactiveCurrencyClients(deal.pairId);
if (inactiveCurrency) {
await this.failDeal({
deal,
failureReason: SwapFailureReason.SwapClientNotSetup,
failedCurrency: inactiveCurrency,
});
throw SwapFailureReason.SwapClientNotSetup;
}
await peer.sendPacket(new packets.SwapRequestPacket(swapRequestBody));
await this.setDealPhase(deal, SwapPhase.SwapRequested);
return deal.rHash;
};
/**
* Accepts a proposed deal for a specified amount if a route and CLTV delta could be determined
* for the swap. Stores the deal in the local collection of deals.
* @returns A promise resolving to `true` if the deal was accepted, `false` otherwise.
*/
public acceptDeal = async (
orderToAccept: OrderToAccept,
requestPacket: packets.SwapRequestPacket,
peer: Peer,
): Promise<boolean> => {
// TODO: max cltv to limit routes
// TODO: consider the time gap between taking the routes and using them.
this.logger.debug(`trying to accept deal: ${JSON.stringify(orderToAccept)} from xudPubKey: ${peer.nodePubKey}`);
const { rHash, proposedQuantity, pairId, takerCltvDelta, orderId } = requestPacket.body!;
const reqId = requestPacket.header.id;
if (this.usedHashes.has(rHash)) {
await this.sendErrorToPeer({
peer,
rHash,
reqId,
failureReason: SwapFailureReason.PaymentHashReuse,
});
return false;
}
const { quantity, price, isBuy } = orderToAccept;
const {
makerCurrency,
makerAmount,
makerUnits,
takerCurrency,
takerAmount,
takerUnits,
} = this.calculateMakerTakerAmounts(quantity, price, isBuy, pairId);
const makerSwapClient = this.swapClientManager.get(makerCurrency)!;
if (!makerSwapClient) {
await this.sendErrorToPeer({
peer,
rHash,
reqId,
failureReason: SwapFailureReason.SwapClientNotSetup,
errorMessage: 'Unsupported maker currency',
});
return false;
}
const takerSwapClient = this.swapClientManager.get(takerCurrency);
if (!takerSwapClient) {
await this.sendErrorToPeer({
peer,
rHash,
reqId,
failureReason: SwapFailureReason.SwapClientNotSetup,
errorMessage: 'Unsupported taker currency',
});
return false;
}
// Make sure we are connected to swap clients for both currencies
const inactiveCurrency = this.checkInactiveCurrencyClients(pairId);
if (inactiveCurrency) {
await this.sendErrorToPeer({
peer,
rHash,
reqId,
failureReason: SwapFailureReason.SwapClientNotSetup,
errorMessage: `${inactiveCurrency} is inactive`,
});
return false;
}
const takerIdentifier = peer.getIdentifier(takerSwapClient.type, takerCurrency)!;
const deal: SwapDeal = {
rHash,
pairId,
proposedQuantity,
orderId,
price,
isBuy,
quantity,
makerAmount,
takerAmount,
makerCurrency,
takerCurrency,
makerUnits,
takerUnits,
takerCltvDelta,
takerPubKey: takerIdentifier,
destination: takerIdentifier,
peerPubKey: peer.nodePubKey!,
localId: orderToAccept.localId,
phase: SwapPhase.SwapCreated,
state: SwapState.Active,
role: SwapRole.Maker,
createTime: Date.now(),
};
// add the deal. Going forward we can "record" errors related to this deal.
this.addDeal(deal);
let makerToTakerRoute: Route | undefined;
try {
makerToTakerRoute = await takerSwapClient.getRoute(
takerUnits,
takerIdentifier,
deal.takerCurrency,
deal.takerCltvDelta,
);
} catch (err) {
await this.failDeal({
deal,
peer,
reqId,
failureReason:
err === errors.INSUFFICIENT_BALANCE
? SwapFailureReason.InsufficientBalance
: SwapFailureReason.UnexpectedClientError,
errorMessage: err.message,
failedCurrency: deal.takerCurrency,
});
return false;
}
if (!makerToTakerRoute) {
await this.failDeal({
deal,
peer,
reqId,
failureReason: SwapFailureReason.NoRouteFound,
errorMessage: 'Unable to find route to destination',
failedCurrency: deal.takerCurrency,
});
return false;
}
let height: number;
try {
height = await takerSwapClient.getHeight();
} catch (err) {
await this.failDeal({
deal,
peer,
reqId,
failureReason: SwapFailureReason.UnexpectedClientError,
errorMessage: `Unable to fetch block height: ${err.message}`,
failedCurrency: takerCurrency,
});
return false;
}
if (height) {
this.logger.debug(`got ${takerCurrency} block height of ${height}`);
const routeTotalTimeLock = makerToTakerRoute.getTotalTimeLock();
const routeLockDuration = routeTotalTimeLock - height;
const routeLockHours = Math.round((routeLockDuration * takerSwapClient.minutesPerBlock) / 60);
this.logger.debug(
`found route to taker with total lock duration of ${routeLockDuration} ${takerCurrency} blocks (~${routeLockHours}h)`,
);
// Add an additional buffer equal to our final lock to allow for more possible routes.
deal.takerMaxTimeLock = routeLockDuration + takerSwapClient.finalLock;
// Here we calculate the minimum lock delta we will expect as maker on the final hop to us on
// the first leg of the swap. This should ensure a very high probability that the final hop
// of the payment to us won't expire before our payment to the taker with time leftover to
// satisfy our finalLock/cltvDelta requirement for the incoming payment swap client.
const lockBuffer = Swaps.calculateLockBuffer(
deal.takerMaxTimeLock,
takerSwapClient.minutesPerBlock,
makerSwapClient.minutesPerBlock,
);
const lockBufferHours = Math.round((lockBuffer * makerSwapClient.minutesPerBlock) / 60);
this.logger.debug(
`calculated lock buffer for first leg: ${lockBuffer} ${makerCurrency} blocks (~${lockBufferHours}h)`,
);
deal.makerCltvDelta = lockBuffer + makerSwapClient.finalLock;
const makerCltvDeltaHours = Math.round((deal.makerCltvDelta * makerSwapClient.minutesPerBlock) / 60);
this.logger.debug(
`lock delta for final hop to maker: ${deal.makerCltvDelta} ${makerCurrency} blocks (~${makerCltvDeltaHours}h)`,
);
}
if (!deal.makerCltvDelta) {
await this.failDeal({
deal,
peer,
reqId,
failedCurrency: makerCurrency,
failureReason: SwapFailureReason.UnexpectedClientError,
errorMessage: 'Could not calculate makerCltvDelta.',
});
return false;
}
try {
await makerSwapClient.addInvoice({
rHash: deal.rHash,
units: deal.makerUnits,
expiry: deal.makerCltvDelta,
currency: deal.makerCurrency,
});
} catch (err) {
await this.failDeal({
deal,
peer,
reqId,
failedCurrency: makerCurrency,
failureReason: SwapFailureReason.UnexpectedClientError,
errorMessage: `could not add invoice for while accepting deal: ${err.message}`,
});
return false;
}
// persist the swap deal to the database after we've added an invoice for it
const newPhasePromise = this.setDealPhase(deal, SwapPhase.SwapAccepted);
const responseBody: packets.SwapAcceptedPacketBody = {
rHash,
makerCltvDelta: deal.makerCltvDelta || 1,
quantity: proposedQuantity,
};
this.emit('swap.accepted', {
...deal,
currencySending: deal.takerCurrency,
currencyReceiving: deal.makerCurrency,
amountSending: deal.takerAmount,
amountReceiving: deal.makerAmount,
quantity: deal.quantity!,
});
this.logger.debug(`sending swap accepted packet: ${JSON.stringify(responseBody)} to peer: ${peer.nodePubKey}`);
const sendSwapAcceptedPromise = peer.sendPacket(
new packets.SwapAcceptedPacket(responseBody, requestPacket.header.id),
);
try {
await Promise.all([newPhasePromise, sendSwapAcceptedPromise]);
} catch (e) {
this.logger.trace(`failed to accept deal because: ${JSON.stringify(e)}`);
await this.failDeal({
deal,
peer,
reqId,
failureReason: SwapFailureReason.UnknownError,
errorMessage: 'Unable to accept deal',
failedCurrency: deal.takerCurrency,
});
return false;
}
return true;
};
private handleHtlcAccepted = async (swapClient: SwapClient, rHash: string, units: bigint, currency: string) => {
let rPreimage: string;
const deal = this.getDeal(rHash);
if (deal?.state === SwapState.Error) {
// we double check here to ensure that we don't attempt to resolve a hash
// and/or send payment for a stale deal that has already failed but
// eventually gets an incoming htlc accepted
this.logger.warn(`htlc accepted for failed deal ${rHash}`);
return;
}
try {
rPreimage = await this.resolveHash(rHash, units, currency);
} catch (err) {
this.logger.error(`could not resolve hash for deal ${rHash}`, err);
return;
}
if (!deal) {
// if there's no deal associated with this hash, we treat it as a sanity swap
// and attempt to settle our incoming payment
await swapClient.settleInvoice(rHash, rPreimage, currency).catch(this.logger.error);
} else if (deal.state === SwapState.Active) {
// we check that the deal is still active before we try to settle the invoice
try {
await swapClient.settleInvoice(rHash, rPreimage, currency);
} catch (err) {
this.logger.error(`could not settle invoice for deal ${rHash}`, err);
if (deal.role === SwapRole.Maker) {
// if we are the maker, we must be able to settle the invoice otherwise we lose funds
// we will continuously retry settling the invoice until it succeeds
// TODO: determine when we are permanently unable (due to htlc expiration or unknown invoice hash) to
// settle an invoice and fail the deal, rather than endlessly retrying settle invoice calls
this.logger.alert(
`incoming ${currency} payment with hash ${rHash} could not be settled with preimage ${rPreimage}, this is not expected and funds may be at risk`,
);
const settleRetryPromise = new Promise<void>((resolve) => {
const settleRetryTimer = setInterval(async () => {
try {
await swapClient.settleInvoice(rHash, rPreimage, currency);
this.logger.info(`successfully settled invoice for deal ${rHash} on retry`);
resolve();
clearInterval(settleRetryTimer);
} catch (settleInvoiceErr) {
this.logger.error(`could not settle invoice for deal ${rHash}`, settleInvoiceErr);
}
}, SwapRecovery.PENDING_SWAP_RECHECK_INTERVAL);
});
await settleRetryPromise;
} else {
// if we are the taker, funds are not at risk and we may simply fail the deal
await this.failDeal({
deal,
failureReason: SwapFailureReason.UnexpectedClientError,
errorMessage: err.message,
});
return;
}
}
// if we succeeded in settling our incoming payment we update the deal phase & state
await this.setDealPhase(deal, SwapPhase.PaymentReceived);
}
};
/**
* Handles a response from a peer to confirm a swap deal and updates the deal. If the deal is
* accepted, initiates the swap.
*/
private handleSwapAccepted = async (responsePacket: packets.SwapAcceptedPacket, peer: Peer) => {
assert(responsePacket.body, 'SwapAcceptedPacket does not contain a body');
const { quantity, rHash, makerCltvDelta } = responsePacket.body;
const deal = this.getDeal(rHash);
if (!deal) {
this.logger.warn(`received swap accepted for unrecognized deal: ${rHash}`);
// TODO: penalize peer
return;
}
if (deal.phase !== SwapPhase.SwapRequested) {
this.logger.warn(`received swap accepted for deal that is not in SwapRequested phase: ${rHash}`);
// TODO: penalize peer
return;
}
if (deal.state === SwapState.Error) {
// this swap deal may have already failed, either due to a DealTimedOut
// error while we were waiting for the swap to be accepted, or some
// other unexpected error or issue
this.logger.warn(`received swap accepted for deal that has already failed: ${rHash}`);
return;
}
// clear the timer waiting for acceptance of our swap offer, and set a new timer waiting for
// the swap to be completed
clearTimeout(this.timeouts.get(rHash));
this.timeouts.delete(rHash);
// update deal with maker's cltv delta
deal.makerCltvDelta = makerCltvDelta;
if (quantity) {
deal.quantity = quantity; // set the accepted quantity for the deal
if (quantity <= 0) {
await this.failDeal({
deal,
peer,
failureReason: SwapFailureReason.InvalidSwapPacketReceived,
errorMessage: 'accepted quantity must be a positive number',
});
// TODO: penalize peer
return;
} else if (quantity > deal.proposedQuantity) {
await this.failDeal({
deal,
peer,
failureReason: SwapFailureReason.InvalidSwapPacketReceived,
errorMessage: 'accepted quantity should not be greater than proposed quantity',
});
// TODO: penalize peer
return;
} else if (quantity < deal.proposedQuantity) {
const { makerAmount, takerAmount } = this.calculateMakerTakerAmounts(
quantity,
deal.price,
deal.isBuy,
deal.pairId,
);
deal.takerAmount = takerAmount;
deal.makerAmount = makerAmount;
}
}
const makerSwapClient = this.swapClientManager.get(deal.makerCurrency);
const takerSwapClient = this.swapClientManager.get(deal.takerCurrency);
if (!makerSwapClient || !takerSwapClient) {
// We checked that we had a swap client for both currencies involved during the peer handshake. Still...
return;
}
try {
await takerSwapClient.addInvoice({
rHash: deal.rHash,
units: deal.takerUnits,
expiry: deal.takerCltvDelta,
currency: deal.takerCurrency,
});
} catch (err) {
await this.failDeal({
deal,
peer,
failedCurrency: deal.takerCurrency,
failureReason: SwapFailureReason.UnexpectedClientError,
errorMessage: err.message,
});
return;
}
// persist the deal to the database before we attempt to send
await this.setDealPhase(deal, SwapPhase.SendingPayment);
try {
await makerSwapClient.sendPayment(deal);
} catch (err) {
// first we must handle the edge case where the maker has paid us but failed to claim our payment
// in this case, we've already marked the swap as having been paid and completed
if (deal.state === SwapState.Completed) {
this.logger.warn(`maker was unable to claim payment for ${deal.rHash} but has already paid us`);
return;
}
if (err.code === errorCodes.PAYMENT_REJECTED) {
// if the maker rejected our payment, the swap failed due to an error on their side
// and we don't need to send them a SwapFailedPacket
await this.failDeal({
deal,
failureReason: SwapFailureReason.PaymentRejected,
errorMessage: err.message,
});
} else {
await this.failDeal({
deal,
peer,
failedCurrency: deal.makerCurrency,
failureReason: SwapFailureReason.SendPaymentFailure,
errorMessage: err.message,
});
}
}
};
/**
* Verifies that the resolve request is valid. Checks the received amount vs
* the expected amount.
* @returns `true` if the resolve request is valid, `false` otherwise
*/
private validateResolveRequest = (deal: SwapDeal, resolveRequest: ResolveRequest) => {
const { units, tokenAddress, expiration, chainHeight } = resolveRequest;
const peer = this.pool.getPeer(deal.peerPubKey);
let expectedUnits: bigint;
let expectedTokenAddress: string | undefined;
let expectedCurrency: string;
let source: string;
let destination: string;
switch (deal.role) {
case SwapRole.Maker: {
expectedUnits = deal.makerUnits;
expectedCurrency = deal.makerCurrency;
expectedTokenAddress = this.swapClientManager.connextClient?.tokenAddresses.get(deal.makerCurrency);
source = 'Taker';
destination = 'Maker';
const lockExpirationDelta = expiration - chainHeight;
// We relax the validation by LOCK_EXPIRATION_SLIPPAGE blocks because
// new blocks could be mined during the time it takes from taker's
// payment to reach the maker for validation.
// This usually happens in simulated environments with fast mining enabled.
const LOCK_EXPIRATION_SLIPPAGE = 3;
if (deal.makerCltvDelta! - LOCK_EXPIRATION_SLIPPAGE > lockExpirationDelta) {
this.logger.error(`
lockExpirationDelta of ${lockExpirationDelta} does not meet
makerCltvDelta ${deal.makerCltvDelta!} - LOCK_EXPIRATION_SLIPPAGE ${LOCK_EXPIRATION_SLIPPAGE}