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