2dc6b7df614731296ab9e479a9b697d2f4c086a7
[ldk-sample] / src / cli.rs
1 use crate::disk;
2 use crate::hex_utils;
3 use crate::{
4         ChannelManager, FilesystemLogger, HTLCStatus, MillisatAmount, PaymentInfo,
5         PaymentInfoStorage, PeerManager,
6 };
7 use bitcoin::hashes::sha256::Hash as Sha256Hash;
8 use bitcoin::hashes::Hash;
9 use bitcoin::network::constants::Network;
10 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
11 use bitcoin::secp256k1::Secp256k1;
12 use lightning::chain;
13 use lightning::ln::channelmanager::{PaymentHash, PaymentPreimage, PaymentSecret};
14 use lightning::ln::features::InvoiceFeatures;
15 use lightning::routing::network_graph::{NetGraphMsgHandler, RoutingFees};
16 use lightning::routing::router;
17 use lightning::routing::router::RouteHint;
18 use lightning::util::config::UserConfig;
19 use rand;
20 use rand::Rng;
21 use std::env;
22 use std::io;
23 use std::io::{BufRead, Write};
24 use std::net::{SocketAddr, TcpStream};
25 use std::ops::Deref;
26 use std::path::Path;
27 use std::str::FromStr;
28 use std::sync::Arc;
29 use std::time::Duration;
30 use tokio::sync::mpsc;
31
32 pub(crate) struct LdkUserInfo {
33         pub(crate) bitcoind_rpc_username: String,
34         pub(crate) bitcoind_rpc_password: String,
35         pub(crate) bitcoind_rpc_port: u16,
36         pub(crate) bitcoind_rpc_host: String,
37         pub(crate) ldk_storage_dir_path: String,
38         pub(crate) ldk_peer_listening_port: u16,
39         pub(crate) network: Network,
40 }
41
42 pub(crate) fn parse_startup_args() -> Result<LdkUserInfo, ()> {
43         if env::args().len() < 4 {
44                 println!("ldk-tutorial-node requires 3 arguments: `cargo run <bitcoind-rpc-username>:<bitcoind-rpc-password>@<bitcoind-rpc-host>:<bitcoind-rpc-port> ldk_storage_directory_path [<ldk-incoming-peer-listening-port>] [bitcoin-network]`");
45                 return Err(());
46         }
47         let bitcoind_rpc_info = env::args().skip(1).next().unwrap();
48         let bitcoind_rpc_info_parts: Vec<&str> = bitcoind_rpc_info.split("@").collect();
49         if bitcoind_rpc_info_parts.len() != 2 {
50                 println!("ERROR: bad bitcoind RPC URL provided");
51                 return Err(());
52         }
53         let rpc_user_and_password: Vec<&str> = bitcoind_rpc_info_parts[0].split(":").collect();
54         if rpc_user_and_password.len() != 2 {
55                 println!("ERROR: bad bitcoind RPC username/password combo provided");
56                 return Err(());
57         }
58         let bitcoind_rpc_username = rpc_user_and_password[0].to_string();
59         let bitcoind_rpc_password = rpc_user_and_password[1].to_string();
60         let bitcoind_rpc_path: Vec<&str> = bitcoind_rpc_info_parts[1].split(":").collect();
61         if bitcoind_rpc_path.len() != 2 {
62                 println!("ERROR: bad bitcoind RPC path provided");
63                 return Err(());
64         }
65         let bitcoind_rpc_host = bitcoind_rpc_path[0].to_string();
66         let bitcoind_rpc_port = bitcoind_rpc_path[1].parse::<u16>().unwrap();
67
68         let ldk_storage_dir_path = env::args().skip(2).next().unwrap();
69
70         let mut ldk_peer_port_set = true;
71         let ldk_peer_listening_port: u16 = match env::args().skip(3).next().map(|p| p.parse()) {
72                 Some(Ok(p)) => p,
73                 Some(Err(e)) => panic!(e),
74                 None => {
75                         ldk_peer_port_set = false;
76                         9735
77                 }
78         };
79
80         let arg_idx = match ldk_peer_port_set {
81                 true => 4,
82                 false => 3,
83         };
84         let network: Network = match env::args().skip(arg_idx).next().as_ref().map(String::as_str) {
85                 Some("testnet") => Network::Testnet,
86                 Some("regtest") => Network::Regtest,
87                 Some(_) => panic!("Unsupported network provided. Options are: `regtest`, `testnet`"),
88                 None => Network::Testnet,
89         };
90         Ok(LdkUserInfo {
91                 bitcoind_rpc_username,
92                 bitcoind_rpc_password,
93                 bitcoind_rpc_host,
94                 bitcoind_rpc_port,
95                 ldk_storage_dir_path,
96                 ldk_peer_listening_port,
97                 network,
98         })
99 }
100
101 pub(crate) async fn poll_for_user_input(
102         peer_manager: Arc<PeerManager>, channel_manager: Arc<ChannelManager>,
103         router: Arc<NetGraphMsgHandler<Arc<dyn chain::Access>, Arc<FilesystemLogger>>>,
104         payment_storage: PaymentInfoStorage, node_privkey: SecretKey, event_notifier: mpsc::Sender<()>,
105         ldk_data_dir: String, logger: Arc<FilesystemLogger>, network: Network,
106 ) {
107         println!("LDK startup successful. To view available commands: \"help\".\nLDK logs are available at <your-supplied-ldk-data-dir-path>/.ldk/logs");
108         let stdin = io::stdin();
109         print!("> ");
110         io::stdout().flush().unwrap(); // Without flushing, the `>` doesn't print
111         for line in stdin.lock().lines() {
112                 let _ = event_notifier.try_send(());
113                 let line = line.unwrap();
114                 let mut words = line.split_whitespace();
115                 if let Some(word) = words.next() {
116                         match word {
117                                 "help" => help(),
118                                 "openchannel" => {
119                                         let peer_pubkey_and_ip_addr = words.next();
120                                         let channel_value_sat = words.next();
121                                         if peer_pubkey_and_ip_addr.is_none() || channel_value_sat.is_none() {
122                                                 println!("ERROR: openchannel has 2 required arguments: `openchannel pubkey@host:port channel_amt_satoshis` [--public]");
123                                                 print!("> ");
124                                                 io::stdout().flush().unwrap();
125                                                 continue;
126                                         }
127                                         let peer_pubkey_and_ip_addr = peer_pubkey_and_ip_addr.unwrap();
128                                         let (pubkey, peer_addr) =
129                                                 match parse_peer_info(peer_pubkey_and_ip_addr.to_string()) {
130                                                         Ok(info) => info,
131                                                         Err(e) => {
132                                                                 println!("{:?}", e.into_inner().unwrap());
133                                                                 print!("> ");
134                                                                 io::stdout().flush().unwrap();
135                                                                 continue;
136                                                         }
137                                                 };
138
139                                         let chan_amt_sat: Result<u64, _> = channel_value_sat.unwrap().parse();
140                                         if chan_amt_sat.is_err() {
141                                                 println!("ERROR: channel amount must be a number");
142                                                 print!("> ");
143                                                 io::stdout().flush().unwrap();
144                                                 continue;
145                                         }
146
147                                         if connect_peer_if_necessary(
148                                                 pubkey,
149                                                 peer_addr,
150                                                 peer_manager.clone(),
151                                                 event_notifier.clone(),
152                                         )
153                                         .is_err()
154                                         {
155                                                 print!("> ");
156                                                 io::stdout().flush().unwrap();
157                                                 continue;
158                                         };
159
160                                         let announce_channel = match words.next() {
161                                                 Some("--public") | Some("--public=true") => true,
162                                                 Some("--public=false") => false,
163                                                 Some(_) => {
164                                                         println!("ERROR: invalid `--public` command format. Valid formats: `--public`, `--public=true` `--public=false`");
165                                                         print!("> ");
166                                                         io::stdout().flush().unwrap();
167                                                         continue;
168                                                 }
169                                                 None => false,
170                                         };
171
172                                         if open_channel(
173                                                 pubkey,
174                                                 chan_amt_sat.unwrap(),
175                                                 announce_channel,
176                                                 channel_manager.clone(),
177                                         )
178                                         .is_ok()
179                                         {
180                                                 let peer_data_path = format!("{}/channel_peer_data", ldk_data_dir.clone());
181                                                 let _ = disk::persist_channel_peer(
182                                                         Path::new(&peer_data_path),
183                                                         peer_pubkey_and_ip_addr,
184                                                 );
185                                         }
186                                 }
187                                 "sendpayment" => {
188                                         let invoice_str = words.next();
189                                         if invoice_str.is_none() {
190                                                 println!("ERROR: sendpayment requires an invoice: `sendpayment <invoice>`");
191                                                 print!("> ");
192                                                 io::stdout().flush().unwrap();
193                                                 continue;
194                                         }
195
196                                         let invoice_res = lightning_invoice::Invoice::from_str(invoice_str.unwrap());
197                                         if invoice_res.is_err() {
198                                                 println!("ERROR: invalid invoice: {:?}", invoice_res.unwrap_err());
199                                                 print!("> ");
200                                                 io::stdout().flush().unwrap();
201                                                 continue;
202                                         }
203                                         let invoice = invoice_res.unwrap();
204                                         let route_hints: Vec<lightning_invoice::Route> =
205                                                 invoice.routes().iter().map(|&route| route.clone()).collect();
206
207                                         let amt_pico_btc = invoice.amount_pico_btc();
208                                         if amt_pico_btc.is_none() {
209                                                 println!("ERROR: invalid invoice: must contain amount to pay");
210                                                 print!("> ");
211                                                 io::stdout().flush().unwrap();
212                                                 continue;
213                                         }
214                                         let amt_msat = amt_pico_btc.unwrap() / 10;
215
216                                         let payee_pubkey = invoice.recover_payee_pub_key();
217                                         let final_cltv = *invoice.min_final_cltv_expiry().unwrap_or(&9) as u32;
218
219                                         let mut payment_hash = PaymentHash([0; 32]);
220                                         payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
221
222                                         let payment_secret = match invoice.payment_secret() {
223                                                 Some(secret) => {
224                                                         let mut payment_secret = PaymentSecret([0; 32]);
225                                                         payment_secret.0.copy_from_slice(&secret.0);
226                                                         Some(payment_secret)
227                                                 }
228                                                 None => None,
229                                         };
230
231                                         // rust-lightning-invoice doesn't currently support features, so we parse features
232                                         // manually from the invoice.
233                                         let mut invoice_features = InvoiceFeatures::empty();
234                                         for field in &invoice.into_signed_raw().raw_invoice().data.tagged_fields {
235                                                 match field {
236                                                         lightning_invoice::RawTaggedField::UnknownSemantics(vec) => {
237                                                                 if vec[0] == bech32::u5::try_from_u8(5).unwrap() {
238                                                                         if vec.len() >= 6 && vec[5].to_u8() & 0b10000 != 0 {
239                                                                                 invoice_features =
240                                                                                         invoice_features.set_variable_length_onion_optional();
241                                                                         }
242                                                                         if vec.len() >= 6 && vec[5].to_u8() & 0b01000 != 0 {
243                                                                                 invoice_features =
244                                                                                         invoice_features.set_variable_length_onion_required();
245                                                                         }
246                                                                         if vec.len() >= 4 && vec[3].to_u8() & 0b00001 != 0 {
247                                                                                 invoice_features =
248                                                                                         invoice_features.set_payment_secret_optional();
249                                                                         }
250                                                                         if vec.len() >= 5 && vec[4].to_u8() & 0b10000 != 0 {
251                                                                                 invoice_features =
252                                                                                         invoice_features.set_payment_secret_required();
253                                                                         }
254                                                                         if vec.len() >= 4 && vec[3].to_u8() & 0b00100 != 0 {
255                                                                                 invoice_features =
256                                                                                         invoice_features.set_basic_mpp_optional();
257                                                                         }
258                                                                         if vec.len() >= 4 && vec[3].to_u8() & 0b00010 != 0 {
259                                                                                 invoice_features =
260                                                                                         invoice_features.set_basic_mpp_required();
261                                                                         }
262                                                                 }
263                                                         }
264                                                         _ => {}
265                                                 }
266                                         }
267                                         let invoice_features_opt = match invoice_features == InvoiceFeatures::empty() {
268                                                 true => None,
269                                                 false => Some(invoice_features),
270                                         };
271                                         send_payment(
272                                                 payee_pubkey,
273                                                 amt_msat,
274                                                 final_cltv,
275                                                 payment_hash,
276                                                 payment_secret,
277                                                 invoice_features_opt,
278                                                 route_hints,
279                                                 router.clone(),
280                                                 channel_manager.clone(),
281                                                 payment_storage.clone(),
282                                                 logger.clone(),
283                                         );
284                                 }
285                                 "getinvoice" => {
286                                         let amt_str = words.next();
287                                         if amt_str.is_none() {
288                                                 println!("ERROR: getinvoice requires an amount in millisatoshis");
289                                                 print!("> ");
290                                                 io::stdout().flush().unwrap();
291                                                 continue;
292                                         }
293
294                                         let amt_msat: Result<u64, _> = amt_str.unwrap().parse();
295                                         if amt_msat.is_err() {
296                                                 println!("ERROR: getinvoice provided payment amount was not a number");
297                                                 print!("> ");
298                                                 io::stdout().flush().unwrap();
299                                                 continue;
300                                         }
301                                         get_invoice(
302                                                 amt_msat.unwrap(),
303                                                 payment_storage.clone(),
304                                                 node_privkey.clone(),
305                                                 channel_manager.clone(),
306                                                 network,
307                                         );
308                                 }
309                                 "connectpeer" => {
310                                         let peer_pubkey_and_ip_addr = words.next();
311                                         if peer_pubkey_and_ip_addr.is_none() {
312                                                 println!("ERROR: connectpeer requires peer connection info: `connectpeer pubkey@host:port`");
313                                                 print!("> ");
314                                                 io::stdout().flush().unwrap();
315                                                 continue;
316                                         }
317                                         let (pubkey, peer_addr) =
318                                                 match parse_peer_info(peer_pubkey_and_ip_addr.unwrap().to_string()) {
319                                                         Ok(info) => info,
320                                                         Err(e) => {
321                                                                 println!("{:?}", e.into_inner().unwrap());
322                                                                 print!("> ");
323                                                                 io::stdout().flush().unwrap();
324                                                                 continue;
325                                                         }
326                                                 };
327                                         if connect_peer_if_necessary(
328                                                 pubkey,
329                                                 peer_addr,
330                                                 peer_manager.clone(),
331                                                 event_notifier.clone(),
332                                         )
333                                         .is_ok()
334                                         {
335                                                 println!("SUCCESS: connected to peer {}", pubkey);
336                                         }
337                                 }
338                                 "listchannels" => list_channels(channel_manager.clone()),
339                                 "listpayments" => list_payments(payment_storage.clone()),
340                                 "closechannel" => {
341                                         let channel_id_str = words.next();
342                                         if channel_id_str.is_none() {
343                                                 println!("ERROR: closechannel requires a channel ID: `closechannel <channel_id>`");
344                                                 print!("> ");
345                                                 io::stdout().flush().unwrap();
346                                                 continue;
347                                         }
348                                         let channel_id_vec = hex_utils::to_vec(channel_id_str.unwrap());
349                                         if channel_id_vec.is_none() {
350                                                 println!("ERROR: couldn't parse channel_id as hex");
351                                                 print!("> ");
352                                                 io::stdout().flush().unwrap();
353                                                 continue;
354                                         }
355                                         let mut channel_id = [0; 32];
356                                         channel_id.copy_from_slice(&channel_id_vec.unwrap());
357                                         close_channel(channel_id, channel_manager.clone());
358                                 }
359                                 "forceclosechannel" => {
360                                         let channel_id_str = words.next();
361                                         if channel_id_str.is_none() {
362                                                 println!("ERROR: forceclosechannel requires a channel ID: `forceclosechannel <channel_id>`");
363                                                 print!("> ");
364                                                 io::stdout().flush().unwrap();
365                                                 continue;
366                                         }
367                                         let channel_id_vec = hex_utils::to_vec(channel_id_str.unwrap());
368                                         if channel_id_vec.is_none() {
369                                                 println!("ERROR: couldn't parse channel_id as hex");
370                                                 print!("> ");
371                                                 io::stdout().flush().unwrap();
372                                                 continue;
373                                         }
374                                         let mut channel_id = [0; 32];
375                                         channel_id.copy_from_slice(&channel_id_vec.unwrap());
376                                         force_close_channel(channel_id, channel_manager.clone());
377                                 }
378                                 _ => println!("Unknown command. See `\"help\" for available commands."),
379                         }
380                 }
381                 print!("> ");
382                 io::stdout().flush().unwrap();
383         }
384 }
385
386 fn help() {
387         println!("openchannel pubkey@host:port <channel_amt_satoshis>");
388         println!("sendpayment <invoice>");
389         println!("getinvoice <amt_in_millisatoshis>");
390         println!("connectpeer pubkey@host:port");
391         println!("listchannels");
392         println!("listpayments");
393         println!("closechannel <channel_id>");
394         println!("forceclosechannel <channel_id>");
395 }
396
397 fn list_channels(channel_manager: Arc<ChannelManager>) {
398         print!("[");
399         for chan_info in channel_manager.list_channels() {
400                 println!("");
401                 println!("\t{{");
402                 println!("\t\tchannel_id: {},", hex_utils::hex_str(&chan_info.channel_id[..]));
403                 println!(
404                         "\t\tpeer_pubkey: {},",
405                         hex_utils::hex_str(&chan_info.remote_network_id.serialize())
406                 );
407                 let mut pending_channel = false;
408                 match chan_info.short_channel_id {
409                         Some(id) => println!("\t\tshort_channel_id: {},", id),
410                         None => {
411                                 pending_channel = true;
412                         }
413                 }
414                 println!("\t\tpending_open: {},", pending_channel);
415                 println!("\t\tchannel_value_satoshis: {},", chan_info.channel_value_satoshis);
416                 println!("\t\tchannel_can_send_payments: {},", chan_info.is_live);
417                 println!("\t}},");
418         }
419         println!("]");
420 }
421
422 fn list_payments(payment_storage: PaymentInfoStorage) {
423         let payments = payment_storage.lock().unwrap();
424         print!("[");
425         for (payment_hash, payment_info) in payments.deref() {
426                 println!("");
427                 println!("\t{{");
428                 println!("\t\tamount_millisatoshis: {},", payment_info.amt_msat);
429                 println!("\t\tpayment_hash: {},", hex_utils::hex_str(&payment_hash.0));
430                 // println!("\t\thtlc_direction: {},", direction_str);
431                 println!(
432                         "\t\thtlc_status: {},",
433                         match payment_info.status {
434                                 HTLCStatus::Pending => "pending",
435                                 HTLCStatus::Succeeded => "succeeded",
436                                 HTLCStatus::Failed => "failed",
437                         }
438                 );
439
440                 println!("\t}},");
441         }
442         println!("]");
443 }
444
445 pub(crate) fn connect_peer_if_necessary(
446         pubkey: PublicKey, peer_addr: SocketAddr, peer_manager: Arc<PeerManager>,
447         event_notifier: mpsc::Sender<()>,
448 ) -> Result<(), ()> {
449         for node_pubkey in peer_manager.get_peer_node_ids() {
450                 if node_pubkey == pubkey {
451                         return Ok(());
452                 }
453         }
454         match TcpStream::connect_timeout(&peer_addr, Duration::from_secs(10)) {
455                 Ok(stream) => {
456                         let peer_mgr = peer_manager.clone();
457                         let event_ntfns = event_notifier.clone();
458                         tokio::spawn(async move {
459                                 lightning_net_tokio::setup_outbound(peer_mgr, event_ntfns, pubkey, stream).await;
460                         });
461                         let mut peer_connected = false;
462                         while !peer_connected {
463                                 for node_pubkey in peer_manager.get_peer_node_ids() {
464                                         if node_pubkey == pubkey {
465                                                 peer_connected = true;
466                                         }
467                                 }
468                         }
469                 }
470                 Err(e) => {
471                         println!("ERROR: failed to connect to peer: {:?}", e);
472                         return Err(());
473                 }
474         }
475         Ok(())
476 }
477
478 fn open_channel(
479         peer_pubkey: PublicKey, channel_amt_sat: u64, announce_channel: bool,
480         channel_manager: Arc<ChannelManager>,
481 ) -> Result<(), ()> {
482         let mut config = UserConfig::default();
483         if announce_channel {
484                 config.channel_options.announced_channel = true;
485         }
486         // lnd's max to_self_delay is 2016, so we want to be compatible.
487         config.peer_channel_config_limits.their_to_self_delay = 2016;
488         match channel_manager.create_channel(peer_pubkey, channel_amt_sat, 0, 0, None) {
489                 Ok(_) => {
490                         println!("EVENT: initiated channel with peer {}. ", peer_pubkey);
491                         return Ok(());
492                 }
493                 Err(e) => {
494                         println!("ERROR: failed to open channel: {:?}", e);
495                         return Err(());
496                 }
497         }
498 }
499
500 fn send_payment(
501         payee: PublicKey, amt_msat: u64, final_cltv: u32, payment_hash: PaymentHash,
502         payment_secret: Option<PaymentSecret>, payee_features: Option<InvoiceFeatures>,
503         mut route_hints: Vec<lightning_invoice::Route>,
504         router: Arc<NetGraphMsgHandler<Arc<dyn chain::Access>, Arc<FilesystemLogger>>>,
505         channel_manager: Arc<ChannelManager>, payment_storage: PaymentInfoStorage,
506         logger: Arc<FilesystemLogger>,
507 ) {
508         let network_graph = router.network_graph.read().unwrap();
509         let first_hops = channel_manager.list_usable_channels();
510         let payer_pubkey = channel_manager.get_our_node_id();
511
512         let mut hints: Vec<RouteHint> = Vec::new();
513         for route in route_hints.drain(..) {
514                 let route_hops = route.into_inner();
515                 let last_hop = &route_hops[route_hops.len() - 1];
516                 hints.push(RouteHint {
517                         src_node_id: last_hop.pubkey,
518                         short_channel_id: u64::from_be_bytes(last_hop.short_channel_id),
519                         fees: RoutingFees {
520                                 base_msat: last_hop.fee_base_msat,
521                                 proportional_millionths: last_hop.fee_proportional_millionths,
522                         },
523                         cltv_expiry_delta: last_hop.cltv_expiry_delta,
524                         htlc_minimum_msat: None,
525                         htlc_maximum_msat: None,
526                 })
527         }
528         let route = router::get_route(
529                 &payer_pubkey,
530                 &network_graph,
531                 &payee,
532                 payee_features,
533                 Some(&first_hops.iter().collect::<Vec<_>>()),
534                 &hints.iter().collect::<Vec<_>>(),
535                 amt_msat,
536                 final_cltv,
537                 logger,
538         );
539         if let Err(e) = route {
540                 println!("ERROR: failed to find route: {}", e.err);
541                 return;
542         }
543         let status = match channel_manager.send_payment(&route.unwrap(), payment_hash, &payment_secret)
544         {
545                 Ok(()) => {
546                         println!("EVENT: initiated sending {} msats to {}", amt_msat, payee);
547                         HTLCStatus::Pending
548                 }
549                 Err(e) => {
550                         println!("ERROR: failed to send payment: {:?}", e);
551                         HTLCStatus::Failed
552                 }
553         };
554         let mut payments = payment_storage.lock().unwrap();
555         payments.insert(
556                 payment_hash,
557                 PaymentInfo {
558                         preimage: None,
559                         secret: payment_secret,
560                         status,
561                         amt_msat: MillisatAmount(Some(amt_msat)),
562                 },
563         );
564 }
565
566 fn get_invoice(
567         amt_msat: u64, payment_storage: PaymentInfoStorage, our_node_privkey: SecretKey,
568         channel_manager: Arc<ChannelManager>, network: Network,
569 ) {
570         let mut payments = payment_storage.lock().unwrap();
571         let secp_ctx = Secp256k1::new();
572
573         let mut preimage = [0; 32];
574         rand::thread_rng().fill_bytes(&mut preimage);
575         let payment_hash = Sha256Hash::hash(&preimage);
576
577         let our_node_pubkey = channel_manager.get_our_node_id();
578         let mut invoice = lightning_invoice::InvoiceBuilder::new(match network {
579                 Network::Bitcoin => lightning_invoice::Currency::Bitcoin,
580                 Network::Testnet => lightning_invoice::Currency::BitcoinTestnet,
581                 Network::Regtest => lightning_invoice::Currency::Regtest,
582                 Network::Signet => panic!("Signet invoices not supported"),
583         })
584         .payment_hash(payment_hash)
585         .description("rust-lightning-bitcoinrpc invoice".to_string())
586         .amount_pico_btc(amt_msat * 10)
587         .current_timestamp()
588         .payee_pub_key(our_node_pubkey);
589
590         // Add route hints to the invoice.
591         let our_channels = channel_manager.list_usable_channels();
592         let mut min_final_cltv_expiry = 9;
593         for channel in our_channels {
594                 let short_channel_id = match channel.short_channel_id {
595                         Some(id) => id.to_be_bytes(),
596                         None => continue,
597                 };
598                 let forwarding_info = match channel.counterparty_forwarding_info {
599                         Some(info) => info,
600                         None => continue,
601                 };
602                 if forwarding_info.cltv_expiry_delta > min_final_cltv_expiry {
603                         min_final_cltv_expiry = forwarding_info.cltv_expiry_delta;
604                 }
605                 invoice = invoice.route(vec![lightning_invoice::RouteHop {
606                         pubkey: channel.remote_network_id,
607                         short_channel_id,
608                         fee_base_msat: forwarding_info.fee_base_msat,
609                         fee_proportional_millionths: forwarding_info.fee_proportional_millionths,
610                         cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
611                 }]);
612         }
613         invoice = invoice.min_final_cltv_expiry(min_final_cltv_expiry.into());
614
615         // Sign the invoice.
616         let invoice =
617                 invoice.build_signed(|msg_hash| secp_ctx.sign_recoverable(msg_hash, &our_node_privkey));
618
619         match invoice {
620                 Ok(invoice) => println!("SUCCESS: generated invoice: {}", invoice),
621                 Err(e) => println!("ERROR: failed to create invoice: {:?}", e),
622         }
623
624         payments.insert(
625                 PaymentHash(payment_hash.into_inner()),
626                 PaymentInfo {
627                         preimage: Some(PaymentPreimage(preimage)),
628                         // We can't add payment secrets to invoices until we support features in invoices.
629                         // Otherwise lnd errors with "destination hop doesn't understand payment addresses"
630                         // (for context, lnd calls payment secrets "payment addresses").
631                         secret: None,
632                         status: HTLCStatus::Pending,
633                         amt_msat: MillisatAmount(Some(amt_msat)),
634                 },
635         );
636 }
637
638 fn close_channel(channel_id: [u8; 32], channel_manager: Arc<ChannelManager>) {
639         match channel_manager.close_channel(&channel_id) {
640                 Ok(()) => println!("EVENT: initiating channel close"),
641                 Err(e) => println!("ERROR: failed to close channel: {:?}", e),
642         }
643 }
644
645 fn force_close_channel(channel_id: [u8; 32], channel_manager: Arc<ChannelManager>) {
646         match channel_manager.force_close_channel(&channel_id) {
647                 Ok(()) => println!("EVENT: initiating channel force-close"),
648                 Err(e) => println!("ERROR: failed to force-close channel: {:?}", e),
649         }
650 }
651
652 pub(crate) fn parse_peer_info(
653         peer_pubkey_and_ip_addr: String,
654 ) -> Result<(PublicKey, SocketAddr), std::io::Error> {
655         let mut pubkey_and_addr = peer_pubkey_and_ip_addr.split("@");
656         let pubkey = pubkey_and_addr.next();
657         let peer_addr_str = pubkey_and_addr.next();
658         if peer_addr_str.is_none() || peer_addr_str.is_none() {
659                 return Err(std::io::Error::new(
660                         std::io::ErrorKind::Other,
661                         "ERROR: incorrectly formatted peer
662         info. Should be formatted as: `pubkey@host:port`",
663                 ));
664         }
665
666         let peer_addr: Result<SocketAddr, _> = peer_addr_str.unwrap().parse();
667         if peer_addr.is_err() {
668                 return Err(std::io::Error::new(
669                         std::io::ErrorKind::Other,
670                         "ERROR: couldn't parse pubkey@host:port into a socket address",
671                 ));
672         }
673
674         let pubkey = hex_utils::to_compressed_pubkey(pubkey.unwrap());
675         if pubkey.is_none() {
676                 return Err(std::io::Error::new(
677                         std::io::ErrorKind::Other,
678                         "ERROR: unable to parse given pubkey for node",
679                 ));
680         }
681
682         Ok((pubkey.unwrap(), peer_addr.unwrap()))
683 }