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