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