forked from itsneski/lightning-jet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjet
executable file
·1325 lines (1195 loc) · 53 KB
/
jet
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
#!/usr/bin/env node
const cap = require('caporal');
const importLazy = require('import-lazy')(require);
const {version} = importLazy('./package');
const lndClient = importLazy('./api/connect');
const {listActiveRebalancesFormattedSync} = importLazy('./api/utils');
const {rebalanceHistoryFormattedSync} = importLazy('./api/utils');
const {pendingHtlcsFormattedSync} = importLazy('./api/utils');
const {listForcedClosingFormattedSync} = importLazy('./api/utils');
const {listPeersFormattedSync} = importLazy('./api/utils');
const {readLastLineSync} = importLazy('./api/utils');
const {withCommas} = importLazy('./lnd-api/utils');
const {listFeesSync} = importLazy('./lnd-api/utils');
const {listPeersSync} = importLazy('./lnd-api/utils');
const {listPeersMapSync} = importLazy('./lnd-api/utils');
const {listChannelsSync} = importLazy('./lnd-api/utils');
const {closeChannel} = importLazy('./lnd-api/utils');
const {updateChannelSync} = importLazy('./lnd-api/update-channel');
const {listChannels} = importLazy('./api/list-channels');
const {htlcHistoryFormatted} = importLazy('./api/htlc-history');
const {htlcAnalyzerFormatted} = importLazy('./api/htlc-analyzer');
const {htlcAnalyzerNode} = importLazy('./api/htlc-analyzer');
const {classifyPeersSync} = importLazy('./api/utils');
const {resolveNode} = importLazy('./api/utils');
const {resolveChannel} = importLazy('./api/utils');
const {feeHistorySync} = importLazy('./db/utils');
const {listChannelEvents} = importLazy('./db/utils');
const {latestChannelEvents} = importLazy('./db/utils');
const {statSync} = require('fs');
const date = require('date-and-time');
const serviceUtils = importLazy('./service/utils');
const {getServiceNames} = importLazy('./service/utils');
const {stopService} = importLazy('./service/utils');
const {startService} = importLazy('./service/utils');
const {restartService} = importLazy('./service/utils');
const {printStatus} = importLazy('./service/utils');
const {rebalanceStatus} = importLazy('./api/analyze-fees');
const constants = importLazy('./api/constants');
const config = importLazy('./api/config');
const rebalanceApi = importLazy('./api/rebalance');
const {reconnect} = importLazy('./bos/reconnect');
const {isLndAlive} = importLazy('./lnd-api/utils');
const {inactiveChannels} = importLazy('./api/list-channels');
const {REPEATABLE} = cap;
const {INT} = cap;
const isInt = value => {
var x = parseFloat(value);
return !isNaN(value) && (x | 0) === x;
}
// service names, plus all for restart
const serviceNames = getServiceNames();
var serviceNamesPlus = serviceNames.slice();
serviceNamesPlus.push('all');
cap
.version(version)
.command('info', 'Information about this node, another node, or a channel')
.argument('[id]', 'Node id, node partial alias, or channel id')
.option('--db', 'Lists db tables sorted by size')
.help('Returns various node or channel stats')
.action((args, options, logger) => {
return new Promise(async (resolve, reject) => {
if (options.db) {
// print db stats
const {stats} = require('./db/utils');
console.log('list of database tables sorted by [on-disk] size:');
console.table(stats());
return;
}
if (!isLndAlive(lndClient)) return reject('lnd is offline');
const {withCommas} = require('./lnd-api/utils');
const {getChanInfo} = require('./lnd-api/utils');
const {getNodeInfoSync} = require('./lnd-api/utils');
const {getInfoSync} = require('./lnd-api/utils');
if (args.id) {
// locate node or channel
let matches = resolveNode(args.id);
if (matches && matches.length > 0) {
if (matches.length > 1) return console.log('multiple node matches found; narrow your selection');
printNode(matches[0].id);
} else {
// try to resolve channel
matches = resolveChannel(args.id);
if (matches && matches.length > 0) {
if (matches.length > 1) return console.error('multiple channel matches found; narrow your selection');
printChan(matches[0]);
} else {
// no matches out of existing peers, query for node id directly
if (printNode(args.id)) {
// already printed node stats
} else if (printChan(args.id)) {
// already printed chan stats
} else {
console.log('no matches found');
}
}
}
return;
function printNode(id) {
try {
const info = getNodeInfoSync(lndClient, id).info;
if (!info) return;
console.log('pub id:', info.node.pub_key);
console.log('name:', info.node.alias);
console.log('total chans:', info.num_channels);
console.log('total capacity:', withCommas(info.total_capacity), '(sats)');
return info;
} catch(err) {
// no need to print error
}
}
function printChan(id) {
try {
const info = getChanInfo(lndClient, id);
if (!info) return;
console.log('chan id:', info.chan.channel_id);
console.log('capacity:', withCommas(info.chan.capacity));
const myNode = getInfoSync(lndClient).identity_pubkey;
const peer1 = getNodeInfoSync(lndClient, info.chan.node1_pub);
const peer2 = getNodeInfoSync(lndClient, info.chan.node2_pub);
if (peer1.info.node.pub_key === myNode) {
console.log('peer:', peer2.info.node.alias + ', ' + peer2.info.node.pub_key);
} else if (peer2.info.node.pub_key === myNode) {
console.log('peer:', peer1.info.node.alias + ', ' + peer1.info.node.pub_key);
} else {
console.log('peer1:', peer1.info.node.alias + ', ' + peer1.info.node.pub_key);
console.log('peer2:', peer2.info.node.alias + ', ' + peer2.info.node.pub_key);
}
return info;
} catch(err) {
// no need to print error
}
}
}
const nodeInfo = getInfoSync(lndClient);
const {walletBalance} = require('./lnd-api/utils');
const balance = walletBalance(lndClient);
const {checkSize} = require('./api/channeldb');
const check = checkSize();
const {jetDbStats} = require('./api/utils');
const stats = jetDbStats();
console.log('lnd version:', nodeInfo.version);
console.log('node id:', nodeInfo.identity_pubkey);
console.log('node alias:', nodeInfo.alias);
console.log('total chans:', nodeInfo.num_active_channels + nodeInfo.num_inactive_channels);
console.log('--active:', nodeInfo.num_active_channels);
console.log('--inactive:', nodeInfo.num_inactive_channels);
if (balance.response) {
console.log('bitcoin balance (sats):', withCommas(balance.response.total_balance));
console.log('--confirmed:', withCommas(balance.response.confirmed_balance));
console.log('--unconfirmed:', withCommas(balance.response.unconfirmed_balance));
}
if (check.error) console.log('channel.db:', check.error);
else {
const str = (check.size >= 1000) ? withCommas(check.size) + ' gb' : check.size + ' mb'
console.log('channel.db:', str);
}
if (stats) {
console.log('jet.db:', stats.str);
}
})
})
.command('start', 'Starts a service')
.argument('<service>', 'Service; use \'all\' to restart all services', serviceNamesPlus)
.help(`Services: ${serviceNames.join(', ')}`)
.action((args, options, logger) => {
return new Promise(async (resolve, reject) => {
let msg = startService(args.service);
if (msg) console.log(msg);
})
})
.command('stop', 'Stops a service')
.argument('<service>', 'Service; use \'all\' to restart all services', serviceNamesPlus)
.help(`Services: ${serviceNames.join(', ')}`)
.action((args, options, logger) => {
return new Promise(async (resolve, reject) => {
stopService(args.service);
})
})
.command('restart', 'Restarts a service')
.argument('<service>', 'Service; use \'all\' to restart all services', serviceNamesPlus)
.help(`Services: ${serviceNames.join(', ')}`)
.action((args, options, logger) => {
return new Promise(async (resolve, reject) => {
restartService(args.service);
})
})
.command('status', 'Shows services status')
.action((args, options, logger) => {
return new Promise(async (resolve, reject) => {
printStatus();
})
})
.command('stats', 'Shows channel profitability stats')
.option('--days [days]', 'Depth of history in days; max of ' + Math.floor(constants.db.maxTxnDepth/2) + ' days, default ' + Math.floor(constants.defaultTxnInterval/24))
.option('--hours [hours]', 'Depth of history in hours; max of ' + 24 * Math.floor(constants.db.maxTxnDepth/2) + ' days, default ' + Math.floor(constants.defaultTxnInterval/24))
.action((args, options, logger) => {
return new Promise(async (resolve, reject) => {
if (!isLndAlive(lndClient)) return reject('lnd is offline');
const maxDepth = 24 * Math.floor(constants.db.maxTxnDepth/2); // hours
const hours = options.hours || (options.days && options.days * 24) || constants.defaultTxnInterval;
if (hours > maxDepth) return console.error('history depth exceeds the max of ' + maxDepth + ' hours (' + Math.floor(maxDepth/24) + ' days)');
const msec = new Date(new Date().toUTCString()).getTime();
const fromTimestamp = (msec - hours * 60 * 60 * 1000) * Math.pow(10, 6);
const {txnByChanAndType} = require('./db/utils');
const list = txnByChanAndType(fromTimestamp);
if (!list || list.length === 0) return console.log('no records found');
// get historical record to display % change
const fromT = (msec - 2 * hours * 60 * 60 * 1000) * Math.pow(10, 6);
const toT = (msec - hours * 60 * 60 * 1000) * Math.pow(10, 6);
const prevList = txnByChanAndType(fromT, toT);
let historyMap = {};
let historyTotal = {
profit: 0,
inbound: { amount: 0 },
forward: { fee: 0, amount: 0 },
rebalance: { fee: 0, amount: 0 }
}
if (prevList && prevList.length > 0) {
prevList.sort((a, b) => a.txdate_ns - b.txdate_ns);
prevList.forEach(item => {
if (!historyMap[item.chan]) historyMap[item.chan] = {
forward: { fee: 0, amount: 0 },
inbound: { amount: 0 },
rebalance: { fee: 0, amount: 0 }
}
if (item.type === 'forward') {
historyMap[item.chan].forward.fee = item.total_fee;
historyMap[item.chan].forward.amount = item.total_amount;
historyTotal.forward.fee += item.total_fee;
historyTotal.forward.amount += item.total_amount;
} else if (item.type === 'inbound') {
historyMap[item.chan].inbound.amount = item.total_amount;
} else if (item.type === 'rebalance') {
historyMap[item.chan].rebalance.fee = item.total_fee;
historyMap[item.chan].rebalance.amount = item.total_amount;
historyTotal.rebalance.fee += item.total_fee;
historyTotal.rebalance.amount += item.total_amount;
}
historyMap[item.chan].delta = historyMap[item.chan].forward.fee - historyMap[item.chan].rebalance.fee;
})
historyTotal.profit = historyTotal.forward.fee - historyTotal.rebalance.fee;
}
let chanMap = {};
const chans = listChannelsSync(lndClient);
chans.forEach(c => {
chanMap[c.chan_id] = c.remote_pubkey;
})
let peerMap = {};
const peers = listPeersSync(lndClient);
peers.forEach(p => {
peerMap[p.id] = p.name;
})
let map = {};
list.forEach(item => {
const chan = item.chan;
if (!map[chan]) map[chan] = {};
let p = map[chan];
if (item.type === 'forward') {
p.forward = {
amount: item.total_amount,
fee: item.total_fee
}
} else if (item.type === 'inbound') {
p.inbound = {
amount: item.total_amount
}
} else if (item.type === 'rebalance') {
p.rebalance = {
amount: item.total_amount,
fee: item.total_fee
}
}
})
let combined = [];
Object.keys(map).forEach(k => {
let item = {};
item.chan = k;
item.peer = chanMap[k];
item.name = peerMap[chanMap[k]];
if (map[k].forward) item.forward = map[k].forward;
if (map[k].inbound) item.inbound = map[k].inbound;
if (map[k].rebalance) item.rebalance = map[k].rebalance;
const feeForward = (item.forward && item.forward.fee) || 0;
const feeRebalance = (item.rebalance && item.rebalance.fee) || 0;
item.delta = feeForward - feeRebalance;
combined.push(item);
})
// print cumulative stats
const {withCommas} = require('./lnd-api/utils');
let total = 0;
let totalForwarded = { amount: 0, fee: 0 };
let totalRebalanced = { amount: 0, fee: 0 };
combined.forEach(item => {
total += item.delta;
totalForwarded.amount += (item.forward && item.forward.amount) || 0;
totalForwarded.fee += (item.forward && item.forward.fee) || 0;
totalRebalanced.amount += (item.rebalance && item.rebalance.amount) || 0;
totalRebalanced.fee += (item.rebalance && item.rebalance.fee) || 0;
})
let str = 'cumulative stats';
const days = isInt(hours/24) && Math.floor(hours/24);
if (days) str += ' over the past ' + days + ' day(s)';
else str += ' over the past ' + hours + ' hour(s)';
console.log(str + ':');
let cumulative = [];
cumulative.push({
period: 'current',
profit: total,
forwarded: withCommas(totalForwarded.amount),
earned: totalForwarded.fee,
rebalanced: withCommas(totalRebalanced.amount),
paid: totalRebalanced.fee
})
cumulative.push({
period: 'previous',
profit: historyTotal.profit,
forwarded: withCommas(historyTotal.forward.amount),
earned: historyTotal.forward.fee,
rebalanced: withCommas(historyTotal.rebalance.amount),
paid: historyTotal.rebalance.fee
})
console.log('this table displays data for two time periods, current and previous; e.g. display weekly data over the past week along with the data from a week ago');
console.table(cumulative);
// profitable channels
let profitable = [];
combined.forEach(item => {
if (item.delta <= 0) return;
let rec = {
chan: item.chan,
peer: item.name,
profit: item.delta,
inbound: (item.inbound && item.inbound.amount) || 0,
outbound: (item.forward && item.forward.amount) || 0,
earned: (item.forward && item.forward.fee) || 0,
rebalanced: (item.rebalance && item.rebalance.amount) || 0,
paid: (item.rebalance && item.rebalance.fee) || 0,
}
const prev = historyMap[item.chan] && historyMap[item.chan].delta;
if (prev !== undefined && prev !== 0) {
const delta = rec.profit - prev;
if (delta !== 0) {
rec.delta = delta;
}
if (historyMap[item.chan].forward.amount !== 0) rec['delta_fw %'] = Math.round(100 * (rec.outbound - historyMap[item.chan].forward.amount) / historyMap[item.chan].forward.amount);
if (historyMap[item.chan].rebalance.amount !== 0) rec['delta_rb %'] = Math.round(100 * (rec.rebalanced - historyMap[item.chan].rebalance.amount) / historyMap[item.chan].rebalance.amount);
}
profitable.push(rec);
})
profitable.sort((a, b) => b.profit - a.profit);
console.log('\nprofitable channels:');
if (profitable.length === 0) console.log('none found');
else {
console.log('-profit: profit in sats');
console.log('-inbound: total inbound sats')
console.log('-outbound: total outbound sats');
console.log('-earned: total sats earned on forwards (outbound)');
console.log('-rebalanced: total sats rebalanced');
console.log('-paid: total sats paid for rebalances');
console.log('-delta: change in profit (sats) since the last interval; e.g. 15 means that the profit has increased by 15 sats');
console.log('-delta_fw: change in sats (%) forwarded since the last interval; e.g. 25 means that the node forwarded 25% more sats comparing to the last interval');
console.log('-delta_rb: change in sats (%) rebalanced since the last interval; e.g. 25 means that the node rebalanced 25% more sats comparing to the last interval');
console.table(profitable);
}
// unprofitable channels
let unprofitable = [];
combined.forEach(item => {
if (item.delta > 0) return;
let rec = {
chan: item.chan,
peer: item.name,
loss: Math.abs(item.delta), // present loss as a positive integer
inbound: (item.inbound && item.inbound.amount) || 0,
outbound: (item.forward && item.forward.amount) || 0,
earned: (item.forward && item.forward.fee) || 0,
rebalanced: (item.rebalance && item.rebalance.amount) || 0,
paid: (item.rebalance && item.rebalance.fee) || 0,
}
const prev = historyMap[item.chan] && historyMap[item.chan].delta;
if (prev !== undefined && prev !== 0) {
const delta = -(item.delta - prev);
if (delta !== 0) {
rec.delta = delta;
}
if (historyMap[item.chan].forward.amount !== 0) rec['delta_fw %'] = Math.round(100 * (rec.outbound - historyMap[item.chan].forward.amount) / historyMap[item.chan].forward.amount);
if (historyMap[item.chan].rebalance.amount !== 0) rec['delta_rb %'] = Math.round(100 * (rec.rebalanced - historyMap[item.chan].rebalance.amount) / historyMap[item.chan].rebalance.amount);
}
unprofitable.push(rec);
})
unprofitable.sort((a, b) => b.loss - a.loss);
console.log('\nunprofitable channels:');
if (unprofitable.length === 0) console.log('none found');
else {
console.log('-delta: change in loss (sats) since the last interval; e.g. 15 means that the loss has increased by 15 sats');
console.table(unprofitable);
}
})
})
.command('probes', 'Displays nodes (discovered during probes) that have signaled a commitment to liquidity. This tool can be used to identify prospects for new channels.')
.option('--days [days]', 'Depth of history in days')
.option('--hours [hours]', 'Depth of history in hours')
.option('--top [n]', 'Return top n records, default ' + constants.defaultProbeTopN)
.option('--all', 'Return all records')
.option('--peers', 'Shows probe data for current peers (as opposed to new nodes)')
.option('--sort [col]', 'Sort by a column', ['sats_sum', 'count', 'avg_ppm', 'min_ppm', 'max_ppm'])
.action((args, options, logger) => {
return new Promise(async (resolve, reject) => {
if (!isLndAlive(lndClient)) return reject('lnd is offline');
if (options.top && options.top <= 1) return console.error('--top must be above or equal to 1');
const top = (options.all) ? options.top : options.top || constants.defaultProbeTopN;
const hours = (options.all) ? options.hours || (options.days && options.days * 24) : options.hours || (options.days && options.days * 24) || constants.defaultProbeInterval;
const maxInterval = 24 * (config.db.maxProbeDepth || constants.db.maxProbeDepth);
if (hours > maxInterval) return console.error('provided depth exceeds the max of ' + maxInterval + ' hours (' + maxInterval / 24 + ' days)');
const msec = new Date(new Date().toUTCString()).getTime();
const fromDate = hours && (msec - hours * 60 * 60 * 1000);
const sortCol = options.sort || 'count';
const {reportLiquidity} = require('./db/utils');
const list = reportLiquidity(fromDate);
if (!list || list.length === 0) return console.log('no records found');
if (sortCol === 'sats_sum') {
list.sort((a, b) => { return b.sats_sum - a.sats_sum });
} else if (sortCol === 'count') {
list.sort((a, b) => { return b.count - a.count });
} else if (sortCol === 'avg_ppm') {
list.sort((a, b) => { return a.avg_ppm - b.avg_ppm });
} else if (sortCol === 'min_ppm') {
list.sort((a, b) => { return a.min_ppm - b.min_ppm });
} else if (sortCol === 'max_ppm') {
list.sort((a, b) => { return b.max_ppm - a.max_ppm });
} else {
console.error('unknown sort column,', sortCol);
}
const peers = listPeersSync(lndClient);
let peerMap = {};
peers.forEach(p => {
peerMap[p.id] = p;
})
const days = Math.max(1, Math.round(hours / 24));
const classified = classifyPeersSync(lndClient, days);
let cmap = {};
if (classified.inbound) {
classified.inbound.forEach(p => {
cmap[p.peer] = { type: 'inbound', node: p }
})
}
if (classified.outbound) {
classified.outbound.forEach(p => {
cmap[p.peer] = { type: 'outbound', node: p }
})
}
if (classified.balanced) {
classified.balanced.forEach(p => {
cmap[p.peer] = { type: 'low volume', node: p }
})
}
let formatted = [];
list.forEach(item => {
if (!options.peers && peerMap[item.node]) return;
if (options.peers && !peerMap[item.node]) return;
if (peerMap[item.node]) {
let s = {
peer: item.node,
name: peerMap[item.node].name,
count: item.count,
sats_sum: item.sats_sum,
avg_ppm: item.avg_ppm,
min_ppm: item.min_ppm,
max_ppm: item.max_ppm
}
if (cmap[item.node]) {
s.local = withCommas(cmap[item.node].node.local);
s.type = cmap[item.node].type;
}
formatted.push(s);
peerMap[item.node].included = true;
} else {
formatted.push(item);
}
})
if (top) formatted = formatted.slice(0, top);
let str = 'probe data showing nodes that signaled commitment of liquidity\n';
if (options.peers) str += 'analyzing data for existing peers (as opposed to prospects for new channels)\n'
str += 'data generated'
if (hours) {
const days = isInt(hours/24) && Math.floor(hours/24);
if (days) str += ' over the past ' + days + ' day(s)';
else str += ' over the past ' + hours + ' hour(s)';
} else {
str += ' since the beginning'
}
if (top) str += '; returning top ' + top + ' records';
str += '; sorted by ' + sortCol;
console.log(str + '\n');
console.log('-count: total number of times a node signaled commitment of liquidity');
console.log('-sats_sum: total number of sats a node signaled to commit');
console.log('-avg_ppm: average ppm of [commited] liquidity');
if (options.peers) {
console.log('-local: sats on the local side (assumes one channel per peer)');
console.log("-type: peer's classification info inbound, outbound and low-volume");
}
console.table(formatted);
if (options.peers) {
let none = [];
Object.keys(peerMap).forEach(k => {
if (!peerMap[k].included) none.push({peer: k, name: peerMap[k].name});
})
if (none.length > 0) {
console.log('\npeers that havent signaled any commitment of liquidity');
console.table(none);
}
}
})
})
.command('rebalance', 'Rebalances the node via circular rebalance.')
.help('Calls BalanceOfSatoshis rebalance api in a loop until the target amount is met or all possible routes are exhausted.')
.argument('<from>', 'From this peer. Can be a partial alias, a pub id, or a bos tag')
.argument('<to>', 'To this peer. Can be a partial alias, a pub id, or a bos tag')
.argument('<amount>', 'Amount in sats')
.option('--ppm <ppm>', 'Max ppm')
.option('--mins [mins]', 'Max time to run in minutes')
.action((args, options, logger) => {
return new Promise(async (resolve, reject) => {
if (!isLndAlive(lndClient)) return reject('lnd is offline');
const amount = (args.amount < 1000) ? args.amount * 1000000 : args.amount;
try {
rebalanceApi({
from: args.from,
to: args.to,
amount: amount,
ppm: options.ppm,
mins: options.mins
})
} catch(err) {
console.error(err.message);
}
})
})
.command('pay', 'Pay an invoice')
.argument('<request>', 'Payment Request')
.option('--avoid <avoid>', 'Avoid forwarding via node/chan/tag', REPEATABLE)
.option('--in <public_key>', 'Route through specific peer of destination')
.option('--max-fee <max_fee>', 'Maximum fee to pay', INT, 1337)
.option('--max-paths <paths>', 'Maximum paths to use', INT, 1)
.option('--message <message>', 'Attach text message to payment')
.option('--no-color', 'Mute all colors')
.option('--node <node_name>', 'Node to use to pay payment request')
.option('--out <public_key>', 'Make first hop through peer', REPEATABLE)
.action((args, options, logger) => {
return new Promise(async (resolve, reject) => {
if (!isLndAlive(lndClient)) return reject('lnd is offline');
const pay = require('./api/pay');
const ret = pay({
request: args.request,
avoid: options.avoid || [],
in: options.in,
maxFee: options.maxFee,
maxPaths: options.maxPaths,
message: options.message,
node: options.node,
out: options.out || []
})
console.log(ret);
})
})
.command('peers', 'Lists peers classified into inbound, outbound and balanced based on routing history')
.help('Notable columns: p - % of [inbound or outbound] routing by the peer out of total [inbound or outbound] across all peers; ppm - peer\'s current ppm rate; margin - rebalance ppm margin, rebalance will be profitable as long as its ppm is below this margin.')
.option('--days [days]', 'Depth of routing history in days')
.action((args, options, logger) => {
return new Promise(async (resolve, reject) => {
if (!isLndAlive(lndClient)) return reject('lnd is offline');
const days = options.days || 1;
let peers = listPeersFormattedSync(days);
console.log('classification of peers based on past', days, 'day(s):');
console.log('-local: total sats on local side (excluding htlcs)')
console.log('-remote: total sats on remote side (excluding htlcs)')
if (peers.inbound.length > 0) {
console.log('\ninbound peers:');
console.table(peers.inbound);
} else {
console.log('no inbound peers found');
}
if (peers.outbound.length > 0) {
console.log('\noutbound peers:');
console.table(peers.outbound);
} else {
console.log('no outbound peers found');
}
if (peers.balanced.length > 0) {
console.log('\nlow routing volume peers:');
console.table(peers.balanced);
}
if (peers.skipped.length > 0) {
console.log('\nskipped peers:');
console.table(peers.skipped);
}
if (peers.all.length > 0) {
console.log('\nall peers:');
console.table(peers.all);
} else {
console.log('no peers found');
}
})
})
.command('fees', 'Lists peer fees')
.action((args, options, logger) => {
return new Promise(async (resolve, reject) => {
if (!isLndAlive(lndClient)) return reject('lnd is offline');
let fees = listFeesSync(lndClient);
//console.log(classified);
//console.log(fees);
let formatted = [];
fees.forEach(f => {
let name = f.name;
formatted.push({
peer: f.name,
lc_base: f.local.base,
lc_rate: f.local.rate,
rm_base: f.remote.base,
rm_rate: f.remote.rate
})
})
formatted.sort(function(a, b) {
return b.rm_rate - a.rm_rate;
})
console.table(formatted);
})
})
.command('analyze-fees', 'Analyzes peer fees')
.argument('[node]', 'Pub id or an alias (full or partial) of [outbound] node for fee analysis')
.option('--profit [profit]', 'Profit margin in % to evaluate fees against')
.help('Each peers\' channel local and remote fees will be evaluated against the profitability margin')
.action((args, options, logger) => {
return new Promise(async (resolve, reject) => {
if (!isLndAlive(lndClient)) return reject('lnd is offline');
if (options.profit < 0 || options.profit > 100) return console.error('profit has to be between 0 and 100');
const {printFeeAnalysis} = require('./api/analyze-fees');
let classified = classifyPeersSync(lndClient);
let chans = [];
let nodesFound = [];
if (classified.outbound) {
classified.outbound.forEach(c => {
chans.push({chan: c.id, peer: c.peer});
if (args.node) {
let lc1 = c.name && c.name.toLowerCase();
let lc2 = args.node.toLowerCase();
if (args.node === c.peer || (lc1 && lc1.indexOf(lc2) >= 0)) {
nodesFound.push(c);
}
}
})
}
if (classified.balanced) {
classified.balanced.forEach(c => {
chans.push({chan: c.id, peer: c.peer});
if (args.node) {
let lc1 = c.name && c.name.toLowerCase();
let lc2 = args.node.toLowerCase();
if (args.node === c.peer || (lc1 && lc1.indexOf(lc2) >= 0)) {
nodesFound.push(c);
}
}
})
}
if (args.node) {
if (nodesFound.length >= 2) {
let matches = [];
nodesFound.forEach(n => matches.push(n.name));
return console.error('multiple node matches found:', matches);
}
if (nodesFound.length === 0) return console.error('node not found (possibly an inbound node)');
let node = nodesFound[0];
chans = [{chan: node.id, peer: node.peer}];
let fees = listFeesSync(lndClient, chans);
return printFeeAnalysis(node.name, node.peer, fees[0].local, fees[0].remote, options.profit);
}
let fees = listFeesSync(lndClient, chans);
let feeMap = {};
fees.forEach(f => feeMap[f.id] = f);
let msg = 'analyzing fees for [outbound] peers';
msg += (options.profit) ? ' based on profit of ' + options.profit + '%' : '. no profit requirements specified'
console.log('-------------------------------------------------------------')
console.log(msg);
console.log('-------------------------------------------------------------')
let unknownPeers = [];
let count = 0;
classified.outbound.forEach(c => {
console.log(); // newline
if (!feeMap[c.peer]) unknownPeers.push({name: c.name, id: c.peer});
let num = printFeeAnalysis(c.name, c.peer, feeMap[c.peer].local, feeMap[c.peer].remote, options.profit);
count += num;
})
if (count === 0) console.log('no issues to report');
msg = 'analyzing fees for [balanced] peers';
msg += (options.profit) ? ' based on profit of ' + options.profit + '%' : '. no profit requirements specified'
console.log('\n-------------------------------------------------------------')
console.log(msg);
console.log('-------------------------------------------------------------')
count = 0;
classified.balanced.forEach(c => {
console.log(); // newline
if (!feeMap[c.peer]) unknownPeers.push({name: c.name, id: c.peer});
let num = printFeeAnalysis(c.name, c.peer, feeMap[c.peer].local, feeMap[c.peer].remote, options.profit);
count += num;
})
if (count === 0) console.log('no issues to report');
if (unknownPeers.length > 0) {
console.log(constants.colorYellow, '\nunknown fee data for the following peers (excluded):');
unknownPeers.forEach(p => {
console.log(p.name, p.id);
})
}
})
})
.command('htlc-history', 'Prints cumulative htlcs history for peers')
.argument('[days]', 'Depth of history in days')
.help('Prints % of total inbound / outbound routing for each peer (e.g. inbound routing from D++ takes 25% of total inbound traffic across all peers), and % of inbound / outbound routing for a peer (e.g. inbound routing from D++ takes 95% of total routing from D++)')
.action((args, options, logger) => {
return new Promise(async (resolve, reject) => {
if (!isLndAlive(lndClient)) return reject('lnd is offline');
let days = args.days || 7; // hardcoded??
let history = htlcHistoryFormatted(days);
console.log('htlc history over the past', days, 'days');
if (history.unknown) {
console.log('unknown channels:', history.unknown);
}
console.log('inbound routing:');
console.table(history.inbound);
console.log('outbound routing:');
console.table(history.outbound);
if (history.noTraffic) {
console.log('no routing:');
console.table(history.noTraffic);
}
})
})
.command('htlc-analyzer', 'Prints stats about failed htlcs')
.argument('[node]', 'Pub id or an alias (full or partial) of [outbound] node for htlc analysis')
.option('--days [days]', 'Depth of history in days. Can provide partial days, e.g., .5 days (12 hours)')
.option('--hours [hours]', 'Depth of history in hours.')
.action((args, options, logger) => {
return new Promise(async (resolve, reject) => {
if (!isLndAlive(lndClient)) return reject('lnd is offline');
try {
let days = options.days || 1;
days = (options.hours) ? options.hours / 24 : days;
let showDays = isInt(days) ? days : days.toFixed(2);
let showHours = isInt(days * 24) ? days * 24 : (days * 24).toFixed(1);
console.log('htlc analysis over the past', showDays, 'day(s) or', showHours, 'hour(s)');
console.log('terminology: missed routing opportunity are htlcs that an [outbound] peer would\'ve routed if it had enough [local] liquidity');
if (args.node) {
let formatted = htlcAnalyzerNode(args.node, days);
if (formatted) {
console.log('node: ' + formatted.stats.name + ', ' + formatted.stats.id);
console.log('missed htlc count: ' + formatted.stats.count + ', total missed sats: ' + withCommas(formatted.stats.total) + ', avg htlc size in sats: ' + withCommas(formatted.stats.avg));
console.log('\ndetailed breakdown of missed htlcs for [inbound] peers:');
console.log('-from: [inbound] peer that attempted to route sats');
console.log('-sats: total missed sats for the peer');
console.log('-count: # of missed htlcs');
console.log('-avg: average htlc size in sats');
console.table(formatted.peers);
console.log('\ndetailed list of missed htlcs:');
console.table(formatted.list);
} else {
console.log('no missed htlcs found');
}
} else {
let formatted = htlcAnalyzerFormatted(days);
if (formatted) {
console.log('\ndetailed breakdown of missed htlcs for [outbound] peers:');
console.log('-to: [outbound] peer that attempted to route sats');
console.log('-sats: total missed sats for the peer');
console.log('-count: # of missed htlcs');
console.log('-avg: average htlc size in sats');
console.log('-p: total missed sats for the peer as a % of the total across all peers');
console.table(formatted.peers);
console.log('\ndetailed breakdown of missed htlcs for peer pairs:');
console.log('-from: [inbound] peer that attempted to route sats');
console.log('-to: [outbound] peer');
console.log('-sats: total missed sats for the [outbound] peer');
console.log('-avg: average htlc size in sats');
console.log('-count: # of missed htlcs');
console.log('-p: total missed sats for the peer pair as a % of the total across all peers');
console.table(formatted.list);
} else {
console.log('no missed htlcs found');
}
}
} catch(error) {
console.error(error.toString());
}
})
})
.command('rebalance-history', 'Lists past rebalances')
.argument('[node]', 'Pub id or an alias (full or partial)')
.option('--mins [mins]', 'Depth of history in minutes')
.option('--hours [hours]', 'Depth of history in hours')
.option('--filter [filter]', 'Filter by success or failed', ['success', 'failed'])
.action((args, options, logger) => {
return new Promise(async (resolve, reject) => {
if (!isLndAlive(lndClient)) return reject('lnd is offline');
let secs = (options.hours) ? options.hours * 60 * 60 : -1;
secs = (options.mins) ? options.mins * 60 : secs;
// find matches
let id;
let name;
if (args.node) {
let matches = resolveNode(args.node);
if (!matches) return console.error('no matches found');
else if (matches.length >= 2) return console.error('multiple matches found:', matches);
id = matches[0].id;
name = matches[0].name;
}
let formatted = rebalanceHistoryFormattedSync(secs, options.filter, id);
let msg = 'rebalance history';
if (options.mins) msg += ' over the past ' + options.mins + ' min(s)';
if (options.hours) msg += ' over the past ' + options.hours + ' hour(s)';
if (name) msg += ' for ' + name;
msg += '\n date - when rebalance started';
msg += '\n secs - how long rebalance ran in seconds';
msg += '\n min - minimum max ppm required for rebalance to go through';
msg += '\n type - rebalance type: regular (from inbound to outbound peers), low volume (between low volume peers), missed (based on missed htlcs), forward (ad-hock on forwards)';
console.log(msg);
if (!formatted || formatted.length === 0) console.log('no entries found');
else console.table(formatted);
})
})
.command('list-peers', 'Lists peer aliases and ids')
.action((args, options, logger) => {
return new Promise(async (resolve, reject) => {
if (!isLndAlive(lndClient)) return reject('lnd is offline');
let peers = listPeersSync(lndClient);
let peerNames = [];
peers.forEach(p => {
peerNames.push({
name: (p.active) ? p.name : '💀 ' + p.name,
id: p.id,
active: p.active
})
})
peerNames.sort(function(a, b) {
return a.name.localeCompare(b.name);
})
console.table(peerNames);
})
})
.command('list-channels', 'Lists channels: active, inactive and force closing. Lists top ten channels sorted based on channel state updates')
.help('Lists channels: active, inactive and force closing. Lists top ten channels sorted based on channel state updates')
.action((args, options, logger) => {
return new Promise(async (resolve, reject) => {
if (!isLndAlive(lndClient)) return reject('lnd is offline');
const chans = listChannels();
if (!chans) return console.log('no channels found, likely due to an error');
if (chans.active && chans.active.length > 0) {
console.log('all channels:');
console.table(chans.active);
}
// list inactive channels if any
const inactive = inactiveChannels();
if (inactive && inactive.length > 0) {
console.log('\ninactive channels:\n-mins: shows how long a channel has been inactive in minutes (based on recorded channel events)');
console.table(inactive);
}
if (chans.pendingOpen && chans.pendingOpen.length > 0) {
let pending = [];
chans.pendingOpen.forEach(c => {
pending.push({
peer: c.peer,
id: c.id,
txn: c.channel_point,
capacity: c.capacity,
remote: c.remote_balance,
local: c.local_balance
})
})
console.log('\npending channels:');
console.log('-txn: funding transaction');
console.table(pending);
}
if (chans.updates && chans.updates.length > 0) {
console.log('\ntop channels based on updates:');
console.log('-updates: number of channel state updates');
console.log('-p: channel updates as a % out of the total across all channels');
console.table(chans.updates);
}
if (chans.waitingClose && chans.waitingClose.length > 0) {
console.log('\nwaiting close channels:');
console.table(chans.waitingClose);
}
if (chans.pending && chans.pending.length > 0) {
console.log('\nforce closing channels:');
console.log('-limbo: number of sats in limbo state');
console.log('-htlcs: number of pending htlcs');
console.log('-maturity: blocks till maturity');
console.log('-time: hours till maturity');
console.table(chans.pending);
}
})
})
.command('monitor', 'Prints information about ongoing rebalances and stuck htlcs')
.argument('[secs]', 'Refresh delay in seconds')
.option('--status', 'Prints rebalance status for peers')
.option('--current', 'Lists rebalances in progress')
.action((args, options, logger) => {
return new Promise(async (resolve, reject) => {
if (!isLndAlive(lndClient)) return reject('lnd is offline');
const delay = args.secs || constants.monitor.refresh; // in seconds
const inProgress = !!options.current;
console.log('loading data...');
if (options.status) {
runMonitorStatusLoop();
setInterval(runMonitorStatusLoop, delay * 1000);
} else {
runMonitorLoop(inProgress);
setInterval(runMonitorLoop, delay * 1000, inProgress);