This repository was archived by the owner on Feb 9, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathlightning-manager.ts
More file actions
1414 lines (1289 loc) · 41.5 KB
/
lightning-manager.ts
File metadata and controls
1414 lines (1289 loc) · 41.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import ldk from './ldk';
import { err, ok, Result } from './utils/result';
import {
DefaultLdkDataShape,
DefaultTransactionDataShape,
EEventTypes,
ELdkData,
ELdkFiles,
ELdkLogLevels,
ENetworks,
TAccount,
TAccountBackup,
TAddPeerReq,
TBroadcastTransaction,
TBroadcastTransactionEvent,
TChannelManagerChannelClosed,
TChannelManagerDiscardFunding,
TChannelManagerFundingGenerationReady,
TChannelManagerOpenChannelRequest,
TChannelManagerPayment,
TChannelManagerPaymentFailed,
TChannelManagerPaymentPathFailed,
TChannelManagerPaymentPathSuccessful,
TChannelManagerPaymentSent,
TChannelManagerPendingHtlcsForwardable,
TChannelManagerSpendableOutputs,
TGetAddress,
TGetScriptPubKeyHistory,
TGetScriptPubKeyHistoryResponse,
TGetBestBlock,
TGetTransactionData,
THeader,
TLdkPeers,
TLdkStart,
TPeer,
TRegisterOutputEvent,
TRegisterTxEvent,
TTransactionData,
TLdkConfirmedOutputs,
TLdkConfirmedTransactions,
TLdkBroadcastedTransactions,
TChannelUpdate,
TPaymentReq,
TPaymentTimeoutReq,
TLdkPaymentIds,
TNetworkGraphUpdated,
TGetTransactionPosition,
TTransactionPosition,
TChannel,
} from './utils/types';
import {
appendPath,
parseData,
promiseTimeout,
startParamCheck,
} from './utils/helpers';
import * as bitcoin from 'bitcoinjs-lib';
import { networks } from 'bitcoinjs-lib';
import { EmitterSubscription } from 'react-native';
//TODO startup steps
// Step 0: Listen for events ✅
// Step 1: Initialize the FeeEstimator ✅
// Step 2: Initialize the Logger ✅
// Step 3: Initialize the BroadcasterInterface ✅
// Step 4: Initialize Persist ✅
// Step 5: Initialize the ChainMonitor ✅
// Step 6: Initialize the KeysManager ✅
// Step 7: Read ChannelMonitor state from disk ✅
// Step 8: Initialize the ChannelManager ✅
// Step 9: Sync ChannelMonitors and ChannelManager to chain tip ✅
// Step 10: Give ChannelMonitors to ChainMonitor ✅
// Step 11: Optional: Initialize the NetGraphMsgHandler [Not required for a non routing node]
// Step 12: Initialize the PeerManager ✅
// Step 13: Initialize networking ✅
// Step 14: Connect and Disconnect Blocks ✅
// Step 15: Handle LDK Events ✅
// Step 16: Initialize routing ProbabilisticScorer [Not sure if required]
// Step 17: Create InvoicePayer ✅
// Step 18: Persist ChannelManager and NetworkGraph ✅
// Step 19: Background Processing
class LightningManager {
currentBlock: THeader = {
hex: '',
hash: '',
height: 0,
};
watchTxs: TRegisterTxEvent[] = [];
watchOutputs: TRegisterOutputEvent[] = [];
getBestBlock: TGetBestBlock = async (): Promise<THeader> => ({
hex: '',
hash: '',
height: 0,
});
account: TAccount = {
name: '',
seed: '',
};
backupSubscriptions: {
[id: string]: (backup: Result<TAccountBackup>) => void;
} = {};
backupSubscriptionsId = 0;
backupSubscriptionsDebounceTimer: NodeJS.Timeout | undefined = undefined;
getTransactionData: TGetTransactionData =
async (): Promise<TTransactionData> => DefaultTransactionDataShape;
getTransactionPosition: TGetTransactionPosition =
async (): Promise<TTransactionPosition> => -1;
network: ENetworks = ENetworks.regtest;
baseStoragePath = '';
logFilePath = '';
getAddress: TGetAddress = async (): Promise<string> => '';
getScriptPubKeyHistory: TGetScriptPubKeyHistory = async (): Promise<
TGetScriptPubKeyHistoryResponse[]
> => [];
broadcastTransaction: TBroadcastTransaction = async (): Promise<any> => {};
feeRate: number = 1000; // feerate_sat_per_1000_weight
pathFailedSubscription: EmitterSubscription | undefined;
paymentFailedSubscription: EmitterSubscription | undefined;
paymentSentSubscription: EmitterSubscription | undefined;
constructor() {
// Step 0: Subscribe to all events
ldk.onEvent(EEventTypes.native_log, (line) => {
if (line.indexOf('Could not locate file at') > -1) {
//Not an important error
return;
}
console.log(`react-native-ldk: ${line}`);
});
ldk.onEvent(EEventTypes.ldk_log, (line) => console.log(`LDK: ${line}`));
ldk.onEvent(EEventTypes.register_tx, this.onRegisterTx.bind(this));
ldk.onEvent(EEventTypes.register_output, this.onRegisterOutput.bind(this));
ldk.onEvent(
EEventTypes.broadcast_transaction,
this.onBroadcastTransaction.bind(this),
);
ldk.onEvent(EEventTypes.backup, this.onLdkBackupEvent.bind(this));
//Channel manager handle events:
ldk.onEvent(
EEventTypes.channel_manager_funding_generation_ready,
this.onChannelManagerFundingGenerationReady.bind(this),
);
ldk.onEvent(
EEventTypes.channel_manager_payment_received,
this.onChannelManagerPaymentReceived.bind(this),
);
ldk.onEvent(
EEventTypes.channel_manager_payment_sent,
this.onChannelManagerPaymentSent.bind(this),
);
ldk.onEvent(
EEventTypes.channel_manager_open_channel_request,
this.onChannelManagerOpenChannelRequest.bind(this),
);
ldk.onEvent(
EEventTypes.channel_manager_payment_path_successful,
this.onChannelManagerPaymentPathSuccessful.bind(this),
);
ldk.onEvent(
EEventTypes.channel_manager_payment_path_failed,
this.onChannelManagerPaymentPathFailed.bind(this),
);
ldk.onEvent(
EEventTypes.channel_manager_payment_failed,
this.onChannelManagerPaymentFailed.bind(this),
);
ldk.onEvent(
EEventTypes.channel_manager_pending_htlcs_forwardable,
this.onChannelManagerPendingHtlcsForwardable.bind(this),
);
ldk.onEvent(
EEventTypes.channel_manager_spendable_outputs,
this.onChannelManagerSpendableOutputs.bind(this),
);
ldk.onEvent(
EEventTypes.channel_manager_channel_closed,
this.onChannelManagerChannelClosed.bind(this),
);
ldk.onEvent(
EEventTypes.channel_manager_discard_funding,
this.onChannelManagerDiscardFunding.bind(this),
);
ldk.onEvent(
EEventTypes.channel_manager_payment_claimed,
this.onChannelManagerPaymentClaimed.bind(this),
);
ldk.onEvent(
EEventTypes.emergency_force_close_channel,
this.onEmergencyForceCloseChannel.bind(this),
);
ldk.onEvent(
EEventTypes.network_graph_updated,
this.onNetworkGraphUpdated.bind(this),
);
}
/**
* Sets storage path on disk where all wallet accounts will be
* stored in subdirectories
* @param path
* @returns {Promise<Ok<string>>}
*/
async setBaseStoragePath(path: string): Promise<Result<string>> {
const storagePath = appendPath(path, ''); //Adds slash if missing
//Storage path will be validated and created when calling ldk.setAccountStoragePath
this.baseStoragePath = storagePath;
return ok('Storage set');
}
/**
* Spins up and syncs all processes
* @param {string} seed
* @param {string} genesisHash
* @param {TGetBestBlock} getBestBlock
* @param {TGetTransactionData} getTransactionData
* @param {TGetAddress} getAddress
* @param {ENetworks} network
* @returns {Promise<Result<string>>}
*/
async start({
account,
genesisHash,
getBestBlock,
getTransactionData,
getTransactionPosition,
getAddress,
getScriptPubKeyHistory,
broadcastTransaction,
network,
feeRate = this.feeRate,
}: TLdkStart): Promise<Result<string>> {
if (!account) {
return err(
'No account provided. Please pass an account object containing the name & seed to the start method and try again.',
);
}
if (!account?.name || !account?.seed) {
return err(
'No account name or seed provided. Please pass an account object containing the name & seed to the start method and try again.',
);
}
if (!getBestBlock) {
return err('getBestBlock method not specified in start method.');
}
if (!genesisHash) {
return err(
'No genesisHash provided. Please pass genesisHash to the start method and try again.',
);
}
if (!getTransactionData) {
return err('getTransactionData is not set in start method.');
}
if (!getTransactionPosition) {
return err('getTransactionPosition is not set in start method.');
}
// Ensure the start params function as expected.
const paramCheckResponse = await startParamCheck({
account,
genesisHash,
getBestBlock,
getTransactionData,
getTransactionPosition,
broadcastTransaction,
getAddress,
getScriptPubKeyHistory,
network,
});
if (paramCheckResponse.isErr()) {
return err(paramCheckResponse.error.message);
}
this.getBestBlock = getBestBlock;
this.account = account;
this.network = network;
this.feeRate = feeRate;
this.getAddress = getAddress;
this.getScriptPubKeyHistory = getScriptPubKeyHistory;
this.broadcastTransaction = broadcastTransaction;
this.getTransactionData = getTransactionData;
this.getTransactionPosition = getTransactionPosition;
const bestBlock = await this.getBestBlock();
this.watchTxs = [];
this.watchOutputs = [];
if (!this.baseStoragePath) {
return err(
'baseStoragePath required for wallet persistence. Call setBaseStoragePath(path) first.',
);
}
let accountStoragePath = appendPath(this.baseStoragePath, account.name);
this.logFilePath = `${accountStoragePath}/logs/${Date.now()}.log`;
const logFilePathRes = await ldk.setLogFilePath(this.logFilePath);
if (logFilePathRes.isErr()) {
return logFilePathRes;
}
//The path all wallet and network graph persistence will be saved to
const storagePathRes = await ldk.setAccountStoragePath(accountStoragePath);
if (storagePathRes.isErr()) {
return storagePathRes;
}
//Validate we didn't change the seed for this account if one exists
const readSeed = await ldk.readFromFile({
fileName: ELdkFiles.seed,
format: 'hex',
});
if (readSeed.isErr()) {
if (readSeed.code === 'file_does_not_exist') {
//Have not yet saved the seed to disk
const writeRes = await ldk.writeToFile({
fileName: ELdkFiles.seed,
content: account.seed,
format: 'hex',
});
if (writeRes.isErr()) {
return err(writeRes.error);
}
} else {
return err(readSeed.error);
}
} else {
//Cannot start an existing node with a different seed
if (readSeed.value.content !== account.seed) {
return err('Seed for current node cannot be changed.');
}
}
// Step 1: Initialize the FeeEstimator
// Lazy loaded in native code
// https://docs.rs/lightning/latest/lightning/chain/chaininterface/trait.FeeEstimator.html
// Set fee estimates
const feeUpdateRes = await ldk.updateFees({
highPriority: 12500,
normal: 12500,
background: 12500,
});
if (feeUpdateRes.isErr()) {
return feeUpdateRes;
}
// Step 2: Initialize the Logger
// Lazy loaded in native code
// https://docs.rs/lightning/latest/lightning/util/logger/index.html
//Switch on log levels we're interested in. All levels are false by default.
await ldk.setLogLevel(ELdkLogLevels.info, true);
await ldk.setLogLevel(ELdkLogLevels.warn, true);
await ldk.setLogLevel(ELdkLogLevels.error, true);
await ldk.setLogLevel(ELdkLogLevels.debug, true);
//TODO might not always need this one as they make the logs a little noisy
// await ldk.setLogLevel(ELdkLogLevels.trace, true);
// Step 3: Initialize the BroadcasterInterface
// Lazy loaded in native code
// https://docs.rs/lightning/latest/lightning/chain/chaininterface/trait.BroadcasterInterface.html
// Step 4: Initialize Persist
// Lazy loaded in native code
// https://docs.rs/lightning/latest/lightning/chain/chainmonitor/trait.Persist.html
// Step 5: Initialize the ChainMonitor
const chainMonitorRes = await ldk.initChainMonitor();
if (chainMonitorRes.isErr()) {
return chainMonitorRes;
}
// Step 6: Initialize the KeysManager
const keysManager = await ldk.initKeysManager(this.account.seed);
if (keysManager.isErr()) {
return keysManager;
}
// Step 7: Read ChannelMonitors state from disk
// Handled in initChannelManager below
//TODO allow users to override
let rapidGossipSyncUrl = '';
if (network === 'mainnet') {
rapidGossipSyncUrl = 'https://rapidsync.lightningdevkit.org/snapshot/';
}
// Step 11: Optional: Initialize the NetGraphMsgHandler
const networkGraphRes = await ldk.initNetworkGraph({
genesisHash,
rapidGossipSyncUrl,
});
if (networkGraphRes.isErr()) {
return networkGraphRes;
}
// Step 8: Initialize the UserConfig ChannelManager
const confRes = await ldk.initConfig({
acceptInboundChannels: true,
manuallyAcceptInboundChannels: false,
announcedChannels: false,
minChannelHandshakeDepth: 1, //TODO Verify correct min
forceAnnouncedChannelPreference: false,
});
if (confRes.isErr()) {
return confRes;
}
const channelManagerRes = await ldk.initChannelManager({
network: this.network,
bestBlock,
});
if (channelManagerRes.isErr()) {
return channelManagerRes;
}
// Attempt to abandon any stored payment ids.
const paymentIds = await this.getLdkPaymentIds();
if (paymentIds.length) {
await Promise.all(
paymentIds.map(async (paymentId) => {
await ldk.abandonPayment(paymentId);
await this.removeLdkPaymentId(paymentId);
}),
);
}
// Add Peers
const peers = await this.getPeers();
await Promise.all(
peers.map((peer: TPeer) => {
this.addPeer({ ...peer, timeout: 4000 });
}),
);
// Step 9: Sync ChannelMonitors and ChannelManager to chain tip
await this.syncLdk();
// Step 10: Give ChannelMonitors to ChainMonitor
// Step 12: Initialize the PeerManager
// Done with initChannelManager
// Step 13: Initialize networking
// Done with initChannelManager
return ok('Node running');
}
/**
* Fetches current best block and sends to LDK to update both channelManager and chainMonitor.
* Also watches transactions and outputs for confirmed and unconfirmed transactions and updates LDK.
* @returns {Promise<Result<string>>}
*/
async syncLdk(): Promise<Result<string>> {
if (!this.getBestBlock) {
return err('No getBestBlock method provided.');
}
const bestBlock = await this.getBestBlock();
const header = bestBlock?.hex;
const height = bestBlock?.height;
//Don't update unnecessarily
if (this.currentBlock.hash !== bestBlock?.hash) {
const syncToTip = await ldk.syncToTip({
header,
height,
});
if (syncToTip.isErr()) {
return syncToTip;
}
this.currentBlock = bestBlock;
}
const confirmedTxs = await this.getLdkConfirmedTxs();
let channels: TChannel[] = [];
if (this.watchTxs.length > 0) {
// Get fresh array of channels.
const listChannelsResponse = await ldk.listChannels();
if (listChannelsResponse.isOk()) {
channels = listChannelsResponse.value;
}
}
// Iterate over watch transactions and set whether they are confirmed or unconfirmed.
await Promise.all(
this.watchTxs.map(async ({ txid }) => {
if (confirmedTxs.includes(txid)) {
return;
}
let requiredConfirmations = 6;
const channel = channels.find((c) => c.funding_txid === txid);
if (channel && channel?.confirmations_required !== undefined) {
requiredConfirmations = channel.confirmations_required;
}
const txData = await this.getTransactionData(txid);
if (!txData?.header || !txData.transaction) {
return err(
'Unable to retrieve transaction data from the getTransactionData method.',
);
}
const txConfirmations =
txData.height === 0 ? 0 : height - txData.height + 1;
if (txConfirmations >= requiredConfirmations) {
const pos = await this.getTransactionPosition({
tx_hash: txid,
height: txData.height,
});
if (pos >= 0) {
await ldk.setTxConfirmed({
header: txData.header,
height: txData.height,
txData: [{ transaction: txData.transaction, pos }],
});
await this.saveConfirmedTxs(txid);
this.watchTxs = this.watchTxs.filter((tx) => tx.txid !== txid);
}
}
}),
);
const confirmedWatchOutputs = await this.getLdkConfirmedOutputs();
await Promise.all(
this.watchOutputs.map(async ({ index, script_pubkey }) => {
if (confirmedWatchOutputs.includes(script_pubkey)) {
return;
}
const transactions = await this.getScriptPubKeyHistory(script_pubkey);
await Promise.all(
transactions.map(async ({ txid }) => {
const transactionData = await this.getTransactionData(txid);
if (
!transactionData?.height &&
transactionData?.vout?.length < index + 1
) {
return;
}
const txs = await this.getScriptPubKeyHistory(
transactionData?.vout[index].hex,
);
// We're looking for the second transaction from this address.
if (txs.length <= 1) {
return;
}
// We only need the second transaction.
const tx = txs[1];
const txData = await this.getTransactionData(tx.txid);
if (!txData?.height) {
return;
}
const pos = await this.getTransactionPosition({
tx_hash: tx.txid,
height: txData.height,
});
if (pos >= 0) {
await ldk.setTxConfirmed({
header: txData.header,
height: txData.height,
txData: [{ transaction: txData.transaction, pos }],
});
await this.saveConfirmedOutputs(script_pubkey);
this.watchOutputs = this.watchOutputs.filter(
(o) => o.script_pubkey !== script_pubkey,
);
}
}),
);
}),
);
return ok(`Synced to block ${height}`);
}
/**
* Passes a peer to LDK to add and saves it to storage if successful.
* @param {string} pubKey
* @param {string} address
* @param {number} port
* @param {number} timeout
* @returns {Promise<Result<string>>}
*/
addPeer = async ({
pubKey,
address,
port,
timeout,
}: TAddPeerReq): Promise<Result<string>> => {
const peer: TPeer = { pubKey, address, port };
const addPeerResponse = await ldk.addPeer({
...peer,
timeout,
});
if (addPeerResponse.isErr()) {
return err(addPeerResponse.error.message);
}
this.saveLdkPeerData(peer).then().catch(console.error);
return ok(addPeerResponse.value);
};
/**
* Removes the specified peer from storage.
* @param {string} pubKey
* @param {string} address
* @param {number} port
* @returns {Promise<Result<TPeer[]>>}
*/
removePeer = async ({
pubKey,
address,
port,
}: TAddPeerReq): Promise<Result<TPeer[]>> => {
const peers = await this.getPeers();
const newPeers = peers.filter(
(p) => p.pubKey !== pubKey && p.address !== address && p.port !== port,
);
const writeRes = await ldk.writeToFile({
fileName: ELdkFiles.peers,
content: JSON.stringify(newPeers),
});
if (writeRes.isErr()) {
return err(writeRes.error);
}
return ok(newPeers);
};
/**
* Returns saved peers from storage for the current seed.
* @returns {Promise<TLdkPeers>}
*/
getPeers = async (): Promise<TLdkPeers> => {
const res = await ldk.readFromFile({ fileName: ELdkFiles.peers });
if (res.isOk()) {
return parseData(res.value.content, DefaultLdkDataShape.peers);
}
return DefaultLdkDataShape.peers;
};
/**
* This method is used to import backups provided by react-native-ldk's backupAccount method.
* @param {TAccountBackup} accountData
* @param {string} storagePath Default LDK storage path on disk
* @param {boolean} [overwrite] Determines if this function should overwrite an existing account of the same name.
* @returns {Promise<Result<TAccount>>} TAccount is used to start the node using the newly imported and saved data.
*/
importAccount = async ({
backup,
overwrite = false,
}: {
backup: string | TAccountBackup;
overwrite?: boolean;
}): Promise<Result<TAccount>> => {
if (!this.baseStoragePath) {
return err(
'baseStoragePath required for wallet persistence. Call setBaseStoragePath(path) first.',
);
}
try {
if (!backup) {
return err('No backup was provided for import.');
}
let accountBackup: TAccountBackup;
if (typeof backup === 'string') {
try {
accountBackup = JSON.parse(backup);
} catch {
return err('Invalid backup string.');
}
} else if (typeof backup === 'object') {
// It's possible the dev passed the TAccountBackup object instead of the JSON string.
accountBackup = backup;
} else {
return err('Invalid backup. Unable to import.');
}
if (!accountBackup?.account.name) {
return err('No account name was provided in the accountBackup object.');
}
if (!accountBackup?.account.seed) {
return err('No seed was provided in the accountBackup object.');
}
if (!accountBackup?.data) {
return err('No data was provided in the accountBackup object.');
}
if (
!(ELdkData.channel_manager in accountBackup.data) ||
!(ELdkData.channel_monitors in accountBackup.data) ||
!(ELdkData.peers in accountBackup.data) ||
!(ELdkData.confirmed_outputs in accountBackup.data) ||
!(ELdkData.confirmed_transactions in accountBackup.data) ||
!(ELdkData.broadcasted_transactions in accountBackup.data) ||
!(ELdkData.payment_ids in accountBackup.data) ||
!(ELdkData.timestamp in accountBackup.data)
) {
return err(
`Invalid account backup data. Please ensure the following keys exist in the accountBackup object: ${ELdkData.channel_manager}, ${ELdkData.channel_monitors}, ${ELdkData.peers}, ${ELdkData.confirmed_transactions}, , ${ELdkData.confirmed_outputs}`,
);
}
const accountPath = appendPath(
this.baseStoragePath,
accountBackup.account.name,
);
// Ensure the user is not attempting to import an old/stale backup.
let timestamp = 0;
const channelManagerRes = await ldk.readFromFile({
fileName: ELdkFiles.channel_manager,
path: accountPath,
format: 'hex',
});
if (
channelManagerRes.isErr() &&
channelManagerRes.code !== 'file_does_not_exist' // If the file doesn't exist assume there's no backup to be overwritten
) {
return err(channelManagerRes.error);
}
if (!overwrite && accountBackup.data?.timestamp <= timestamp) {
const msg =
accountBackup.data?.timestamp < timestamp
? 'This appears to be an old backup. The stored backup is more recent than the backup trying to be imported.'
: 'No need to import. The backup timestamps match.';
return err(msg);
}
//Save the provided backup data to files
const saveChannelManagerRes = await ldk.writeToFile({
fileName: ELdkFiles.channel_manager,
path: accountPath,
content: accountBackup.data.channel_manager,
format: 'hex',
});
if (saveChannelManagerRes.isErr()) {
return err(saveChannelManagerRes.error);
}
let channelIds = Object.keys(accountBackup.data.channel_monitors);
for (let index = 0; index < channelIds.length; index++) {
const channelId = channelIds[index];
const saveChannelRes = await ldk.writeToFile({
fileName: `${channelId}.bin`,
path: appendPath(accountPath, ELdkFiles.channels),
content: accountBackup.data.channel_monitors[channelId],
format: 'hex',
});
if (saveChannelRes.isErr()) {
return err(saveChannelRes.error);
}
}
const savePeersRes = await ldk.writeToFile({
fileName: ELdkFiles.peers,
path: accountPath,
content: JSON.stringify(accountBackup.data.peers),
});
if (savePeersRes.isErr()) {
return err(savePeersRes.error);
}
const savePaymentIdsRes = await ldk.writeToFile({
fileName: ELdkFiles.payment_ids,
path: accountPath,
content: JSON.stringify(accountBackup.data.payment_ids),
});
if (savePaymentIdsRes.isErr()) {
return err(savePaymentIdsRes.error);
}
const confirmedTxRes = await ldk.writeToFile({
fileName: ELdkFiles.confirmed_transactions,
path: accountPath,
content: JSON.stringify(accountBackup.data.confirmed_transactions),
});
if (confirmedTxRes.isErr()) {
return err(confirmedTxRes.error);
}
const confirmedOutRes = await ldk.writeToFile({
fileName: ELdkFiles.confirmed_outputs,
path: accountPath,
content: JSON.stringify(accountBackup.data.confirmed_outputs),
});
if (confirmedOutRes.isErr()) {
return err(confirmedOutRes.error);
}
const broadcastedTxRes = await ldk.writeToFile({
fileName: ELdkFiles.broadcasted_transactions,
path: accountPath,
content: JSON.stringify(accountBackup.data.broadcasted_transactions),
});
if (broadcastedTxRes.isErr()) {
return err(broadcastedTxRes.error);
}
//Return the saved account info.
return ok(accountBackup.account);
} catch (e) {
return err(e);
}
};
/**
* Used to back up the data that corresponds with the provided account.
* @param {TAccount} account
* @returns {TAccountBackup} This object can be stringified and used to import/restore this LDK account via importAccount.
*/
backupAccount = async ({
account,
}: {
account: TAccount;
}): Promise<Result<TAccountBackup>> => {
if (!this.baseStoragePath) {
return err(
'baseStoragePath required for wallet persistence. Call setBaseStoragePath(path) first.',
);
}
try {
if (!account || !this?.account) {
return err(
'No account provided. Please pass an account object containing the name & seed to the start method and try again.',
);
}
if (!account) {
account = this.account;
}
if (!account?.name || !account?.seed) {
return err(
'No account name or seed provided. Please pass an account object containing the name & seed to the start method and try again.',
);
}
const accountPath = appendPath(this.baseStoragePath, account.name);
//Get serialised channel manager
const channelManagerRes = await ldk.readFromFile({
fileName: ELdkFiles.channel_manager,
path: accountPath,
format: 'hex',
});
if (channelManagerRes.isErr()) {
return err(channelManagerRes.error);
}
//Get serialised channels
const listChannelsRes = await ldk.listChannelFiles();
if (listChannelsRes.isErr()) {
return err(listChannelsRes.error);
}
let channel_monitors: { [key: string]: string } = {};
for (let index = 0; index < listChannelsRes.value.length; index++) {
const fileName = listChannelsRes.value[index];
const serialisedChannelRes = await ldk.readFromFile({
fileName,
path: appendPath(accountPath, ELdkFiles.channels),
format: 'hex',
});
if (serialisedChannelRes.isErr()) {
return err(serialisedChannelRes.error);
}
channel_monitors[fileName.replace('.bin', '')] =
serialisedChannelRes.value.content;
}
const accountBackup: TAccountBackup = {
account,
data: {
channel_manager: channelManagerRes.value.content,
channel_monitors: channel_monitors,
peers: await this.getPeers(),
confirmed_transactions: await this.getLdkConfirmedTxs(),
confirmed_outputs: await this.getLdkConfirmedOutputs(),
broadcasted_transactions: await this.getLdkBroadcastedTxs(),
payment_ids: await this.getLdkPaymentIds(),
timestamp: Date.now(),
},
package_version: require('../package.json').version,
network: this.network,
};
return ok(accountBackup);
} catch (e) {
return err(e);
}
};
/**
* ldk.pay helper that subscribes to and returns pay event success/failures and times out after a specified period of time.
* @param {string} paymentRequest
* @param {number} [amountSats]
* @param {number} [timeout]
* @returns {Promise<Result<TChannelManagerPaymentSent>>}
*/
payWithTimeout = async ({
paymentRequest,
amountSats,
timeout = 20000,
}: TPaymentTimeoutReq): Promise<Result<TChannelManagerPaymentSent>> => {
return promiseTimeout(
timeout,
this.subscribeAndPay({ paymentRequest, amountSats }),
);
};
private subscribeAndPay = async ({
paymentRequest,
amountSats,
}: TPaymentReq): Promise<Result<TChannelManagerPaymentSent>> => {
return new Promise(async (resolve) => {
this.subscribeToPaymentResponses(resolve).then();
const payResponse: Result<string> | undefined = await ldk.pay({
paymentRequest,
amountSats,
});
if (!payResponse) {
this.unsubscribeFromPaymentSubscriptions();
return resolve(err('Unable to pay the provided lightning invoice.'));
}
if (payResponse.isErr()) {
this.unsubscribeFromPaymentSubscriptions();
return resolve(err(payResponse.error.message));
}
//Save payment ids to file on payResponse success.
await this.appendLdkPaymentId(payResponse.value);
});
};
/**
* Subscribes to outgoing lightning payments.
* @returns {Promise<Result<TChannelManagerPaymentSent>>}
*/
private subscribeToPaymentResponses = async (resolve: any): Promise<void> => {
this.pathFailedSubscription = ldk.onEvent(
EEventTypes.channel_manager_payment_path_failed,
async (res: TChannelManagerPaymentPathFailed) => {
this.unsubscribeFromPaymentSubscriptions();
const abandonPaymentRes = await ldk.abandonPayment(res.payment_id);
if (abandonPaymentRes.isOk()) {
this.removeLdkPaymentId(res.payment_id).then();
}
return resolve(err(res.payment_id));
},
);
this.paymentFailedSubscription = ldk.onEvent(
EEventTypes.channel_manager_payment_failed,
async (res: TChannelManagerPaymentFailed) => {
this.unsubscribeFromPaymentSubscriptions();
const abandonPaymentRes = await ldk.abandonPayment(res.payment_id);
if (abandonPaymentRes.isOk()) {
this.removeLdkPaymentId(res.payment_id).then();
}
return resolve(err(res.payment_id));
},
);
this.paymentSentSubscription = ldk.onEvent(
EEventTypes.channel_manager_payment_sent,
(res: TChannelManagerPaymentSent) => {
this.unsubscribeFromPaymentSubscriptions();
this.removeLdkPaymentId(res.payment_id).then();
return resolve(ok(res));
},
);
};
unsubscribeFromPaymentSubscriptions = (): void => {
this.pathFailedSubscription && this.pathFailedSubscription.remove();
this.paymentFailedSubscription && this.paymentFailedSubscription.remove();
this.paymentSentSubscription && this.paymentSentSubscription.remove();
};
/**
* Subscribe to back up events and receive full backups to callback passed
* @param callback
* @returns {string}
*/
subscribeToBackups(
callback: (backup: Result<TAccountBackup>) => void,
): string {
this.backupSubscriptionsId++;
const id = `${this.backupSubscriptionsId}`;
this.backupSubscriptions[id] = callback;
return id;
}