Support paying 0-amount offers and invoices
[ldk-sample] / src / cli.rs
1 use crate::disk::{self, INBOUND_PAYMENTS_FNAME, OUTBOUND_PAYMENTS_FNAME};
2 use crate::hex_utils;
3 use crate::{
4         ChannelManager, HTLCStatus, InboundPaymentInfoStorage, MillisatAmount, NetworkGraph,
5         OnionMessenger, OutboundPaymentInfoStorage, PaymentInfo, PeerManager,
6 };
7 use bitcoin::hashes::sha256::Hash as Sha256;
8 use bitcoin::hashes::Hash;
9 use bitcoin::network::constants::Network;
10 use bitcoin::secp256k1::PublicKey;
11 use lightning::ln::channelmanager::{PaymentId, RecipientOnionFields, Retry};
12 use lightning::ln::msgs::SocketAddress;
13 use lightning::ln::{ChannelId, PaymentHash, PaymentPreimage};
14 use lightning::offers::offer::{self, Offer};
15 use lightning::onion_message::messenger::Destination;
16 use lightning::onion_message::packet::OnionMessageContents;
17 use lightning::routing::gossip::NodeId;
18 use lightning::routing::router::{PaymentParameters, RouteParameters};
19 use lightning::sign::{EntropySource, KeysManager};
20 use lightning::util::config::{ChannelHandshakeConfig, ChannelHandshakeLimits, UserConfig};
21 use lightning::util::persist::KVStore;
22 use lightning::util::ser::{Writeable, Writer};
23 use lightning_invoice::payment::payment_parameters_from_invoice;
24 use lightning_invoice::payment::payment_parameters_from_zero_amount_invoice;
25 use lightning_invoice::{utils, Bolt11Invoice, Currency};
26 use lightning_persister::fs_store::FilesystemStore;
27 use std::env;
28 use std::io;
29 use std::io::Write;
30 use std::net::{SocketAddr, ToSocketAddrs};
31 use std::path::Path;
32 use std::str::FromStr;
33 use std::sync::{Arc, Mutex};
34 use std::time::Duration;
35
36 pub(crate) struct LdkUserInfo {
37         pub(crate) bitcoind_rpc_username: String,
38         pub(crate) bitcoind_rpc_password: String,
39         pub(crate) bitcoind_rpc_port: u16,
40         pub(crate) bitcoind_rpc_host: String,
41         pub(crate) ldk_storage_dir_path: String,
42         pub(crate) ldk_peer_listening_port: u16,
43         pub(crate) ldk_announced_listen_addr: Vec<SocketAddress>,
44         pub(crate) ldk_announced_node_name: [u8; 32],
45         pub(crate) network: Network,
46 }
47
48 #[derive(Debug)]
49 struct UserOnionMessageContents {
50         tlv_type: u64,
51         data: Vec<u8>,
52 }
53
54 impl OnionMessageContents for UserOnionMessageContents {
55         fn tlv_type(&self) -> u64 {
56                 self.tlv_type
57         }
58 }
59
60 impl Writeable for UserOnionMessageContents {
61         fn write<W: Writer>(&self, w: &mut W) -> Result<(), std::io::Error> {
62                 w.write_all(&self.data)
63         }
64 }
65
66 pub(crate) fn poll_for_user_input(
67         peer_manager: Arc<PeerManager>, channel_manager: Arc<ChannelManager>,
68         keys_manager: Arc<KeysManager>, network_graph: Arc<NetworkGraph>,
69         onion_messenger: Arc<OnionMessenger>, inbound_payments: Arc<Mutex<InboundPaymentInfoStorage>>,
70         outbound_payments: Arc<Mutex<OutboundPaymentInfoStorage>>, ldk_data_dir: String,
71         network: Network, logger: Arc<disk::FilesystemLogger>, fs_store: Arc<FilesystemStore>,
72 ) {
73         println!(
74                 "LDK startup successful. Enter \"help\" to view available commands. Press Ctrl-D to quit."
75         );
76         println!("LDK logs are available at <your-supplied-ldk-data-dir-path>/.ldk/logs");
77         println!("Local Node ID is {}.", channel_manager.get_our_node_id());
78         'read_command: loop {
79                 print!("> ");
80                 io::stdout().flush().unwrap(); // Without flushing, the `>` doesn't print
81                 let mut line = String::new();
82                 if let Err(e) = io::stdin().read_line(&mut line) {
83                         break println!("ERROR: {}", e);
84                 }
85
86                 if line.len() == 0 {
87                         // We hit EOF / Ctrl-D
88                         break;
89                 }
90
91                 let mut words = line.split_whitespace();
92                 if let Some(word) = words.next() {
93                         match word {
94                                 "help" => help(),
95                                 "openchannel" => {
96                                         let peer_pubkey_and_ip_addr = words.next();
97                                         let channel_value_sat = words.next();
98                                         if peer_pubkey_and_ip_addr.is_none() || channel_value_sat.is_none() {
99                                                 println!("ERROR: openchannel has 2 required arguments: `openchannel pubkey@host:port channel_amt_satoshis` [--public] [--with-anchors]");
100                                                 continue;
101                                         }
102                                         let peer_pubkey_and_ip_addr = peer_pubkey_and_ip_addr.unwrap();
103                                         let (pubkey, peer_addr) =
104                                                 match parse_peer_info(peer_pubkey_and_ip_addr.to_string()) {
105                                                         Ok(info) => info,
106                                                         Err(e) => {
107                                                                 println!("{:?}", e.into_inner().unwrap());
108                                                                 continue;
109                                                         }
110                                                 };
111
112                                         let chan_amt_sat: Result<u64, _> = channel_value_sat.unwrap().parse();
113                                         if chan_amt_sat.is_err() {
114                                                 println!("ERROR: channel amount must be a number");
115                                                 continue;
116                                         }
117
118                                         if tokio::runtime::Handle::current()
119                                                 .block_on(connect_peer_if_necessary(
120                                                         pubkey,
121                                                         peer_addr,
122                                                         peer_manager.clone(),
123                                                 ))
124                                                 .is_err()
125                                         {
126                                                 continue;
127                                         };
128
129                                         let (mut announce_channel, mut with_anchors) = (false, false);
130                                         while let Some(word) = words.next() {
131                                                 match word {
132                                                         "--public" | "--public=true" => announce_channel = true,
133                                                         "--public=false" => announce_channel = false,
134                                                         "--with-anchors" | "--with-anchors=true" => with_anchors = true,
135                                                         "--with-anchors=false" => with_anchors = false,
136                                                         _ => {
137                                                                 println!("ERROR: invalid boolean flag format. Valid formats: `--option`, `--option=true` `--option=false`");
138                                                                 continue;
139                                                         }
140                                                 }
141                                         }
142
143                                         if open_channel(
144                                                 pubkey,
145                                                 chan_amt_sat.unwrap(),
146                                                 announce_channel,
147                                                 with_anchors,
148                                                 channel_manager.clone(),
149                                         )
150                                         .is_ok()
151                                         {
152                                                 let peer_data_path = format!("{}/channel_peer_data", ldk_data_dir.clone());
153                                                 let _ = disk::persist_channel_peer(
154                                                         Path::new(&peer_data_path),
155                                                         peer_pubkey_and_ip_addr,
156                                                 );
157                                         }
158                                 }
159                                 "sendpayment" => {
160                                         let invoice_str = words.next();
161                                         if invoice_str.is_none() {
162                                                 println!("ERROR: sendpayment requires an invoice: `sendpayment <invoice>`");
163                                                 continue;
164                                         }
165
166                                         let mut user_provided_amt: Option<u64> = None;
167                                         if let Some(amt_msat_str) = words.next() {
168                                                 match amt_msat_str.parse() {
169                                                         Ok(amt) => user_provided_amt = Some(amt),
170                                                         Err(e) => {
171                                                                 println!("ERROR: couldn't parse amount_msat: {}", e);
172                                                                 continue;
173                                                         }
174                                                 };
175                                         }
176
177                                         if let Ok(offer) = Offer::from_str(invoice_str.unwrap()) {
178                                                 let offer_hash = Sha256::hash(invoice_str.unwrap().as_bytes());
179                                                 let payment_id = PaymentId(*offer_hash.as_ref());
180
181                                                 let amt_msat = match (offer.amount(), user_provided_amt) {
182                                                         (Some(offer::Amount::Bitcoin { amount_msats }), _) => *amount_msats,
183                                                         (_, Some(amt)) => amt,
184                                                         (amt, _) => {
185                                                                 println!("ERROR: Cannot process non-Bitcoin-denominated offer value {:?}", amt);
186                                                                 continue;
187                                                         }
188                                                 };
189                                                 if user_provided_amt.is_some() && user_provided_amt != Some(amt_msat) {
190                                                         println!("Amount didn't match offer of {}msat", amt_msat);
191                                                         continue;
192                                                 }
193
194                                                 while user_provided_amt.is_none() {
195                                                         print!("Paying offer for {} msat. Continue (Y/N)? >", amt_msat);
196                                                         io::stdout().flush().unwrap();
197
198                                                         if let Err(e) = io::stdin().read_line(&mut line) {
199                                                                 println!("ERROR: {}", e);
200                                                                 break 'read_command;
201                                                         }
202
203                                                         if line.len() == 0 {
204                                                                 // We hit EOF / Ctrl-D
205                                                                 break 'read_command;
206                                                         }
207
208                                                         if line.starts_with("Y") {
209                                                                 break;
210                                                         }
211                                                         if line.starts_with("N") {
212                                                                 continue 'read_command;
213                                                         }
214                                                 }
215
216                                                 outbound_payments.lock().unwrap().payments.insert(
217                                                         payment_id,
218                                                         PaymentInfo {
219                                                                 preimage: None,
220                                                                 secret: None,
221                                                                 status: HTLCStatus::Pending,
222                                                                 amt_msat: MillisatAmount(Some(amt_msat)),
223                                                         },
224                                                 );
225                                                 fs_store
226                                                         .write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode())
227                                                         .unwrap();
228
229                                                 let retry = Retry::Timeout(Duration::from_secs(10));
230                                                 let amt = Some(amt_msat);
231                                                 let pay = channel_manager
232                                                         .pay_for_offer(&offer, None, amt, None, payment_id, retry, None);
233                                                 if pay.is_err() {
234                                                         println!("ERROR: Failed to pay: {:?}", pay);
235                                                 }
236                                         } else {
237                                                 match Bolt11Invoice::from_str(invoice_str.unwrap()) {
238                                                         Ok(invoice) => send_payment(
239                                                                 &channel_manager,
240                                                                 &invoice,
241                                                                 user_provided_amt,
242                                                                 &mut outbound_payments.lock().unwrap(),
243                                                                 Arc::clone(&fs_store),
244                                                         ),
245                                                         Err(e) => {
246                                                                 println!("ERROR: invalid invoice: {:?}", e);
247                                                         }
248                                                 }
249                                         }
250                                 }
251                                 "keysend" => {
252                                         let dest_pubkey = match words.next() {
253                                                 Some(dest) => match hex_utils::to_compressed_pubkey(dest) {
254                                                         Some(pk) => pk,
255                                                         None => {
256                                                                 println!("ERROR: couldn't parse destination pubkey");
257                                                                 continue;
258                                                         }
259                                                 },
260                                                 None => {
261                                                         println!("ERROR: keysend requires a destination pubkey: `keysend <dest_pubkey> <amt_msat>`");
262                                                         continue;
263                                                 }
264                                         };
265                                         let amt_msat_str = match words.next() {
266                                                 Some(amt) => amt,
267                                                 None => {
268                                                         println!("ERROR: keysend requires an amount in millisatoshis: `keysend <dest_pubkey> <amt_msat>`");
269                                                         continue;
270                                                 }
271                                         };
272                                         let amt_msat: u64 = match amt_msat_str.parse() {
273                                                 Ok(amt) => amt,
274                                                 Err(e) => {
275                                                         println!("ERROR: couldn't parse amount_msat: {}", e);
276                                                         continue;
277                                                 }
278                                         };
279                                         keysend(
280                                                 &channel_manager,
281                                                 dest_pubkey,
282                                                 amt_msat,
283                                                 &*keys_manager,
284                                                 &mut outbound_payments.lock().unwrap(),
285                                                 Arc::clone(&fs_store),
286                                         );
287                                 }
288                                 "getoffer" => {
289                                         let offer_builder = channel_manager.create_offer_builder(String::new());
290                                         if let Err(e) = offer_builder {
291                                                 println!("ERROR: Failed to initiate offer building: {:?}", e);
292                                                 continue;
293                                         }
294
295                                         let amt_str = words.next();
296                                         let offer = if amt_str.is_some() {
297                                                 let amt_msat: Result<u64, _> = amt_str.unwrap().parse();
298                                                 if amt_msat.is_err() {
299                                                         println!("ERROR: getoffer provided payment amount was not a number");
300                                                         continue;
301                                                 }
302                                                 offer_builder.unwrap().amount_msats(amt_msat.unwrap()).build()
303                                         } else {
304                                                 offer_builder.unwrap().build()
305                                         };
306
307                                         if offer.is_err() {
308                                                 println!("ERROR: Failed to build offer: {:?}", offer.unwrap_err());
309                                         } else {
310                                                 // Note that unlike BOLT11 invoice creation we don't bother to add a
311                                                 // pending inbound payment here, as offers can be reused and don't
312                                                 // correspond with individual payments.
313                                                 println!("{}", offer.unwrap());
314                                         }
315                                 }
316                                 "getinvoice" => {
317                                         let amt_str = words.next();
318                                         if amt_str.is_none() {
319                                                 println!("ERROR: getinvoice requires an amount in millisatoshis");
320                                                 continue;
321                                         }
322
323                                         let amt_msat: Result<u64, _> = amt_str.unwrap().parse();
324                                         if amt_msat.is_err() {
325                                                 println!("ERROR: getinvoice provided payment amount was not a number");
326                                                 continue;
327                                         }
328
329                                         let expiry_secs_str = words.next();
330                                         if expiry_secs_str.is_none() {
331                                                 println!("ERROR: getinvoice requires an expiry in seconds");
332                                                 continue;
333                                         }
334
335                                         let expiry_secs: Result<u32, _> = expiry_secs_str.unwrap().parse();
336                                         if expiry_secs.is_err() {
337                                                 println!("ERROR: getinvoice provided expiry was not a number");
338                                                 continue;
339                                         }
340
341                                         let mut inbound_payments = inbound_payments.lock().unwrap();
342                                         get_invoice(
343                                                 amt_msat.unwrap(),
344                                                 &mut inbound_payments,
345                                                 &channel_manager,
346                                                 Arc::clone(&keys_manager),
347                                                 network,
348                                                 expiry_secs.unwrap(),
349                                                 Arc::clone(&logger),
350                                         );
351                                         fs_store
352                                                 .write("", "", INBOUND_PAYMENTS_FNAME, &inbound_payments.encode())
353                                                 .unwrap();
354                                 }
355                                 "connectpeer" => {
356                                         let peer_pubkey_and_ip_addr = words.next();
357                                         if peer_pubkey_and_ip_addr.is_none() {
358                                                 println!("ERROR: connectpeer requires peer connection info: `connectpeer pubkey@host:port`");
359                                                 continue;
360                                         }
361                                         let (pubkey, peer_addr) =
362                                                 match parse_peer_info(peer_pubkey_and_ip_addr.unwrap().to_string()) {
363                                                         Ok(info) => info,
364                                                         Err(e) => {
365                                                                 println!("{:?}", e.into_inner().unwrap());
366                                                                 continue;
367                                                         }
368                                                 };
369                                         if tokio::runtime::Handle::current()
370                                                 .block_on(connect_peer_if_necessary(
371                                                         pubkey,
372                                                         peer_addr,
373                                                         peer_manager.clone(),
374                                                 ))
375                                                 .is_ok()
376                                         {
377                                                 println!("SUCCESS: connected to peer {}", pubkey);
378                                         }
379                                 }
380                                 "disconnectpeer" => {
381                                         let peer_pubkey = words.next();
382                                         if peer_pubkey.is_none() {
383                                                 println!("ERROR: disconnectpeer requires peer public key: `disconnectpeer <peer_pubkey>`");
384                                                 continue;
385                                         }
386
387                                         let peer_pubkey =
388                                                 match bitcoin::secp256k1::PublicKey::from_str(peer_pubkey.unwrap()) {
389                                                         Ok(pubkey) => pubkey,
390                                                         Err(e) => {
391                                                                 println!("ERROR: {}", e.to_string());
392                                                                 continue;
393                                                         }
394                                                 };
395
396                                         if do_disconnect_peer(
397                                                 peer_pubkey,
398                                                 peer_manager.clone(),
399                                                 channel_manager.clone(),
400                                         )
401                                         .is_ok()
402                                         {
403                                                 println!("SUCCESS: disconnected from peer {}", peer_pubkey);
404                                         }
405                                 }
406                                 "listchannels" => list_channels(&channel_manager, &network_graph),
407                                 "listpayments" => list_payments(
408                                         &inbound_payments.lock().unwrap(),
409                                         &outbound_payments.lock().unwrap(),
410                                 ),
411                                 "closechannel" => {
412                                         let channel_id_str = words.next();
413                                         if channel_id_str.is_none() {
414                                                 println!("ERROR: closechannel requires a channel ID: `closechannel <channel_id> <peer_pubkey>`");
415                                                 continue;
416                                         }
417                                         let channel_id_vec = hex_utils::to_vec(channel_id_str.unwrap());
418                                         if channel_id_vec.is_none() || channel_id_vec.as_ref().unwrap().len() != 32 {
419                                                 println!("ERROR: couldn't parse channel_id");
420                                                 continue;
421                                         }
422                                         let mut channel_id = [0; 32];
423                                         channel_id.copy_from_slice(&channel_id_vec.unwrap());
424
425                                         let peer_pubkey_str = words.next();
426                                         if peer_pubkey_str.is_none() {
427                                                 println!("ERROR: closechannel requires a peer pubkey: `closechannel <channel_id> <peer_pubkey>`");
428                                                 continue;
429                                         }
430                                         let peer_pubkey_vec = match hex_utils::to_vec(peer_pubkey_str.unwrap()) {
431                                                 Some(peer_pubkey_vec) => peer_pubkey_vec,
432                                                 None => {
433                                                         println!("ERROR: couldn't parse peer_pubkey");
434                                                         continue;
435                                                 }
436                                         };
437                                         let peer_pubkey = match PublicKey::from_slice(&peer_pubkey_vec) {
438                                                 Ok(peer_pubkey) => peer_pubkey,
439                                                 Err(_) => {
440                                                         println!("ERROR: couldn't parse peer_pubkey");
441                                                         continue;
442                                                 }
443                                         };
444
445                                         close_channel(channel_id, peer_pubkey, channel_manager.clone());
446                                 }
447                                 "forceclosechannel" => {
448                                         let channel_id_str = words.next();
449                                         if channel_id_str.is_none() {
450                                                 println!("ERROR: forceclosechannel requires a channel ID: `forceclosechannel <channel_id> <peer_pubkey>`");
451                                                 continue;
452                                         }
453                                         let channel_id_vec = hex_utils::to_vec(channel_id_str.unwrap());
454                                         if channel_id_vec.is_none() || channel_id_vec.as_ref().unwrap().len() != 32 {
455                                                 println!("ERROR: couldn't parse channel_id");
456                                                 continue;
457                                         }
458                                         let mut channel_id = [0; 32];
459                                         channel_id.copy_from_slice(&channel_id_vec.unwrap());
460
461                                         let peer_pubkey_str = words.next();
462                                         if peer_pubkey_str.is_none() {
463                                                 println!("ERROR: forceclosechannel requires a peer pubkey: `forceclosechannel <channel_id> <peer_pubkey>`");
464                                                 continue;
465                                         }
466                                         let peer_pubkey_vec = match hex_utils::to_vec(peer_pubkey_str.unwrap()) {
467                                                 Some(peer_pubkey_vec) => peer_pubkey_vec,
468                                                 None => {
469                                                         println!("ERROR: couldn't parse peer_pubkey");
470                                                         continue;
471                                                 }
472                                         };
473                                         let peer_pubkey = match PublicKey::from_slice(&peer_pubkey_vec) {
474                                                 Ok(peer_pubkey) => peer_pubkey,
475                                                 Err(_) => {
476                                                         println!("ERROR: couldn't parse peer_pubkey");
477                                                         continue;
478                                                 }
479                                         };
480
481                                         force_close_channel(channel_id, peer_pubkey, channel_manager.clone());
482                                 }
483                                 "nodeinfo" => node_info(&channel_manager, &peer_manager),
484                                 "listpeers" => list_peers(peer_manager.clone()),
485                                 "signmessage" => {
486                                         const MSG_STARTPOS: usize = "signmessage".len() + 1;
487                                         if line.trim().as_bytes().len() <= MSG_STARTPOS {
488                                                 println!("ERROR: signmsg requires a message");
489                                                 continue;
490                                         }
491                                         println!(
492                                                 "{:?}",
493                                                 lightning::util::message_signing::sign(
494                                                         &line.trim().as_bytes()[MSG_STARTPOS..],
495                                                         &keys_manager.get_node_secret_key()
496                                                 )
497                                         );
498                                 }
499                                 "sendonionmessage" => {
500                                         let path_pks_str = words.next();
501                                         if path_pks_str.is_none() {
502                                                 println!(
503                                                         "ERROR: sendonionmessage requires at least one node id for the path"
504                                                 );
505                                                 continue;
506                                         }
507                                         let mut intermediate_nodes = Vec::new();
508                                         let mut errored = false;
509                                         for pk_str in path_pks_str.unwrap().split(",") {
510                                                 let node_pubkey_vec = match hex_utils::to_vec(pk_str) {
511                                                         Some(peer_pubkey_vec) => peer_pubkey_vec,
512                                                         None => {
513                                                                 println!("ERROR: couldn't parse peer_pubkey");
514                                                                 errored = true;
515                                                                 break;
516                                                         }
517                                                 };
518                                                 let node_pubkey = match PublicKey::from_slice(&node_pubkey_vec) {
519                                                         Ok(peer_pubkey) => peer_pubkey,
520                                                         Err(_) => {
521                                                                 println!("ERROR: couldn't parse peer_pubkey");
522                                                                 errored = true;
523                                                                 break;
524                                                         }
525                                                 };
526                                                 intermediate_nodes.push(node_pubkey);
527                                         }
528                                         if errored {
529                                                 continue;
530                                         }
531                                         let tlv_type = match words.next().map(|ty_str| ty_str.parse()) {
532                                                 Some(Ok(ty)) if ty >= 64 => ty,
533                                                 _ => {
534                                                         println!("Need an integral message type above 64");
535                                                         continue;
536                                                 }
537                                         };
538                                         let data = match words.next().map(|s| hex_utils::to_vec(s)) {
539                                                 Some(Some(data)) => data,
540                                                 _ => {
541                                                         println!("Need a hex data string");
542                                                         continue;
543                                                 }
544                                         };
545                                         let destination = Destination::Node(intermediate_nodes.pop().unwrap());
546                                         match onion_messenger.send_onion_message(
547                                                 UserOnionMessageContents { tlv_type, data },
548                                                 destination,
549                                                 None,
550                                         ) {
551                                                 Ok(success) => {
552                                                         println!("SUCCESS: forwarded onion message to first hop {:?}", success)
553                                                 }
554                                                 Err(e) => println!("ERROR: failed to send onion message: {:?}", e),
555                                         }
556                                 }
557                                 "quit" | "exit" => break,
558                                 _ => println!("Unknown command. See `\"help\" for available commands."),
559                         }
560                 }
561         }
562 }
563
564 fn help() {
565         let package_version = env!("CARGO_PKG_VERSION");
566         let package_name = env!("CARGO_PKG_NAME");
567         println!("\nVERSION:");
568         println!("  {} v{}", package_name, package_version);
569         println!("\nUSAGE:");
570         println!("  Command [arguments]");
571         println!("\nCOMMANDS:");
572         println!("  help\tShows a list of commands.");
573         println!("  quit\tClose the application.");
574         println!("\n  Channels:");
575         println!("      openchannel pubkey@host:port <amt_satoshis> [--public] [--with-anchors]");
576         println!("      closechannel <channel_id> <peer_pubkey>");
577         println!("      forceclosechannel <channel_id> <peer_pubkey>");
578         println!("      listchannels");
579         println!("\n  Peers:");
580         println!("      connectpeer pubkey@host:port");
581         println!("      disconnectpeer <peer_pubkey>");
582         println!("      listpeers");
583         println!("\n  Payments:");
584         println!("      sendpayment <invoice|offer> [<amount_msat>]");
585         println!("      keysend <dest_pubkey> <amt_msats>");
586         println!("      listpayments");
587         println!("\n  Invoices:");
588         println!("      getinvoice <amt_msats> <expiry_secs>");
589         println!("      getoffer [<amt_msats>]");
590         println!("\n  Other:");
591         println!("      signmessage <message>");
592         println!(
593                 "      sendonionmessage <node_id_1,node_id_2,..,destination_node_id> <type> <hex_bytes>"
594         );
595         println!("      nodeinfo");
596 }
597
598 fn node_info(channel_manager: &Arc<ChannelManager>, peer_manager: &Arc<PeerManager>) {
599         println!("\t{{");
600         println!("\t\t node_pubkey: {}", channel_manager.get_our_node_id());
601         let chans = channel_manager.list_channels();
602         println!("\t\t num_channels: {}", chans.len());
603         println!("\t\t num_usable_channels: {}", chans.iter().filter(|c| c.is_usable).count());
604         let local_balance_msat = chans.iter().map(|c| c.balance_msat).sum::<u64>();
605         println!("\t\t local_balance_msat: {}", local_balance_msat);
606         println!("\t\t num_peers: {}", peer_manager.get_peer_node_ids().len());
607         println!("\t}},");
608 }
609
610 fn list_peers(peer_manager: Arc<PeerManager>) {
611         println!("\t{{");
612         for (pubkey, _) in peer_manager.get_peer_node_ids() {
613                 println!("\t\t pubkey: {}", pubkey);
614         }
615         println!("\t}},");
616 }
617
618 fn list_channels(channel_manager: &Arc<ChannelManager>, network_graph: &Arc<NetworkGraph>) {
619         print!("[");
620         for chan_info in channel_manager.list_channels() {
621                 println!("");
622                 println!("\t{{");
623                 println!("\t\tchannel_id: {},", chan_info.channel_id);
624                 if let Some(funding_txo) = chan_info.funding_txo {
625                         println!("\t\tfunding_txid: {},", funding_txo.txid);
626                 }
627
628                 println!(
629                         "\t\tpeer_pubkey: {},",
630                         hex_utils::hex_str(&chan_info.counterparty.node_id.serialize())
631                 );
632                 if let Some(node_info) = network_graph
633                         .read_only()
634                         .nodes()
635                         .get(&NodeId::from_pubkey(&chan_info.counterparty.node_id))
636                 {
637                         if let Some(announcement) = &node_info.announcement_info {
638                                 println!("\t\tpeer_alias: {}", announcement.alias);
639                         }
640                 }
641
642                 if let Some(id) = chan_info.short_channel_id {
643                         println!("\t\tshort_channel_id: {},", id);
644                 }
645                 println!("\t\tis_channel_ready: {},", chan_info.is_channel_ready);
646                 println!("\t\tchannel_value_satoshis: {},", chan_info.channel_value_satoshis);
647                 println!("\t\toutbound_capacity_msat: {},", chan_info.outbound_capacity_msat);
648                 if chan_info.is_usable {
649                         println!("\t\tavailable_balance_for_send_msat: {},", chan_info.outbound_capacity_msat);
650                         println!("\t\tavailable_balance_for_recv_msat: {},", chan_info.inbound_capacity_msat);
651                 }
652                 println!("\t\tchannel_can_send_payments: {},", chan_info.is_usable);
653                 println!("\t\tpublic: {},", chan_info.is_public);
654                 println!("\t}},");
655         }
656         println!("]");
657 }
658
659 fn list_payments(
660         inbound_payments: &InboundPaymentInfoStorage, outbound_payments: &OutboundPaymentInfoStorage,
661 ) {
662         print!("[");
663         for (payment_hash, payment_info) in &inbound_payments.payments {
664                 println!("");
665                 println!("\t{{");
666                 println!("\t\tamount_millisatoshis: {},", payment_info.amt_msat);
667                 println!("\t\tpayment_hash: {},", payment_hash);
668                 println!("\t\thtlc_direction: inbound,");
669                 println!(
670                         "\t\thtlc_status: {},",
671                         match payment_info.status {
672                                 HTLCStatus::Pending => "pending",
673                                 HTLCStatus::Succeeded => "succeeded",
674                                 HTLCStatus::Failed => "failed",
675                         }
676                 );
677
678                 println!("\t}},");
679         }
680
681         for (payment_hash, payment_info) in &outbound_payments.payments {
682                 println!("");
683                 println!("\t{{");
684                 println!("\t\tamount_millisatoshis: {},", payment_info.amt_msat);
685                 println!("\t\tpayment_hash: {},", payment_hash);
686                 println!("\t\thtlc_direction: outbound,");
687                 println!(
688                         "\t\thtlc_status: {},",
689                         match payment_info.status {
690                                 HTLCStatus::Pending => "pending",
691                                 HTLCStatus::Succeeded => "succeeded",
692                                 HTLCStatus::Failed => "failed",
693                         }
694                 );
695
696                 println!("\t}},");
697         }
698         println!("]");
699 }
700
701 pub(crate) async fn connect_peer_if_necessary(
702         pubkey: PublicKey, peer_addr: SocketAddr, peer_manager: Arc<PeerManager>,
703 ) -> Result<(), ()> {
704         for (node_pubkey, _) in peer_manager.get_peer_node_ids() {
705                 if node_pubkey == pubkey {
706                         return Ok(());
707                 }
708         }
709         let res = do_connect_peer(pubkey, peer_addr, peer_manager).await;
710         if res.is_err() {
711                 println!("ERROR: failed to connect to peer");
712         }
713         res
714 }
715
716 pub(crate) async fn do_connect_peer(
717         pubkey: PublicKey, peer_addr: SocketAddr, peer_manager: Arc<PeerManager>,
718 ) -> Result<(), ()> {
719         match lightning_net_tokio::connect_outbound(Arc::clone(&peer_manager), pubkey, peer_addr).await
720         {
721                 Some(connection_closed_future) => {
722                         let mut connection_closed_future = Box::pin(connection_closed_future);
723                         loop {
724                                 tokio::select! {
725                                         _ = &mut connection_closed_future => return Err(()),
726                                         _ = tokio::time::sleep(Duration::from_millis(10)) => {},
727                                 };
728                                 if peer_manager.get_peer_node_ids().iter().find(|(id, _)| *id == pubkey).is_some() {
729                                         return Ok(());
730                                 }
731                         }
732                 }
733                 None => Err(()),
734         }
735 }
736
737 fn do_disconnect_peer(
738         pubkey: bitcoin::secp256k1::PublicKey, peer_manager: Arc<PeerManager>,
739         channel_manager: Arc<ChannelManager>,
740 ) -> Result<(), ()> {
741         //check for open channels with peer
742         for channel in channel_manager.list_channels() {
743                 if channel.counterparty.node_id == pubkey {
744                         println!("Error: Node has an active channel with this peer, close any channels first");
745                         return Err(());
746                 }
747         }
748
749         //check the pubkey matches a valid connected peer
750         let peers = peer_manager.get_peer_node_ids();
751         if !peers.iter().any(|(pk, _)| &pubkey == pk) {
752                 println!("Error: Could not find peer {}", pubkey);
753                 return Err(());
754         }
755
756         peer_manager.disconnect_by_node_id(pubkey);
757         Ok(())
758 }
759
760 fn open_channel(
761         peer_pubkey: PublicKey, channel_amt_sat: u64, announced_channel: bool, with_anchors: bool,
762         channel_manager: Arc<ChannelManager>,
763 ) -> Result<(), ()> {
764         let config = UserConfig {
765                 channel_handshake_limits: ChannelHandshakeLimits {
766                         // lnd's max to_self_delay is 2016, so we want to be compatible.
767                         their_to_self_delay: 2016,
768                         ..Default::default()
769                 },
770                 channel_handshake_config: ChannelHandshakeConfig {
771                         announced_channel,
772                         negotiate_anchors_zero_fee_htlc_tx: with_anchors,
773                         ..Default::default()
774                 },
775                 ..Default::default()
776         };
777
778         match channel_manager.create_channel(peer_pubkey, channel_amt_sat, 0, 0, None, Some(config)) {
779                 Ok(_) => {
780                         println!("EVENT: initiated channel with peer {}. ", peer_pubkey);
781                         return Ok(());
782                 }
783                 Err(e) => {
784                         println!("ERROR: failed to open channel: {:?}", e);
785                         return Err(());
786                 }
787         }
788 }
789
790 fn send_payment(
791         channel_manager: &ChannelManager, invoice: &Bolt11Invoice, required_amount_msat: Option<u64>,
792         outbound_payments: &mut OutboundPaymentInfoStorage, fs_store: Arc<FilesystemStore>,
793 ) {
794         let payment_id = PaymentId((*invoice.payment_hash()).to_byte_array());
795         let payment_secret = Some(*invoice.payment_secret());
796         let zero_amt_invoice =
797                 invoice.amount_milli_satoshis().is_none() || invoice.amount_milli_satoshis() == Some(0);
798         let pay_params_opt = if zero_amt_invoice {
799                 if let Some(amt_msat) = required_amount_msat {
800                         payment_parameters_from_zero_amount_invoice(invoice, amt_msat)
801                 } else {
802                         println!("Need an amount for the given 0-value invoice");
803                         print!("> ");
804                         return;
805                 }
806         } else {
807                 if required_amount_msat.is_some() && invoice.amount_milli_satoshis() != required_amount_msat
808                 {
809                         println!(
810                                 "Amount didn't match invoice value of {}msat",
811                                 invoice.amount_milli_satoshis().unwrap_or(0)
812                         );
813                         print!("> ");
814                         return;
815                 }
816                 payment_parameters_from_invoice(invoice)
817         };
818         let (payment_hash, recipient_onion, route_params) = match pay_params_opt {
819                 Ok(res) => res,
820                 Err(e) => {
821                         println!("Failed to parse invoice");
822                         print!("> ");
823                         return;
824                 }
825         };
826         outbound_payments.payments.insert(
827                 payment_id,
828                 PaymentInfo {
829                         preimage: None,
830                         secret: payment_secret,
831                         status: HTLCStatus::Pending,
832                         amt_msat: MillisatAmount(invoice.amount_milli_satoshis()),
833                 },
834         );
835         fs_store.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode()).unwrap();
836
837         match channel_manager.send_payment(
838                 payment_hash,
839                 recipient_onion,
840                 payment_id,
841                 route_params,
842                 Retry::Timeout(Duration::from_secs(10)),
843         ) {
844                 Ok(_) => {
845                         let payee_pubkey = invoice.recover_payee_pub_key();
846                         let amt_msat = invoice.amount_milli_satoshis().unwrap();
847                         println!("EVENT: initiated sending {} msats to {}", amt_msat, payee_pubkey);
848                         print!("> ");
849                 }
850                 Err(e) => {
851                         println!("ERROR: failed to send payment: {:?}", e);
852                         print!("> ");
853                         outbound_payments.payments.get_mut(&payment_id).unwrap().status = HTLCStatus::Failed;
854                         fs_store.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode()).unwrap();
855                 }
856         };
857 }
858
859 fn keysend<E: EntropySource>(
860         channel_manager: &ChannelManager, payee_pubkey: PublicKey, amt_msat: u64, entropy_source: &E,
861         outbound_payments: &mut OutboundPaymentInfoStorage, fs_store: Arc<FilesystemStore>,
862 ) {
863         let payment_preimage = PaymentPreimage(entropy_source.get_secure_random_bytes());
864         let payment_id = PaymentId(Sha256::hash(&payment_preimage.0[..]).to_byte_array());
865
866         let route_params = RouteParameters::from_payment_params_and_value(
867                 PaymentParameters::for_keysend(payee_pubkey, 40, false),
868                 amt_msat,
869         );
870         outbound_payments.payments.insert(
871                 payment_id,
872                 PaymentInfo {
873                         preimage: None,
874                         secret: None,
875                         status: HTLCStatus::Pending,
876                         amt_msat: MillisatAmount(Some(amt_msat)),
877                 },
878         );
879         fs_store.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode()).unwrap();
880         match channel_manager.send_spontaneous_payment_with_retry(
881                 Some(payment_preimage),
882                 RecipientOnionFields::spontaneous_empty(),
883                 payment_id,
884                 route_params,
885                 Retry::Timeout(Duration::from_secs(10)),
886         ) {
887                 Ok(_payment_hash) => {
888                         println!("EVENT: initiated sending {} msats to {}", amt_msat, payee_pubkey);
889                         print!("> ");
890                 }
891                 Err(e) => {
892                         println!("ERROR: failed to send payment: {:?}", e);
893                         print!("> ");
894                         outbound_payments.payments.get_mut(&payment_id).unwrap().status = HTLCStatus::Failed;
895                         fs_store.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode()).unwrap();
896                 }
897         };
898 }
899
900 fn get_invoice(
901         amt_msat: u64, inbound_payments: &mut InboundPaymentInfoStorage,
902         channel_manager: &ChannelManager, keys_manager: Arc<KeysManager>, network: Network,
903         expiry_secs: u32, logger: Arc<disk::FilesystemLogger>,
904 ) {
905         let currency = match network {
906                 Network::Bitcoin => Currency::Bitcoin,
907                 Network::Regtest => Currency::Regtest,
908                 Network::Signet => Currency::Signet,
909                 Network::Testnet | _ => Currency::BitcoinTestnet,
910         };
911         let invoice = match utils::create_invoice_from_channelmanager(
912                 channel_manager,
913                 keys_manager,
914                 logger,
915                 currency,
916                 Some(amt_msat),
917                 "ldk-tutorial-node".to_string(),
918                 expiry_secs,
919                 None,
920         ) {
921                 Ok(inv) => {
922                         println!("SUCCESS: generated invoice: {}", inv);
923                         inv
924                 }
925                 Err(e) => {
926                         println!("ERROR: failed to create invoice: {:?}", e);
927                         return;
928                 }
929         };
930
931         let payment_hash = PaymentHash(invoice.payment_hash().to_byte_array());
932         inbound_payments.payments.insert(
933                 payment_hash,
934                 PaymentInfo {
935                         preimage: None,
936                         secret: Some(invoice.payment_secret().clone()),
937                         status: HTLCStatus::Pending,
938                         amt_msat: MillisatAmount(Some(amt_msat)),
939                 },
940         );
941 }
942
943 fn close_channel(
944         channel_id: [u8; 32], counterparty_node_id: PublicKey, channel_manager: Arc<ChannelManager>,
945 ) {
946         match channel_manager.close_channel(&ChannelId(channel_id), &counterparty_node_id) {
947                 Ok(()) => println!("EVENT: initiating channel close"),
948                 Err(e) => println!("ERROR: failed to close channel: {:?}", e),
949         }
950 }
951
952 fn force_close_channel(
953         channel_id: [u8; 32], counterparty_node_id: PublicKey, channel_manager: Arc<ChannelManager>,
954 ) {
955         match channel_manager
956                 .force_close_broadcasting_latest_txn(&ChannelId(channel_id), &counterparty_node_id)
957         {
958                 Ok(()) => println!("EVENT: initiating channel force-close"),
959                 Err(e) => println!("ERROR: failed to force-close channel: {:?}", e),
960         }
961 }
962
963 pub(crate) fn parse_peer_info(
964         peer_pubkey_and_ip_addr: String,
965 ) -> Result<(PublicKey, SocketAddr), std::io::Error> {
966         let mut pubkey_and_addr = peer_pubkey_and_ip_addr.split("@");
967         let pubkey = pubkey_and_addr.next();
968         let peer_addr_str = pubkey_and_addr.next();
969         if peer_addr_str.is_none() {
970                 return Err(std::io::Error::new(
971                         std::io::ErrorKind::Other,
972                         "ERROR: incorrectly formatted peer info. Should be formatted as: `pubkey@host:port`",
973                 ));
974         }
975
976         let peer_addr = peer_addr_str.unwrap().to_socket_addrs().map(|mut r| r.next());
977         if peer_addr.is_err() || peer_addr.as_ref().unwrap().is_none() {
978                 return Err(std::io::Error::new(
979                         std::io::ErrorKind::Other,
980                         "ERROR: couldn't parse pubkey@host:port into a socket address",
981                 ));
982         }
983
984         let pubkey = hex_utils::to_compressed_pubkey(pubkey.unwrap());
985         if pubkey.is_none() {
986                 return Err(std::io::Error::new(
987                         std::io::ErrorKind::Other,
988                         "ERROR: unable to parse given pubkey for node",
989                 ));
990         }
991
992         Ok((pubkey.unwrap(), peer_addr.unwrap().unwrap()))
993 }