-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathLndClient.ts
1380 lines (1255 loc) · 49.9 KB
/
LndClient.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 * as grpc from '@grpc/grpc-js';
import { ServiceClient } from '@grpc/grpc-js/build/src/make-client';
import assert from 'assert';
import crypto from 'crypto';
import { promises as fs, watch } from 'fs';
import path from 'path';
import { SwapClientType, SwapRole, SwapState } from '../constants/enums';
import Logger from '../Logger';
import * as lndinvoicesGrpc from '../proto/lndinvoices_grpc_pb';
import * as lndinvoices from '../proto/lndinvoices_pb';
import * as lndwalletGrpc from '../proto/lndwalletunlocker_grpc_pb';
import * as lndwallet from '../proto/lndwalletunlocker_pb';
import * as lndrouterGrpc from '../proto/lndrouter_grpc_pb';
import * as lndrouter from '../proto/lndrouter_pb';
import * as lndGrpc from '../proto/lndrpc_grpc_pb';
import * as lndrpc from '../proto/lndrpc_pb';
import { BASE_MAX_CLIENT_WAIT_TIME, MAX_FEE_RATIO, MAX_PAYMENT_TIME } from '../swaps/consts';
import swapErrors from '../swaps/errors';
import SwapClient, {
ChannelBalance,
ClientStatus,
PaymentState,
SwapClientInfo,
WithdrawArguments,
} from '../swaps/SwapClient';
import { CloseChannelParams, OpenChannelParams, SwapCapacities, SwapDeal } from '../swaps/types';
import { deriveChild } from '../utils/seedutil';
import { base64ToHex, hexToUint8Array } from '../utils/utils';
import errors from './errors';
import { Chain, ChannelCount, ClientMethods, LndClientConfig, LndInfo } from './types';
// @ts-ignore
const LightningClient = grpc.makeClientConstructor(lndGrpc['lnrpc.Lightning'], 'LightningService');
// @ts-ignore
const WalletUnlockerClient = grpc.makeClientConstructor(lndwalletGrpc['lnrpc.WalletUnlocker'], 'WalletUnlockerService');
// @ts-ignore
const InvoicesClient = grpc.makeClientConstructor(lndinvoicesGrpc['invoicesrpc.Invoices'], 'InvoicesService');
// @ts-ignore
const RouterClient = grpc.makeClientConstructor(lndrouterGrpc['routerrpc.Router'], 'RouterService');
interface LndClient {
on(event: 'connectionVerified', listener: (swapClientInfo: SwapClientInfo) => void): this;
on(event: 'htlcAccepted', listener: (rHash: string, units: bigint) => void): this;
on(event: 'channelBackup', listener: (channelBackup: Uint8Array) => void): this;
on(event: 'channelBackupEnd', listener: () => void): this;
on(event: 'locked', listener: () => void): this;
once(event: 'initialized', listener: () => void): this;
emit(event: 'connectionVerified', swapClientInfo: SwapClientInfo): boolean;
emit(event: 'htlcAccepted', rHash: string, units: bigint): boolean;
emit(event: 'channelBackup', channelBackup: Uint8Array): boolean;
emit(event: 'channelBackupEnd'): boolean;
emit(event: 'locked'): boolean;
emit(event: 'initialized'): boolean;
}
const GRPC_CLIENT_OPTIONS = {
'grpc.ssl_target_name_override': 'localhost',
'grpc.default_authority': 'localhost',
'grpc.max_receive_message_length': 1024 * 1024 * 200, // grpc default is 4 mb but lnd uses 200 mb
};
/** A class representing a client to interact with lnd. */
class LndClient extends SwapClient {
public readonly type = SwapClientType.Lnd;
public readonly finalLock: number;
public config: LndClientConfig;
public currency: string;
public walletPassword?: string;
private lightning?: ServiceClient;
private walletUnlocker?: ServiceClient;
/** The maximum time to wait for a client to be ready for making grpc calls, can be used for exponential backoff. */
private maxClientWaitTime = BASE_MAX_CLIENT_WAIT_TIME;
private invoices?: ServiceClient;
private router?: ServiceClient;
/** The path to the lnd admin macaroon, will be undefined if `nomacaroons` is enabled */
private macaroonpath?: string;
private meta = new grpc.Metadata();
private uri!: string;
private credentials!: grpc.ChannelCredentials;
/** The identity pub key for this lnd instance. */
private identityPubKey?: string;
/** List of client's public listening uris that are advertised to the network */
private urisList?: string[];
/** The identifier for the chain this lnd instance is using in the format [chain]-[network] like "bitcoin-testnet" */
private chainIdentifier?: string;
private channelBackupSubscription?: grpc.ClientReadableStream<lndrpc.ChanBackupSnapshot>;
private invoiceSubscriptions = new Map<string, grpc.ClientReadableStream<lndrpc.Invoice>>();
private initRetryTimeout?: NodeJS.Timeout;
private totalOutboundAmount = 0;
private totalInboundAmount = 0;
private maxChannelOutboundAmount = 0;
private maxChannelInboundAmount = 0;
private initWalletResolve?: (value: boolean) => void;
private watchMacaroonResolve?: (value: boolean) => void;
private static MINUTES_PER_BLOCK_BY_CURRENCY: { [key: string]: number } = {
BTC: 10,
LTC: 2.5,
};
/**
* Creates an lnd client.
*/
constructor({ config, logger, currency }: { config: LndClientConfig; logger: Logger; currency: string }) {
super(logger, config.disable);
this.config = config;
this.currency = currency;
this.finalLock = config.cltvdelta;
}
private waitForClientReady = (client: grpc.Client) => {
return new Promise((resolve, reject) => {
client.waitForReady(Date.now() + this.maxClientWaitTime, (err) => {
if (err) {
if (err.message === 'Failed to connect before the deadline') {
this.maxClientWaitTime *= 10; // exponentially backoff the max wait time if we reach the deadline
resolve();
}
reject(err);
} else {
this.maxClientWaitTime = BASE_MAX_CLIENT_WAIT_TIME; // reset our max wait time
resolve();
}
});
});
};
public get minutesPerBlock() {
return LndClient.MINUTES_PER_BLOCK_BY_CURRENCY[this.currency];
}
public get label() {
return `LND-${this.currency}`;
}
/**
* Initializes the client for calls to lnd and verifies that we can connect to it.
* @param awaitingCreate whether xud is waiting for its node key to be created
*/
public initSpecific = async () => {
const { certpath, macaroonpath, nomacaroons, host, port } = this.config;
let lndCert: Buffer | undefined;
try {
lndCert = await fs.readFile(certpath);
} catch (err) {
if (err.code === 'ENOENT') {
// if we have not created the lnd wallet yet and the tls.cert file can
// not be found, we will briefly wait for the cert to be created in
// case lnd has not been run before and is being started in parallel
// with xud
const certDir = path.join(certpath, '..');
const CERT_TIMEOUT = 3000;
lndCert = await new Promise((resolve) => {
this.logger.debug(`watching ${certDir} for tls.cert to be created`);
const timeout = setTimeout(() => {
fsWatcher.close();
resolve(undefined);
}, CERT_TIMEOUT);
const fsWatcher = watch(certDir, (event, filename) => {
if (event === 'change' && filename === 'tls.cert') {
this.logger.debug('tls.cert was created');
fsWatcher.close();
clearTimeout(timeout);
fs.readFile(certpath)
.then(resolve)
.catch((readFileErr) => {
this.logger.error(readFileErr);
resolve(undefined);
});
}
});
});
}
}
if (lndCert) {
this.logger.debug(`loaded tls cert from ${certpath}`);
this.credentials = grpc.credentials.createSsl(lndCert);
} else {
this.logger.error(`could not load tls cert from ${certpath}, is lnd installed?`);
this.setStatus(ClientStatus.Misconfigured);
this.initRetryTimeout = setTimeout(this.init, LndClient.RECONNECT_INTERVAL);
return;
}
if (!nomacaroons) {
this.macaroonpath = macaroonpath;
try {
await this.loadMacaroon();
} catch (err) {
this.logger.info(`could not load macaroon at ${macaroonpath}, this is normal before creating a new wallet`);
}
} else {
this.logger.info('macaroons are disabled');
}
this.uri = `${host}:${port}`;
if (this.initRetryTimeout) {
clearTimeout(this.initRetryTimeout);
this.initRetryTimeout = undefined;
}
};
public get pubKey() {
return this.identityPubKey;
}
public get uris() {
return this.urisList;
}
public get chain() {
return this.chainIdentifier;
}
public setReservedInboundAmount = (_reservedInboundAmount: number) => {
// not currently used for lnd
};
/** Lnd specific procedure to mark the client as locked. */
private lock = () => {
if (!this.walletUnlocker) {
this.walletUnlocker = new WalletUnlockerClient(this.uri, this.credentials, GRPC_CLIENT_OPTIONS);
}
if (this.lightning) {
this.lightning.close();
this.lightning = undefined;
}
if (!this.isWaitingUnlock()) {
this.setStatus(ClientStatus.WaitingUnlock);
}
this.emit('locked');
};
/** Lnd specific procedure to mark the client as unlocked. */
private setUnlocked = () => {
// we should close and unreference the wallet unlocker service when we set the status to Unlocked
if (this.walletUnlocker) {
this.walletUnlocker.close();
this.walletUnlocker = undefined;
}
if (this.isWaitingUnlock()) {
this.setStatus(ClientStatus.Unlocked);
} else {
// we should not be calling this method we were in the WaitingUnlock status
this.logger.warn(`tried to set client status to WaitingUnlock from status ${this.status}`);
}
};
protected updateCapacity = async () => {
await this.channelBalance().catch(async (err) => {
this.logger.error('failed to update total outbound capacity', err);
});
};
private unaryCall = <T, U>(
methodName: Exclude<keyof lndGrpc.LightningClient, ClientMethods>,
params: T,
): Promise<U> => {
return new Promise((resolve, reject) => {
if (this.hasNoInvoiceSupport()) {
reject(errors.NO_HOLD_INVOICE_SUPPORT);
return;
}
if (!this.isOperational()) {
reject(errors.DISABLED);
return;
}
if (!this.lightning) {
reject(errors.UNAVAILABLE(this.currency, this.status));
return;
}
(this.lightning[methodName] as Function)(params, this.meta, (err: grpc.ServiceError, response: U) => {
if (err) {
if (err.code === grpc.status.UNAVAILABLE) {
this.disconnect();
} else if (err.code === grpc.status.UNIMPLEMENTED) {
this.lock();
}
this.logger.trace(`error on ${methodName}: ${err.message}`);
reject(err);
} else {
resolve(response);
}
});
});
};
private loadMacaroon = async () => {
if (this.macaroonpath) {
const adminMacaroon = await fs.readFile(this.macaroonpath);
this.meta.add('macaroon', adminMacaroon.toString('hex'));
this.logger.debug(`loaded macaroon from ${this.macaroonpath}`);
}
};
private unaryInvoiceCall = <T, U>(
methodName: Exclude<keyof lndinvoicesGrpc.InvoicesClient, ClientMethods>,
params: T,
): Promise<U> => {
return new Promise((resolve, reject) => {
if (!this.isOperational()) {
reject(errors.DISABLED);
return;
}
if (!this.invoices) {
reject(errors.UNAVAILABLE(this.currency, this.status));
return;
}
(this.invoices[methodName] as Function)(params, this.meta, (err: grpc.ServiceError, response: U) => {
if (err) {
if (err.code === grpc.status.UNAVAILABLE) {
this.disconnect();
} else if (err.code === grpc.status.UNIMPLEMENTED) {
this.lock();
}
this.logger.trace(`error on ${methodName}: ${err.message}`);
reject(err);
} else {
resolve(response);
}
});
});
};
private unaryWalletUnlockerCall = <T, U>(
methodName: Exclude<keyof lndwalletGrpc.WalletUnlockerClient, ClientMethods>,
params: T,
): Promise<U> => {
return new Promise((resolve, reject) => {
if (!this.isOperational()) {
reject(errors.DISABLED);
return;
}
if (!this.walletUnlocker) {
reject(errors.UNAVAILABLE(this.currency, this.status));
return;
}
(this.walletUnlocker[methodName] as Function)(params, this.meta, (err: grpc.ServiceError, response: U) => {
if (err) {
if (err.code === grpc.status.UNAVAILABLE) {
this.disconnect();
}
if (err.code === grpc.status.UNIMPLEMENTED) {
this.logger.debug(`lnd already unlocked before ${methodName} call`);
resolve();
} else {
this.logger.debug(`error on ${methodName}: ${err.message}`);
reject(err);
}
} else {
resolve(response);
}
});
});
};
public getLndInfo = async (): Promise<LndInfo> => {
let channels: ChannelCount | undefined;
let chains: Chain[] | undefined;
let blockheight: number | undefined;
let uris: string[] | undefined;
let version: string | undefined;
let alias: string | undefined;
let status = 'Ready';
if (this.hasNoInvoiceSupport()) {
status = errors.NO_HOLD_INVOICE_SUPPORT(this.currency).message;
} else if (!this.isOperational()) {
status = errors.DISABLED(this.currency).message;
} else if (this.isDisconnected()) {
status = errors.UNAVAILABLE(this.currency, this.status).message;
} else {
try {
const getInfoResponse = await this.getInfo();
const closedChannelsResponse = await this.getClosedChannels();
channels = {
active: getInfoResponse.getNumActiveChannels(),
inactive: getInfoResponse.getNumInactiveChannels(),
pending: getInfoResponse.getNumPendingChannels(),
closed: closedChannelsResponse.getChannelsList().length,
};
chains = getInfoResponse.getChainsList().map((value) => value.toObject());
blockheight = getInfoResponse.getBlockHeight();
uris = getInfoResponse.getUrisList();
version = getInfoResponse.getVersion();
alias = getInfoResponse.getAlias();
if (this.isOutOfSync()) {
status = errors.UNAVAILABLE(this.currency, this.status).message;
} else if (channels.active <= 0) {
status = errors.NO_ACTIVE_CHANNELS(this.currency).message;
}
} catch (err) {
this.logger.error('getinfo error', err);
status = err.message;
}
}
return {
status,
channels,
chains,
blockheight,
uris,
version,
alias,
};
};
/**
* Waits for the lnd wallet to be initialized and for its macaroons to be created then attempts
* to verify the connection to lnd.
*/
private awaitWalletInit = async () => {
/**
* Whether the lnd wallet has been created via an InitWallet call,
* `false` if we close the client before the lnd wallet is created.
*/
let isWalletInitialized: boolean;
if (this.status === ClientStatus.Initialized) {
// we are waiting for the lnd wallet to be initialized by xud and for the lnd macaroons to be created
this.logger.info('waiting for wallet to be initialized...');
this.walletUnlocker = new WalletUnlockerClient(this.uri, this.credentials, GRPC_CLIENT_OPTIONS);
await this.waitForClientReady(this.walletUnlocker);
this.lock();
isWalletInitialized = await new Promise<boolean>((resolve) => {
this.initWalletResolve = resolve;
});
} else if (this.status === ClientStatus.Unlocked) {
// the lnd wallet has been created but its macaroons have not been written to the file system yet
isWalletInitialized = true;
} else {
assert.fail('awaitWalletInit should not be called from a status besides Initialized or Unlocked');
}
if (isWalletInitialized) {
// admin.macaroon will not necessarily be created by the time lnd responds to a successful
// InitWallet call, so we watch the folder that we expect it to be in for it to be created
await this.watchThenLoadMacaroon();
// once we've loaded the macaroon we can attempt to verify the conneciton
this.verifyConnection().catch(this.logger.error);
}
};
protected verifyConnection = async () => {
if (!this.isOperational()) {
throw errors.DISABLED;
}
if (this.isWaitingUnlock()) {
return; // temporary workaround to prevent unexplained lnd crashes after unlock
}
if (this.macaroonpath && this.meta.get('macaroon').length === 0) {
// we have not loaded the macaroon yet - it is not created until the lnd wallet is initialized
if (!this.isWaitingUnlock() && !this.initWalletResolve) {
// check that we are not already waiting for wallet init & unlock
this.awaitWalletInit().catch(this.logger.error);
}
return;
}
this.logger.info(`trying to verify connection to lnd at ${this.uri}`);
this.lightning = new LightningClient(this.uri, this.credentials, GRPC_CLIENT_OPTIONS);
try {
await this.waitForClientReady(this.lightning);
const getInfoResponse = await this.getInfo();
if (getInfoResponse.getSyncedToChain()) {
// check if the lnd pub key value is different from the one we had previously.
let newPubKey: string | undefined;
let newUris: string[] = [];
if (this.identityPubKey !== getInfoResponse.getIdentityPubkey()) {
newPubKey = getInfoResponse.getIdentityPubkey();
this.logger.debug(`pubkey is ${newPubKey}`);
this.identityPubKey = newPubKey;
newUris = getInfoResponse.getUrisList();
if (newUris.length) {
this.logger.debug(`uris are ${newUris}`);
} else {
this.logger.debug('no uris advertised');
}
this.urisList = newUris;
}
// check if the chain this lnd instance uses has changed
const chain = getInfoResponse.getChainsList()[0];
const chainIdentifier = `${chain.getChain()}-${chain.getNetwork()}`;
if (!this.chainIdentifier) {
this.chainIdentifier = chainIdentifier;
this.logger.debug(`chain is ${chainIdentifier}`);
} else if (this.chainIdentifier !== chainIdentifier) {
// we switched chains for this lnd client while xud was running which is not supported
this.logger.error(`chain switched from ${this.chainIdentifier} to ${chainIdentifier}`);
this.setStatus(ClientStatus.Misconfigured);
}
if (this.walletUnlocker) {
// WalletUnlocker service is disabled when the main Lightning service is available
this.walletUnlocker.close();
this.walletUnlocker = undefined;
}
this.invoices = new InvoicesClient(this.uri, this.credentials, GRPC_CLIENT_OPTIONS);
this.router = new RouterClient(this.uri, this.credentials, GRPC_CLIENT_OPTIONS);
try {
const randomHash = crypto.randomBytes(32).toString('hex');
this.logger.debug(`checking hold invoice support with hash: ${randomHash}`);
await this.addInvoice({ rHash: randomHash, units: 1n });
await this.removeInvoice(randomHash);
} catch (err) {
if (err.code !== grpc.status.UNAVAILABLE) {
// mark the client as not having hold invoice support if the invoice calls failed due to
// reasons other than generic grpc connectivity errors
this.logger.error('could not add hold invoice', err);
this.setStatus(ClientStatus.NoHoldInvoiceSupport);
}
throw err; // we don't want to proceed with marking the client as connected, regardless of the error
}
await this.setConnected(newPubKey, newUris);
} else {
this.setStatus(ClientStatus.OutOfSync);
this.logger.warn(`lnd is out of sync with chain, retrying in ${LndClient.RECONNECT_INTERVAL} ms`);
}
} catch (err) {
const errStr = typeof err === 'string' ? err : JSON.stringify(err);
this.logger.error(
`could not verify connection at ${this.uri}, error: ${errStr}, retrying in ${LndClient.RECONNECT_INTERVAL} ms`,
);
}
};
/**
* Returns general information concerning the lightning node including it’s identity pubkey, alias, the chains it
* is connected to, and information concerning the number of open+pending channels.
*/
public getInfo = (): Promise<lndrpc.GetInfoResponse> => {
return this.unaryCall<lndrpc.GetInfoRequest, lndrpc.GetInfoResponse>('getInfo', new lndrpc.GetInfoRequest());
};
/**
* Returns closed channels that this node was a participant in.
*/
public getClosedChannels = (): Promise<lndrpc.ClosedChannelsResponse> => {
return this.unaryCall<lndrpc.ClosedChannelsRequest, lndrpc.ClosedChannelsResponse>(
'closedChannels',
new lndrpc.ClosedChannelsRequest(),
);
};
public walletDeposit = async () => {
const depositAddress = await this.newAddress();
return depositAddress;
};
public deposit = async () => {
throw new Error(
'Depositing directly to channel is not supported. Please use a lightning service provider such as Boltz to create a channel with 1 transaction or deposit to the on-chain wallet first.',
);
};
public withdraw = async ({ amount, destination, all = false, fee }: WithdrawArguments) => {
const request = new lndrpc.SendCoinsRequest();
request.setAddr(destination);
if (fee) {
request.setSatPerByte(fee);
}
if (all) {
request.setSendAll(all);
} else if (amount) {
request.setAmount(amount);
}
const withdrawResponse = await this.unaryCall<lndrpc.SendCoinsRequest, lndrpc.SendCoinsResponse>(
'sendCoins',
request,
);
return withdrawResponse.getTxid();
};
public sendSmallestAmount = async (rHash: string, destination: string): Promise<string> => {
const request = this.buildSendRequest({
rHash,
destination,
amount: 1,
// In case of sanity swaps we don't know the
// takerCltvDelta or the makerCltvDelta. Using our
// client's default.
finalCltvDelta: this.finalLock,
});
const preimage = await this.sendPaymentV2(request);
return preimage;
};
public sendPayment = async (deal: SwapDeal): Promise<string> => {
assert(deal.state === SwapState.Active);
let request: lndrouter.SendPaymentRequest;
assert(deal.makerCltvDelta, 'swap deal must have a makerCltvDelta');
if (deal.role === SwapRole.Taker) {
// we are the taker paying the maker
assert(deal.destination, 'swap deal as taker must have a destination');
request = this.buildSendRequest({
rHash: deal.rHash,
destination: deal.destination,
amount: deal.makerAmount,
// Using the agreed upon makerCltvDelta. Maker won't accept
// our payment if we provide a smaller value.
finalCltvDelta: deal.makerCltvDelta,
});
} else {
// we are the maker paying the taker
assert(deal.takerPubKey, 'swap deal as maker must have a takerPubKey');
assert(deal.takerCltvDelta, 'swap deal as maker must have a takerCltvDelta');
request = this.buildSendRequest({
rHash: deal.rHash,
destination: deal.takerPubKey,
amount: deal.takerAmount,
finalCltvDelta: deal.takerCltvDelta,
// Enforcing the maximum duration/length of the payment by specifying
// the cltvLimit. We add 3 blocks to offset the block padding set by lnd.
cltvLimit: deal.takerMaxTimeLock! + 3,
});
}
this.logger.debug(`sending payment of ${request.getAmt()} with hash ${deal.rHash}`);
const preimage = await this.sendPaymentV2(request);
return preimage;
};
/**
* Sends a payment through the Lightning Network.
* @returns the preimage in hex format
*/
private sendPaymentV2 = (request: lndrouter.SendPaymentRequest): Promise<string> => {
return new Promise<string>((resolve, reject) => {
if (!this.router) {
reject(swapErrors.FINAL_PAYMENT_ERROR(errors.UNAVAILABLE(this.currency, this.status).message));
return;
}
if (!this.isConnected()) {
reject(swapErrors.FINAL_PAYMENT_ERROR(errors.UNAVAILABLE(this.currency, this.status).message));
return;
}
this.logger.trace(`sending payment with request: ${JSON.stringify(request.toObject())}`);
const call = this.router.sendPaymentV2(request, this.meta);
call.on('data', (response: lndrpc.Payment) => {
switch (response.getStatus()) {
case lndrpc.Payment.PaymentStatus.FAILED:
switch (response.getFailureReason()) {
case lndrpc.PaymentFailureReason.FAILURE_REASON_TIMEOUT:
case lndrpc.PaymentFailureReason.FAILURE_REASON_NO_ROUTE:
case lndrpc.PaymentFailureReason.FAILURE_REASON_ERROR:
case lndrpc.PaymentFailureReason.FAILURE_REASON_INSUFFICIENT_BALANCE:
reject(swapErrors.FINAL_PAYMENT_ERROR(lndrpc.PaymentFailureReason[response.getFailureReason()]));
break;
case lndrpc.PaymentFailureReason.FAILURE_REASON_INCORRECT_PAYMENT_DETAILS:
reject(swapErrors.PAYMENT_REJECTED);
break;
default:
reject(swapErrors.UNKNOWN_PAYMENT_ERROR(response.getFailureReason().toString()));
break;
}
break;
case lndrpc.Payment.PaymentStatus.SUCCEEDED:
resolve(response.getPaymentPreimage());
break;
default:
// in-flight status, we'll wait for a final status update event
break;
}
});
call.on('end', () => {
call.removeAllListeners();
});
call.on('error', (err: any) => {
call.removeAllListeners();
this.logger.error('error event from sendPaymentV2', err);
if (typeof err.message === 'string' && err.message.includes('chain backend is still syncing')) {
reject(swapErrors.FINAL_PAYMENT_ERROR(err.message));
} else {
reject(swapErrors.UNKNOWN_PAYMENT_ERROR(JSON.stringify(err)));
}
});
});
};
/**
* Builds a lndrpc.SendRequest
*/
private buildSendRequest = ({
rHash,
destination,
amount,
finalCltvDelta,
cltvLimit,
}: {
rHash: string;
destination: string;
amount: number;
finalCltvDelta: number;
cltvLimit?: number;
}): lndrouter.SendPaymentRequest => {
const request = new lndrouter.SendPaymentRequest();
request.setPaymentHash(Buffer.from(rHash, 'hex'));
request.setDest(Buffer.from(destination, 'hex'));
request.setAmt(amount);
request.setFinalCltvDelta(finalCltvDelta);
request.setTimeoutSeconds(MAX_PAYMENT_TIME / 1000);
const fee = Math.floor(MAX_FEE_RATIO * request.getAmt());
request.setFeeLimitSat(fee);
if (cltvLimit) {
// cltvLimit is used to enforce the maximum
// duration/length of the payment.
request.setCltvLimit(cltvLimit);
}
return request;
};
/**
* Gets a new address for the internal lnd wallet.
*/
private newAddress = async (addressType = lndrpc.AddressType.WITNESS_PUBKEY_HASH) => {
const request = new lndrpc.NewAddressRequest();
request.setType(addressType);
const newAddressResponse = await this.unaryCall<lndrpc.NewAddressRequest, lndrpc.NewAddressResponse>(
'newAddress',
request,
);
return newAddressResponse.getAddress();
};
/**
* Returns the total of unspent outputs for the internal lnd wallet.
*/
public walletBalance = async (): Promise<lndrpc.WalletBalanceResponse.AsObject> => {
const walletBalanceResponse = await this.unaryCall<lndrpc.WalletBalanceRequest, lndrpc.WalletBalanceResponse>(
'walletBalance',
new lndrpc.WalletBalanceRequest(),
);
return walletBalanceResponse.toObject();
};
/**
* Updates all balances related to channels including active, inactive, and pending balances.
* Sets trading limits for this client accordingly.
*/
private updateChannelBalances = async () => {
const [channels, pendingChannels] = await Promise.all([this.listChannels(), this.pendingChannels()]);
let maxOutbound = 0;
let maxInbound = 0;
let balance = 0;
let inactiveBalance = 0;
let totalOutboundAmount = 0;
let totalInboundAmount = 0;
channels.toObject().channelsList.forEach((channel) => {
if (channel.active) {
balance += channel.localBalance;
const outbound = Math.max(0, channel.localBalance - channel.localChanReserveSat);
totalOutboundAmount += outbound;
if (maxOutbound < outbound) {
maxOutbound = outbound;
}
const inbound = Math.max(0, channel.remoteBalance - channel.remoteChanReserveSat);
totalInboundAmount += inbound;
if (maxInbound < inbound) {
maxInbound = inbound;
}
} else {
inactiveBalance += channel.localBalance;
}
});
if (this.maxChannelOutboundAmount !== maxOutbound) {
this.maxChannelOutboundAmount = maxOutbound;
this.logger.debug(`new channel maximum outbound capacity: ${maxOutbound}`);
}
if (this.maxChannelInboundAmount !== maxInbound) {
this.maxChannelInboundAmount = maxInbound;
this.logger.debug(`new channel inbound capacity: ${maxInbound}`);
}
if (this.totalOutboundAmount !== totalOutboundAmount) {
this.totalOutboundAmount = totalOutboundAmount;
this.logger.debug(`new channel total outbound capacity: ${totalOutboundAmount}`);
}
if (this.totalInboundAmount !== totalInboundAmount) {
this.totalInboundAmount = totalInboundAmount;
this.logger.debug(`new channel total inbound capacity: ${totalInboundAmount}`);
}
const pendingOpenBalance = pendingChannels
.toObject()
.pendingOpenChannelsList.reduce((sum, pendingChannel) => sum + (pendingChannel.channel?.localBalance ?? 0), 0);
return {
maxOutbound,
maxInbound,
totalOutboundAmount,
totalInboundAmount,
balance,
inactiveBalance,
pendingOpenBalance,
};
};
public channelBalance = async (): Promise<ChannelBalance> => {
const { balance, inactiveBalance, pendingOpenBalance } = await this.updateChannelBalances();
return { balance, inactiveBalance, pendingOpenBalance };
};
public swapCapacities = async (): Promise<SwapCapacities> => {
const { maxOutbound, maxInbound, totalInboundAmount, totalOutboundAmount } = await this.updateChannelBalances(); // get fresh balances
return {
maxOutboundChannelCapacity: maxOutbound,
maxInboundChannelCapacity: maxInbound,
totalOutboundCapacity: totalOutboundAmount,
totalInboundCapacity: totalInboundAmount,
};
};
public getHeight = async () => {
const info = await this.getInfo();
return info.getBlockHeight();
};
/**
* Connects to another lnd node.
*/
public connectPeer = (pubkey: string, address: string): Promise<lndrpc.ConnectPeerResponse> => {
const request = new lndrpc.ConnectPeerRequest();
const lightningAddress = new lndrpc.LightningAddress();
lightningAddress.setHost(address);
lightningAddress.setPubkey(pubkey);
request.setAddr(lightningAddress);
return this.unaryCall<lndrpc.ConnectPeerRequest, lndrpc.ConnectPeerResponse>('connectPeer', request);
};
/**
* Opens a channel given peerPubKey and amount.
*/
public openChannel = async ({
remoteIdentifier,
units,
uris,
pushUnits = 0n,
fee = 0,
}: OpenChannelParams): Promise<string> => {
if (!remoteIdentifier) {
// TODO: better handling for for unrecognized peers & force closing channels
throw new Error('peer not connected to swap client');
}
if (uris) {
await this.connectPeerAddresses(uris);
}
const openResponse = await this.openChannelSync(remoteIdentifier, Number(units), Number(pushUnits), fee);
return openResponse.hasFundingTxidStr()
? openResponse.getFundingTxidStr()
: base64ToHex(openResponse.getFundingTxidBytes_asB64());
};
/**
* Tries to connect to a given list of a peer's uris in sequential order.
* @returns `true` when successful, otherwise `false`.
*/
private connectPeerAddresses = async (peerListeningUris: string[]): Promise<boolean> => {
const splitListeningUris = peerListeningUris.map((uri) => {
const splitUri = uri.split('@');
return {
peerPubKey: splitUri[0],
address: splitUri[1],
};
});
for (const uri of splitListeningUris) {
const { peerPubKey, address } = uri;
try {
await this.connectPeer(peerPubKey, address);
return true;
} catch (e) {
if (e.message && e.message.includes('already connected')) {
return true;
}
this.logger.trace(`connectPeer to ${uri} failed: ${e}`);
}
}
return false;
};
/**
* Opens a channel with a connected lnd node.
*/
private openChannelSync = (
nodePubkeyString: string,
localFundingAmount: number,
pushSat = 0,
fee = 0,
): Promise<lndrpc.ChannelPoint> => {
const request = new lndrpc.OpenChannelRequest();
request.setNodePubkeyString(nodePubkeyString);
request.setLocalFundingAmount(localFundingAmount);
request.setPushSat(pushSat);
request.setSatPerByte(fee);
return this.unaryCall<lndrpc.OpenChannelRequest, lndrpc.ChannelPoint>('openChannelSync', request);
};
/**
* Lists all open channels for this node.
*/
public listChannels = (): Promise<lndrpc.ListChannelsResponse> => {
return this.unaryCall<lndrpc.ListChannelsRequest, lndrpc.ListChannelsResponse>(
'listChannels',
new lndrpc.ListChannelsRequest(),
);
};
/**
* Lists all pending channels for this node.
*/
private pendingChannels = (): Promise<lndrpc.PendingChannelsResponse> => {
return this.unaryCall<lndrpc.PendingChannelsRequest, lndrpc.PendingChannelsResponse>(
'pendingChannels',
new lndrpc.PendingChannelsRequest(),
);
};
public getRoute = async (units: bigint, destination: string, _currency: string, finalLock = this.finalLock) => {
const request = new lndrpc.QueryRoutesRequest();
request.setAmt(Number(units));
request.setFinalCltvDelta(finalLock);
request.setPubKey(destination);
const fee = new lndrpc.FeeLimit();
fee.setFixed(Math.floor(MAX_FEE_RATIO * request.getAmt()));
request.setFeeLimit(fee);
let route: lndrpc.Route | undefined;
try {
// QueryRoutes no longer returns more than one route
[route] = (await this.queryRoutes(request)).getRoutesList();
} catch (err) {
if (typeof err.message === 'string' && err.message.includes('insufficient local balance')) {
throw swapErrors.INSUFFICIENT_BALANCE;
}
if (
typeof err.message !== 'string' ||
(!err.message.includes('unable to find a path to destination') && !err.message.includes('target not found'))
) {
this.logger.error(
`error calling queryRoutes to ${destination}, amount ${units}, finalCltvDelta ${finalLock}`,
err,
);
throw err;
}
}
if (route) {
this.logger.debug(
`found a route to ${destination} for ${units} units with finalCltvDelta ${finalLock}: ${route}`,
);
} else {
this.logger.debug(`could not find a route to ${destination} for ${units} units with finalCltvDelta ${finalLock}`);
}
return route;
};
public canRouteToNode = async (_destination: string) => {
// lnd doesn't currently have a way to see if any route exists, regardless of balance
// for example, if we have a direct channel to peer but no balance in the channel and
// no other routes, QueryRoutes will return nothing as of lnd v0.8.1.
// For now we err on the side of leniency and assume a route may exist.
return true;
};
/**
* Lists all routes to destination.
*/
private queryRoutes = (request: lndrpc.QueryRoutesRequest): Promise<lndrpc.QueryRoutesResponse> => {
return this.unaryCall<lndrpc.QueryRoutesRequest, lndrpc.QueryRoutesResponse>('queryRoutes', request);
};
public initWallet = async (