forked from lightningdevkit/ldk-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
1275 lines (1232 loc) · 43 KB
/
main.rs
File metadata and controls
1275 lines (1232 loc) · 43 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
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
use std::fmt::Write;
use std::path::PathBuf;
use clap::{CommandFactory, Parser, Subcommand};
use clap_complete::{generate, Shell};
use config::{
api_key_path_for_storage_dir, cert_path_for_storage_dir, get_default_api_key_path,
get_default_cert_path, get_default_config_path, load_config,
};
use hex_conservative::DisplayHex;
use ldk_server_client::client::LdkServerClient;
use ldk_server_client::error::LdkServerError;
use ldk_server_client::error::LdkServerErrorCode::{
AuthError, InternalError, InternalServerError, InvalidRequestError, LightningError,
};
use ldk_server_client::ldk_server_protos::api::{
Bolt11ClaimForHashRequest, Bolt11ClaimForHashResponse, Bolt11FailForHashRequest,
Bolt11FailForHashResponse, Bolt11ReceiveForHashRequest, Bolt11ReceiveForHashResponse,
Bolt11ReceiveRequest, Bolt11ReceiveResponse, Bolt11ReceiveVariableAmountViaJitChannelRequest,
Bolt11ReceiveVariableAmountViaJitChannelResponse, Bolt11ReceiveViaJitChannelRequest,
Bolt11ReceiveViaJitChannelResponse, Bolt11SendRequest, Bolt11SendResponse,
Bolt12ReceiveRequest, Bolt12ReceiveResponse, Bolt12SendRequest, Bolt12SendResponse,
CloseChannelRequest, CloseChannelResponse, ConnectPeerRequest, ConnectPeerResponse,
DecodeInvoiceRequest, DecodeInvoiceResponse, DecodeOfferRequest, DecodeOfferResponse,
DisconnectPeerRequest, DisconnectPeerResponse, ExportPathfindingScoresRequest,
ForceCloseChannelRequest, ForceCloseChannelResponse, GetBalancesRequest, GetBalancesResponse,
GetNodeInfoRequest, GetNodeInfoResponse, GetPaymentDetailsRequest, GetPaymentDetailsResponse,
GraphGetChannelRequest, GraphGetChannelResponse, GraphGetNodeRequest, GraphGetNodeResponse,
GraphListChannelsRequest, GraphListChannelsResponse, GraphListNodesRequest,
GraphListNodesResponse, ListChannelsRequest, ListChannelsResponse,
ListForwardedPaymentsRequest, ListPaymentsRequest, ListPeersRequest, ListPeersResponse,
OnchainReceiveRequest, OnchainReceiveResponse, OnchainSendRequest, OnchainSendResponse,
OpenChannelRequest, OpenChannelResponse, SignMessageRequest, SignMessageResponse,
SpliceInRequest, SpliceInResponse, SpliceOutRequest, SpliceOutResponse, SpontaneousSendRequest,
SpontaneousSendResponse, UnifiedSendRequest, UnifiedSendResponse, UpdateChannelConfigRequest,
UpdateChannelConfigResponse, VerifySignatureRequest, VerifySignatureResponse,
};
use ldk_server_client::ldk_server_protos::types::{
bolt11_invoice_description, Bolt11InvoiceDescription, ChannelConfig, PageToken,
RouteParametersConfig,
};
use serde::Serialize;
use serde_json::{json, Value};
use types::{
Amount, CliListForwardedPaymentsResponse, CliListPaymentsResponse, CliPaginatedResponse,
};
mod config;
mod types;
// Having these default values as constants in the Proto file and
// importing/reusing them here might be better, but Proto3 removed
// the ability to set default values.
const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
const DEFAULT_MAX_PATH_COUNT: u32 = 10;
const DEFAULT_MAX_CHANNEL_SATURATION_POWER_OF_HALF: u32 = 2;
const DEFAULT_EXPIRY_SECS: u32 = 86_400;
#[derive(Parser, Debug)]
#[command(
name = "ldk-server-cli",
version,
about = "CLI for interacting with an LDK Server node",
override_usage = "ldk-server-cli [OPTIONS] <COMMAND>"
)]
struct Cli {
#[arg(short, long, help = "Base URL of the server. If not provided, reads from config file")]
base_url: Option<String>,
#[arg(
short,
long,
help = "API key for authentication. Defaults by reading ~/.ldk-server/[network]/api_key"
)]
api_key: Option<String>,
#[arg(
short,
long,
help = "Path to the server's TLS certificate file (PEM format). Defaults to ~/.ldk-server/tls.crt"
)]
tls_cert: Option<String>,
#[arg(short, long, help = "Path to config file. Defaults to ~/.ldk-server/config.toml")]
config: Option<String>,
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand, Debug)]
enum Commands {
#[command(about = "Retrieve the latest node info like node_id, current_best_block, etc")]
GetNodeInfo,
#[command(about = "Retrieve an overview of all known balances")]
GetBalances,
#[command(about = "Retrieve a new on-chain funding address")]
OnchainReceive,
#[command(about = "Send an on-chain payment to the given address")]
OnchainSend {
#[arg(help = "The address to send coins to")]
address: String,
#[arg(
help = "The amount to send, e.g. 50sat or 50000msat, must be a whole sat amount, cannot send msats on-chain. Will respect any on-chain reserve needed for anchor channels"
)]
amount: Option<Amount>,
#[arg(
long,
help = "Send full balance to the address. Warning: will not retain on-chain reserves for anchor channels"
)]
send_all: Option<bool>,
#[arg(
long,
help = "Fee rate in satoshis per virtual byte. If not set, a reasonable estimate will be used"
)]
fee_rate_sat_per_vb: Option<u64>,
},
#[command(about = "Create a BOLT11 invoice to receive a payment")]
Bolt11Receive {
#[arg(
help = "Amount to request, e.g. 50sat or 50000msat. If unset, a variable-amount invoice is returned"
)]
amount: Option<Amount>,
#[arg(short, long, help = "Description to attach along with the invoice")]
description: Option<String>,
#[arg(
long,
help = "SHA-256 hash of the description (hex). Use instead of description for longer text"
)]
description_hash: Option<String>,
#[arg(short, long, help = "Invoice expiry time in seconds (default: 86400)")]
expiry_secs: Option<u32>,
},
#[command(
about = "Create a BOLT11 hodl invoice for a given payment hash (manual claim required)"
)]
Bolt11ReceiveForHash {
#[arg(help = "The hex-encoded 32-byte payment hash")]
payment_hash: String,
#[arg(
help = "Amount to request, e.g. 50sat or 50000msat. If unset, a variable-amount invoice is returned"
)]
amount: Option<Amount>,
#[arg(short, long, help = "Description to attach along with the invoice")]
description: Option<String>,
#[arg(
long,
help = "SHA-256 hash of the description (hex). Use instead of description for longer text"
)]
description_hash: Option<String>,
#[arg(short, long, help = "Invoice expiry time in seconds (default: 86400)")]
expiry_secs: Option<u32>,
},
#[command(about = "Claim a held payment by providing the preimage")]
Bolt11ClaimForHash {
#[arg(help = "The hex-encoded 32-byte payment preimage")]
preimage: String,
#[arg(
short,
long,
help = "The claimable amount, e.g. 50sat or 50000msat, only used for verifying we are claiming the expected amount"
)]
claimable_amount: Option<Amount>,
#[arg(
short,
long,
help = "The hex-encoded 32-byte payment hash, used to verify the preimage matches"
)]
payment_hash: Option<String>,
},
#[command(about = "Fail/reject a held payment")]
Bolt11FailForHash {
#[arg(help = "The hex-encoded 32-byte payment hash")]
payment_hash: String,
},
#[command(about = "Create a fixed-amount BOLT11 invoice to receive via an LSPS2 JIT channel")]
Bolt11ReceiveViaJitChannel {
#[arg(help = "Amount to request, e.g. 50sat or 50000msat")]
amount: Amount,
#[arg(short, long, help = "Description to attach along with the invoice")]
description: Option<String>,
#[arg(
long,
help = "SHA-256 hash of the description (hex). Use instead of description for longer text"
)]
description_hash: Option<String>,
#[arg(short, long, help = "Invoice expiry time in seconds (default: 86400)")]
expiry_secs: Option<u32>,
#[arg(
long,
help = "Maximum total fee an LSP may deduct for opening the JIT channel, e.g. 50sat or 50000msat"
)]
max_total_lsp_fee_limit: Option<Amount>,
},
#[command(
about = "Create a variable-amount BOLT11 invoice to receive via an LSPS2 JIT channel"
)]
Bolt11ReceiveVariableAmountViaJitChannel {
#[arg(short, long, help = "Description to attach along with the invoice")]
description: Option<String>,
#[arg(
long,
help = "SHA-256 hash of the description (hex). Use instead of description for longer text"
)]
description_hash: Option<String>,
#[arg(short, long, help = "Invoice expiry time in seconds (default: 86400)")]
expiry_secs: Option<u32>,
#[arg(long, help = "Maximum proportional fee the LSP may deduct in ppm-msat")]
max_proportional_lsp_fee_limit_ppm_msat: Option<u64>,
},
#[command(about = "Pay a BOLT11 invoice")]
Bolt11Send {
#[arg(help = "A BOLT11 invoice for a payment within the Lightning Network")]
invoice: String,
#[arg(
help = "Amount to send, e.g. 50sat or 50000msat. Required when paying a zero-amount invoice"
)]
amount: Option<Amount>,
#[arg(
long,
help = "Maximum total routing fee, e.g. 50sat or 50000msat. Defaults to 1% of payment + 50 sats"
)]
max_total_routing_fee: Option<Amount>,
#[arg(long, help = "Maximum total CLTV delta we accept for the route (default: 1008)")]
max_total_cltv_expiry_delta: Option<u32>,
#[arg(
long,
help = "Maximum number of paths that may be used by MPP payments (default: 10)"
)]
max_path_count: Option<u32>,
#[arg(
long,
help = "Maximum share of a channel's total capacity to send over a channel, as a power of 1/2 (default: 2)"
)]
max_channel_saturation_power_of_half: Option<u32>,
},
#[command(about = "Return a BOLT12 offer for receiving payments")]
Bolt12Receive {
#[arg(help = "Description to attach along with the offer")]
description: String,
#[arg(
help = "Amount to request, e.g. 50sat or 50000msat. If unset, a variable-amount offer is returned"
)]
amount: Option<Amount>,
#[arg(long, help = "Offer expiry time in seconds")]
expiry_secs: Option<u32>,
#[arg(long, help = "Number of items requested. Can only be set for fixed-amount offers")]
quantity: Option<u64>,
},
#[command(about = "Send a payment for a BOLT12 offer")]
Bolt12Send {
#[arg(help = "A BOLT12 offer for a payment within the Lightning Network")]
offer: String,
#[arg(
help = "Amount to send, e.g. 50sat or 50000msat. Required when paying a zero-amount offer"
)]
amount: Option<Amount>,
#[arg(short, long, help = "Number of items requested")]
quantity: Option<u64>,
#[arg(
short,
long,
help = "Note to include for the payee. Will be seen by recipient and reflected back in the invoice"
)]
payer_note: Option<String>,
#[arg(
long,
help = "Maximum total routing fee, e.g. 50sat or 50000msat. Defaults to 1% of the payment amount + 50 sats"
)]
max_total_routing_fee: Option<Amount>,
#[arg(long, help = "Maximum total CLTV delta we accept for the route (default: 1008)")]
max_total_cltv_expiry_delta: Option<u32>,
#[arg(
long,
help = "Maximum number of paths that may be used by MPP payments (default: 10)"
)]
max_path_count: Option<u32>,
#[arg(
long,
help = "Maximum share of a channel's total capacity to send over a channel, as a power of 1/2 (default: 2)"
)]
max_channel_saturation_power_of_half: Option<u32>,
},
#[command(about = "Send a spontaneous payment (keysend) to a node")]
SpontaneousSend {
#[arg(help = "The hex-encoded public key of the node to send the payment to")]
node_id: String,
#[arg(help = "The amount to send, e.g. 50sat or 50000msat")]
amount: Amount,
#[arg(
long,
help = "Maximum total routing fee, e.g. 50sat or 50000msat. Defaults to 1% of payment + 50 sats"
)]
max_total_routing_fee: Option<Amount>,
#[arg(long, help = "Maximum total CLTV delta we accept for the route (default: 1008)")]
max_total_cltv_expiry_delta: Option<u32>,
#[arg(
long,
help = "Maximum number of paths that may be used by MPP payments (default: 10)"
)]
max_path_count: Option<u32>,
#[arg(
long,
help = "Maximum share of a channel's total capacity to send over a channel, as a power of 1/2 (default: 2)"
)]
max_channel_saturation_power_of_half: Option<u32>,
},
#[command(
about = "Pay a BIP 21 URI, BIP 353 Human-Readable Name, BOLT11 invoice, or BOLT12 offer"
)]
Pay {
#[arg(help = "A BIP 21 URI, BIP 353 Human-Readable Name, BOLT11 invoice, or BOLT12 offer")]
uri: String,
#[arg(help = "Amount to send, e.g. 50sat or 50000msat. Required for variable-amount URIs")]
amount: Option<Amount>,
#[arg(
long,
help = "Maximum total routing fee, e.g. 50sat or 50000msat. Defaults to 1% of payment + 50 sats"
)]
max_total_routing_fee: Option<Amount>,
#[arg(long, help = "Maximum total CLTV delta we accept for the route (default: 1008)")]
max_total_cltv_expiry_delta: Option<u32>,
#[arg(
long,
help = "Maximum number of paths that may be used by MPP payments (default: 10)"
)]
max_path_count: Option<u32>,
#[arg(
long,
help = "Maximum share of a channel's total capacity to send over a channel, as a power of 1/2 (default: 2)"
)]
max_channel_saturation_power_of_half: Option<u32>,
},
#[command(about = "Decode a BOLT11 invoice and display its fields")]
DecodeInvoice {
#[arg(help = "The BOLT11 invoice string to decode")]
invoice: String,
},
#[command(about = "Decode a BOLT12 offer and display its fields")]
DecodeOffer {
#[arg(help = "The BOLT12 offer string to decode")]
offer: String,
},
#[command(about = "Cooperatively close the channel specified by the given channel ID")]
CloseChannel {
#[arg(help = "The local user_channel_id of this channel")]
user_channel_id: String,
#[arg(help = "The hex-encoded public key of the node to close a channel with")]
counterparty_node_id: String,
},
#[command(about = "Force close the channel specified by the given channel ID")]
ForceCloseChannel {
#[arg(help = "The local user_channel_id of this channel")]
user_channel_id: String,
#[arg(help = "The hex-encoded public key of the node to close a channel with")]
counterparty_node_id: String,
#[arg(long, help = "The reason for force-closing, defaults to \"\"")]
force_close_reason: Option<String>,
},
#[command(about = "Create a new outbound channel to the given remote node")]
OpenChannel {
#[arg(help = "The hex-encoded public key of the node to open a channel with")]
node_pubkey: String,
#[arg(
help = "Address to connect to remote peer (IPv4:port, IPv6:port, OnionV3:port, or hostname:port)"
)]
address: String,
#[arg(
help = "The amount to commit to the channel, e.g. 100sat or 100000msat, must be a whole sat amount, cannot send msats on-chain."
)]
channel_amount: Amount,
#[arg(long, help = "Amount to push to the remote side, e.g. 50sat or 50000msat")]
push_to_counterparty: Option<Amount>,
#[arg(long, help = "Whether the channel should be public")]
announce_channel: bool,
// Channel config options
#[arg(
long,
help = "Amount (in millionths of a satoshi) charged per satoshi for payments forwarded outbound over the channel. This can be updated by using update-channel-config."
)]
forwarding_fee_proportional_millionths: Option<u32>,
#[arg(
long,
help = "Amount (in milli-satoshi) charged for payments forwarded outbound over the channel, in excess of forwarding_fee_proportional_millionths. This can be updated by using update-channel-config."
)]
forwarding_fee_base_msat: Option<u32>,
#[arg(
long,
help = "The difference in the CLTV value between incoming HTLCs and an outbound HTLC forwarded over the channel. This can be updated by using update-channel-config."
)]
cltv_expiry_delta: Option<u32>,
},
#[command(
about = "Increase the channel balance by the given amount, funds will come from the node's on-chain wallet"
)]
SpliceIn {
#[arg(help = "The local user_channel_id of the channel")]
user_channel_id: String,
#[arg(help = "The hex-encoded public key of the channel's counterparty node")]
counterparty_node_id: String,
#[arg(
help = "The amount to splice into the channel, e.g. 50sat or 50000msat, must be a whole sat amount, cannot send msats on-chain."
)]
splice_amount: Amount,
},
#[command(about = "Decrease the channel balance by the given amount")]
SpliceOut {
#[arg(help = "The local user_channel_id of this channel")]
user_channel_id: String,
#[arg(help = "The hex-encoded public key of the channel's counterparty node")]
counterparty_node_id: String,
#[arg(
help = "The amount to splice out of the channel, e.g. 50sat or 50000msat, must be a whole sat amount, cannot send msats on-chain."
)]
splice_amount: Amount,
#[arg(
short,
long,
help = "Bitcoin address to send the spliced-out funds. If not set, uses the node's on-chain wallet"
)]
address: Option<String>,
},
#[command(about = "Return a list of known channels")]
ListChannels,
#[command(about = "Retrieve list of all payments")]
ListPayments {
#[arg(short, long)]
#[arg(
help = "Fetch at least this many payments by iterating through multiple pages. Returns combined results with the last page token. If not provided, returns only a single page."
)]
number_of_payments: Option<u64>,
#[arg(long)]
#[arg(help = "Page token to continue from a previous page (format: token:index)")]
page_token: Option<String>,
},
#[command(about = "Get details of a specific payment by its payment ID")]
GetPaymentDetails {
#[arg(help = "The payment ID in hex-encoded form")]
payment_id: String,
},
#[command(about = "Retrieves list of all forwarded payments")]
ListForwardedPayments {
#[arg(
short,
long,
help = "Fetch at least this many forwarded payments by iterating through multiple pages. Returns combined results with the last page token. If not provided, returns only a single page."
)]
number_of_payments: Option<u64>,
#[arg(long, help = "Page token to continue from a previous page (format: token:index)")]
page_token: Option<String>,
},
#[command(about = "Update the forwarding fees and CLTV expiry delta for an existing channel")]
UpdateChannelConfig {
#[arg(help = "The local user_channel_id of this channel")]
user_channel_id: String,
#[arg(
help = "The hex-encoded public key of the counterparty node to update channel config with"
)]
counterparty_node_id: String,
#[arg(
long,
help = "Amount (in millionths of a satoshi) charged per satoshi for payments forwarded outbound over the channel. This can be updated by using update-channel-config."
)]
forwarding_fee_proportional_millionths: Option<u32>,
#[arg(
long,
help = "Amount (in milli-satoshi) charged for payments forwarded outbound over the channel, in excess of forwarding_fee_proportional_millionths. This can be updated by using update-channel-config."
)]
forwarding_fee_base_msat: Option<u32>,
#[arg(
long,
help = "The difference in the CLTV value between incoming HTLCs and an outbound HTLC forwarded over the channel."
)]
cltv_expiry_delta: Option<u32>,
},
#[command(about = "Connect to a peer on the Lightning Network without opening a channel")]
ConnectPeer {
#[arg(
help = "The peer to connect to in pubkey@address format, or just the pubkey if address is provided separately"
)]
node_pubkey: String,
#[arg(
help = "Address to connect to remote peer (IPv4:port, IPv6:port, OnionV3:port, or hostname:port). Optional if address is included in pubkey via @ separator."
)]
address: Option<String>,
#[arg(
long,
default_value_t = false,
help = "Whether to persist the connection for automatic reconnection on restart"
)]
persist: bool,
},
#[command(about = "Disconnect from a peer and remove it from the peer store")]
DisconnectPeer {
#[arg(help = "The hex-encoded public key of the node to disconnect from")]
node_pubkey: String,
},
#[command(about = "Return a list of peers")]
ListPeers,
#[command(about = "Sign a message with the node's secret key")]
SignMessage {
#[arg(help = "The message to sign")]
message: String,
},
#[command(about = "Verify a signature against a message and public key")]
VerifySignature {
#[arg(help = "The message that was signed")]
message: String,
#[arg(help = "The zbase32-encoded signature to verify")]
signature: String,
#[arg(help = "The hex-encoded public key of the signer")]
public_key: String,
},
#[command(about = "Export the pathfinding scores used by the router")]
ExportPathfindingScores,
#[command(about = "List all known short channel IDs in the network graph")]
GraphListChannels,
#[command(about = "Get channel information from the network graph by short channel ID")]
GraphGetChannel {
#[arg(help = "The short channel ID to look up")]
short_channel_id: u64,
},
#[command(about = "List all known node IDs in the network graph")]
GraphListNodes,
#[command(about = "Get node information from the network graph by node ID")]
GraphGetNode {
#[arg(help = "The hex-encoded node ID to look up")]
node_id: String,
},
#[command(about = "Generate shell completions for the CLI")]
Completions {
#[arg(
value_enum,
help = "The shell to generate completions for (bash, zsh, fish, powershell, elvish)"
)]
shell: Shell,
},
}
#[tokio::main]
async fn main() {
let cli = Cli::parse();
// short-circuit if generating completions
if let Commands::Completions { shell } = cli.command {
generate(shell, &mut Cli::command(), "ldk-server-cli", &mut std::io::stdout());
return;
}
let config_path = cli.config.map(PathBuf::from).or_else(get_default_config_path);
let config = config_path.as_ref().and_then(|p| load_config(p).ok());
let storage_dir =
config.as_ref().and_then(|c| c.storage.as_ref()?.disk.as_ref()?.dir_path.as_deref());
// Get API key from argument, then from api_key file in storage dir, then from default location
let api_key = cli
.api_key
.or_else(|| {
let network =
config.as_ref().and_then(|c| c.network().ok()).unwrap_or("bitcoin".to_string());
storage_dir
.map(|dir| api_key_path_for_storage_dir(dir, &network))
.and_then(|path| std::fs::read(&path).ok())
.or_else(|| {
get_default_api_key_path(&network)
.and_then(|path| std::fs::read(&path).ok())
})
.map(|bytes| bytes.to_lower_hex_string())
})
.unwrap_or_else(|| {
eprintln!("API key not provided. Use --api-key or ensure the api_key file exists at ~/.ldk-server/[network]/api_key");
std::process::exit(1);
});
// Get base URL from argument then from config file
let base_url =
cli.base_url.or_else(|| config.as_ref().map(|c| c.node.rest_service_address.clone()))
.unwrap_or_else(|| {
eprintln!("Base URL not provided. Use --base-url or ensure config file exists at ~/.ldk-server/config.toml");
std::process::exit(1);
});
// Get TLS cert path from argument, then from config tls.cert_path, then from storage dir,
// then try default location.
let tls_cert_path = cli.tls_cert.map(PathBuf::from).or_else(|| {
config
.as_ref()
.and_then(|c| c.tls.as_ref().and_then(|t| t.cert_path.as_ref().map(PathBuf::from)))
.or_else(|| {
storage_dir.map(cert_path_for_storage_dir).filter(|path| path.exists())
})
.or_else(get_default_cert_path)
})
.unwrap_or_else(|| {
eprintln!("TLS cert path not provided. Use --tls-cert or ensure config file exists at ~/.ldk-server/config.toml");
std::process::exit(1);
});
let server_cert_pem = std::fs::read(&tls_cert_path).unwrap_or_else(|e| {
eprintln!("Failed to read server certificate file '{}': {}", tls_cert_path.display(), e);
std::process::exit(1);
});
let client = LdkServerClient::new(base_url, api_key, &server_cert_pem).unwrap_or_else(|e| {
eprintln!("Failed to create client: {e}");
std::process::exit(1);
});
match cli.command {
Commands::GetNodeInfo => {
handle_response_result::<_, GetNodeInfoResponse>(
client.get_node_info(GetNodeInfoRequest {}).await,
);
},
Commands::GetBalances => {
handle_response_result::<_, GetBalancesResponse>(
client.get_balances(GetBalancesRequest {}).await,
);
},
Commands::OnchainReceive => {
handle_response_result::<_, OnchainReceiveResponse>(
client.onchain_receive(OnchainReceiveRequest {}).await,
);
},
Commands::OnchainSend { address, amount, send_all, fee_rate_sat_per_vb } => {
let amount_sats = amount.map(|a| a.to_sat().unwrap_or_else(|e| handle_error_msg(&e)));
handle_response_result::<_, OnchainSendResponse>(
client
.onchain_send(OnchainSendRequest {
address,
amount_sats,
send_all,
fee_rate_sat_per_vb,
})
.await,
);
},
Commands::Bolt11Receive { description, description_hash, expiry_secs, amount } => {
let amount_msat = amount.map(|a| a.to_msat());
let invoice_description =
parse_bolt11_invoice_description(description, description_hash);
let expiry_secs = expiry_secs.unwrap_or(DEFAULT_EXPIRY_SECS);
let request =
Bolt11ReceiveRequest { description: invoice_description, expiry_secs, amount_msat };
handle_response_result::<_, Bolt11ReceiveResponse>(
client.bolt11_receive(request).await,
);
},
Commands::Bolt11ReceiveForHash {
payment_hash,
amount,
description,
description_hash,
expiry_secs,
} => {
let amount_msat = amount.map(|a| a.to_msat());
let invoice_description = match (description, description_hash) {
(Some(desc), None) => Some(Bolt11InvoiceDescription {
kind: Some(bolt11_invoice_description::Kind::Direct(desc)),
}),
(None, Some(hash)) => Some(Bolt11InvoiceDescription {
kind: Some(bolt11_invoice_description::Kind::Hash(hash)),
}),
(Some(_), Some(_)) => {
handle_error(LdkServerError::new(
InternalError,
"Only one of description or description_hash can be set.".to_string(),
));
},
(None, None) => None,
};
let expiry_secs = expiry_secs.unwrap_or(DEFAULT_EXPIRY_SECS);
let request = Bolt11ReceiveForHashRequest {
description: invoice_description,
expiry_secs,
amount_msat,
payment_hash,
};
handle_response_result::<_, Bolt11ReceiveForHashResponse>(
client.bolt11_receive_for_hash(request).await,
);
},
Commands::Bolt11ClaimForHash { preimage, claimable_amount, payment_hash } => {
handle_response_result::<_, Bolt11ClaimForHashResponse>(
client
.bolt11_claim_for_hash(Bolt11ClaimForHashRequest {
payment_hash,
claimable_amount_msat: claimable_amount.map(|a| a.to_msat()),
preimage,
})
.await,
);
},
Commands::Bolt11FailForHash { payment_hash } => {
handle_response_result::<_, Bolt11FailForHashResponse>(
client.bolt11_fail_for_hash(Bolt11FailForHashRequest { payment_hash }).await,
);
},
Commands::Bolt11ReceiveViaJitChannel {
amount,
description,
description_hash,
expiry_secs,
max_total_lsp_fee_limit,
} => {
let request = Bolt11ReceiveViaJitChannelRequest {
amount_msat: amount.to_msat(),
description: parse_bolt11_invoice_description(description, description_hash),
expiry_secs: expiry_secs.unwrap_or(DEFAULT_EXPIRY_SECS),
max_total_lsp_fee_limit_msat: max_total_lsp_fee_limit.map(|a| a.to_msat()),
};
handle_response_result::<_, Bolt11ReceiveViaJitChannelResponse>(
client.bolt11_receive_via_jit_channel(request).await,
);
},
Commands::Bolt11ReceiveVariableAmountViaJitChannel {
description,
description_hash,
expiry_secs,
max_proportional_lsp_fee_limit_ppm_msat,
} => {
let request = Bolt11ReceiveVariableAmountViaJitChannelRequest {
description: parse_bolt11_invoice_description(description, description_hash),
expiry_secs: expiry_secs.unwrap_or(DEFAULT_EXPIRY_SECS),
max_proportional_lsp_fee_limit_ppm_msat,
};
handle_response_result::<_, Bolt11ReceiveVariableAmountViaJitChannelResponse>(
client.bolt11_receive_variable_amount_via_jit_channel(request).await,
);
},
Commands::Bolt11Send {
invoice,
amount,
max_total_routing_fee,
max_total_cltv_expiry_delta,
max_path_count,
max_channel_saturation_power_of_half,
} => {
let amount_msat = amount.map(|a| a.to_msat());
let max_total_routing_fee_msat = max_total_routing_fee.map(|a| a.to_msat());
let route_parameters = RouteParametersConfig {
max_total_routing_fee_msat,
max_total_cltv_expiry_delta: max_total_cltv_expiry_delta
.unwrap_or(DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA),
max_path_count: max_path_count.unwrap_or(DEFAULT_MAX_PATH_COUNT),
max_channel_saturation_power_of_half: max_channel_saturation_power_of_half
.unwrap_or(DEFAULT_MAX_CHANNEL_SATURATION_POWER_OF_HALF),
};
handle_response_result::<_, Bolt11SendResponse>(
client
.bolt11_send(Bolt11SendRequest {
invoice,
amount_msat,
route_parameters: Some(route_parameters),
})
.await,
);
},
Commands::Bolt12Receive { description, amount, expiry_secs, quantity } => {
let amount_msat = amount.map(|a| a.to_msat());
handle_response_result::<_, Bolt12ReceiveResponse>(
client
.bolt12_receive(Bolt12ReceiveRequest {
description,
amount_msat,
expiry_secs,
quantity,
})
.await,
);
},
Commands::Bolt12Send {
offer,
amount,
quantity,
payer_note,
max_total_routing_fee,
max_total_cltv_expiry_delta,
max_path_count,
max_channel_saturation_power_of_half,
} => {
let amount_msat = amount.map(|a| a.to_msat());
let max_total_routing_fee_msat = max_total_routing_fee.map(|a| a.to_msat());
let route_parameters = RouteParametersConfig {
max_total_routing_fee_msat,
max_total_cltv_expiry_delta: max_total_cltv_expiry_delta
.unwrap_or(DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA),
max_path_count: max_path_count.unwrap_or(DEFAULT_MAX_PATH_COUNT),
max_channel_saturation_power_of_half: max_channel_saturation_power_of_half
.unwrap_or(DEFAULT_MAX_CHANNEL_SATURATION_POWER_OF_HALF),
};
handle_response_result::<_, Bolt12SendResponse>(
client
.bolt12_send(Bolt12SendRequest {
offer,
amount_msat,
quantity,
payer_note,
route_parameters: Some(route_parameters),
})
.await,
);
},
Commands::SpontaneousSend {
node_id,
amount,
max_total_routing_fee,
max_total_cltv_expiry_delta,
max_path_count,
max_channel_saturation_power_of_half,
} => {
let amount_msat = amount.to_msat();
let max_total_routing_fee_msat = max_total_routing_fee.map(|a| a.to_msat());
let route_parameters = RouteParametersConfig {
max_total_routing_fee_msat,
max_total_cltv_expiry_delta: max_total_cltv_expiry_delta
.unwrap_or(DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA),
max_path_count: max_path_count.unwrap_or(DEFAULT_MAX_PATH_COUNT),
max_channel_saturation_power_of_half: max_channel_saturation_power_of_half
.unwrap_or(DEFAULT_MAX_CHANNEL_SATURATION_POWER_OF_HALF),
};
handle_response_result::<_, SpontaneousSendResponse>(
client
.spontaneous_send(SpontaneousSendRequest {
amount_msat,
node_id,
route_parameters: Some(route_parameters),
})
.await,
);
},
Commands::Pay {
uri,
amount,
max_total_routing_fee,
max_total_cltv_expiry_delta,
max_path_count,
max_channel_saturation_power_of_half,
} => {
let amount_msat = amount.map(|a| a.to_msat());
let max_total_routing_fee_msat = max_total_routing_fee.map(|a| a.to_msat());
let route_parameters = RouteParametersConfig {
max_total_routing_fee_msat,
max_total_cltv_expiry_delta: max_total_cltv_expiry_delta
.unwrap_or(DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA),
max_path_count: max_path_count.unwrap_or(DEFAULT_MAX_PATH_COUNT),
max_channel_saturation_power_of_half: max_channel_saturation_power_of_half
.unwrap_or(DEFAULT_MAX_CHANNEL_SATURATION_POWER_OF_HALF),
};
handle_response_result::<_, UnifiedSendResponse>(
client
.unified_send(UnifiedSendRequest {
uri,
amount_msat,
route_parameters: Some(route_parameters),
})
.await,
);
},
Commands::DecodeInvoice { invoice } => {
handle_response_result::<_, DecodeInvoiceResponse>(
client.decode_invoice(DecodeInvoiceRequest { invoice }).await,
);
},
Commands::DecodeOffer { offer } => {
handle_response_result::<_, DecodeOfferResponse>(
client.decode_offer(DecodeOfferRequest { offer }).await,
);
},
Commands::CloseChannel { user_channel_id, counterparty_node_id } => {
handle_response_result::<_, CloseChannelResponse>(
client
.close_channel(CloseChannelRequest { user_channel_id, counterparty_node_id })
.await,
);
},
Commands::ForceCloseChannel {
user_channel_id,
counterparty_node_id,
force_close_reason,
} => {
handle_response_result::<_, ForceCloseChannelResponse>(
client
.force_close_channel(ForceCloseChannelRequest {
user_channel_id,
counterparty_node_id,
force_close_reason,
})
.await,
);
},
Commands::OpenChannel {
node_pubkey,
address,
channel_amount,
push_to_counterparty,
announce_channel,
forwarding_fee_proportional_millionths,
forwarding_fee_base_msat,
cltv_expiry_delta,
} => {
let channel_amount_sats =
channel_amount.to_sat().unwrap_or_else(|e| handle_error_msg(&e));
let push_to_counterparty_msat = push_to_counterparty.map(|a| a.to_msat());
let channel_config = build_open_channel_config(
forwarding_fee_proportional_millionths,
forwarding_fee_base_msat,
cltv_expiry_delta,
);
handle_response_result::<_, OpenChannelResponse>(
client
.open_channel(OpenChannelRequest {
node_pubkey,
address,
channel_amount_sats,
push_to_counterparty_msat,
channel_config,
announce_channel,
})
.await,
);
},
Commands::SpliceIn { user_channel_id, counterparty_node_id, splice_amount } => {
let splice_amount_sats =
splice_amount.to_sat().unwrap_or_else(|e| handle_error_msg(&e));
handle_response_result::<_, SpliceInResponse>(
client
.splice_in(SpliceInRequest {
user_channel_id,
counterparty_node_id,
splice_amount_sats,
})
.await,
);
},
Commands::SpliceOut { user_channel_id, counterparty_node_id, address, splice_amount } => {
let splice_amount_sats =
splice_amount.to_sat().unwrap_or_else(|e| handle_error_msg(&e));
handle_response_result::<_, SpliceOutResponse>(
client
.splice_out(SpliceOutRequest {
user_channel_id,
counterparty_node_id,
address,
splice_amount_sats,
})
.await,
);
},
Commands::ListChannels => {
handle_response_result::<_, ListChannelsResponse>(
client.list_channels(ListChannelsRequest {}).await,
);
},
Commands::ListPayments { number_of_payments, page_token } => {
let page_token = page_token
.map(|token_str| parse_page_token(&token_str).unwrap_or_else(|e| handle_error(e)));
handle_response_result::<_, CliListPaymentsResponse>(
fetch_paginated(
number_of_payments,
page_token,
|pt| client.list_payments(ListPaymentsRequest { page_token: pt }),
|r| (r.payments, r.next_page_token),
)
.await,
);
},
Commands::GetPaymentDetails { payment_id } => {
handle_response_result::<_, GetPaymentDetailsResponse>(
client.get_payment_details(GetPaymentDetailsRequest { payment_id }).await,
);
},
Commands::ListForwardedPayments { number_of_payments, page_token } => {
let page_token = page_token
.map(|token_str| parse_page_token(&token_str).unwrap_or_else(|e| handle_error(e)));
handle_response_result::<_, CliListForwardedPaymentsResponse>(
fetch_paginated(
number_of_payments,
page_token,
|pt| {