4 ChannelManager, FilesystemLogger, HTLCStatus, MillisatAmount, PaymentInfo, PaymentInfoStorage,
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;
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;
23 use std::io::{BufRead, Write};
24 use std::net::{SocketAddr, TcpStream};
27 use std::str::FromStr;
29 use std::time::Duration;
30 use tokio::sync::mpsc;
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,
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]`");
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");
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");
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");
65 let bitcoind_rpc_host = bitcoind_rpc_path[0].to_string();
66 let bitcoind_rpc_port = bitcoind_rpc_path[1].parse::<u16>().unwrap();
68 let ldk_storage_dir_path = env::args().skip(2).next().unwrap();
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()) {
73 Some(Err(e)) => panic!(e),
75 ldk_peer_port_set = false;
80 let arg_idx = match ldk_peer_port_set {
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,
91 bitcoind_rpc_username,
92 bitcoind_rpc_password,
96 ldk_peer_listening_port,
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,
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();
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() {
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]");
125 io::stdout().flush().unwrap();
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()) {
133 println!("{:?}", e.into_inner().unwrap());
135 io::stdout().flush().unwrap();
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");
144 io::stdout().flush().unwrap();
148 if connect_peer_if_necessary(
151 peer_manager.clone(),
152 event_notifier.clone(),
157 io::stdout().flush().unwrap();
161 let announce_channel = match words.next() {
162 Some("--public") | Some("--public=true") => true,
163 Some("--public=false") => false,
165 println!("ERROR: invalid `--public` command format. Valid formats: `--public`, `--public=true` `--public=false`");
167 io::stdout().flush().unwrap();
175 chan_amt_sat.unwrap(),
177 channel_manager.clone(),
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,
189 let invoice_str = words.next();
190 if invoice_str.is_none() {
191 println!("ERROR: sendpayment requires an invoice: `sendpayment <invoice>`");
193 io::stdout().flush().unwrap();
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());
201 io::stdout().flush().unwrap();
204 let invoice = invoice_res.unwrap();
205 let route_hints: Vec<lightning_invoice::Route> =
206 invoice.routes().iter().map(|&route| route.clone()).collect();
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");
212 io::stdout().flush().unwrap();
215 let amt_msat = amt_pico_btc.unwrap() / 10;
217 let payee_pubkey = invoice.recover_payee_pub_key();
218 let final_cltv = *invoice.min_final_cltv_expiry().unwrap_or(&9) as u32;
220 let mut payment_hash = PaymentHash([0; 32]);
221 payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
223 let payment_secret = match invoice.payment_secret() {
225 let mut payment_secret = PaymentSecret([0; 32]);
226 payment_secret.0.copy_from_slice(&secret.0);
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 {
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 {
241 invoice_features.set_variable_length_onion_optional();
243 if vec.len() >= 6 && vec[5].to_u8() & 0b01000 != 0 {
245 invoice_features.set_variable_length_onion_required();
247 if vec.len() >= 4 && vec[3].to_u8() & 0b00001 != 0 {
249 invoice_features.set_payment_secret_optional();
251 if vec.len() >= 5 && vec[4].to_u8() & 0b10000 != 0 {
253 invoice_features.set_payment_secret_required();
255 if vec.len() >= 4 && vec[3].to_u8() & 0b00100 != 0 {
257 invoice_features.set_basic_mpp_optional();
259 if vec.len() >= 4 && vec[3].to_u8() & 0b00010 != 0 {
261 invoice_features.set_basic_mpp_required();
268 let invoice_features_opt = match invoice_features == InvoiceFeatures::empty() {
270 false => Some(invoice_features),
278 invoice_features_opt,
281 channel_manager.clone(),
282 outbound_payments.clone(),
287 let amt_str = words.next();
288 if amt_str.is_none() {
289 println!("ERROR: getinvoice requires an amount in millisatoshis");
291 io::stdout().flush().unwrap();
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");
299 io::stdout().flush().unwrap();
304 inbound_payments.clone(),
305 node_privkey.clone(),
306 channel_manager.clone(),
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`");
315 io::stdout().flush().unwrap();
318 let (pubkey, peer_addr) =
319 match parse_peer_info(peer_pubkey_and_ip_addr.unwrap().to_string()) {
322 println!("{:?}", e.into_inner().unwrap());
324 io::stdout().flush().unwrap();
328 if connect_peer_if_necessary(
331 peer_manager.clone(),
332 event_notifier.clone(),
336 println!("SUCCESS: connected to peer {}", pubkey);
339 "listchannels" => list_channels(channel_manager.clone()),
341 list_payments(inbound_payments.clone(), outbound_payments.clone())
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>`");
348 io::stdout().flush().unwrap();
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");
355 io::stdout().flush().unwrap();
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());
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>`");
367 io::stdout().flush().unwrap();
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");
374 io::stdout().flush().unwrap();
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());
381 _ => println!("Unknown command. See `\"help\" for available commands."),
385 io::stdout().flush().unwrap();
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>");
400 fn list_channels(channel_manager: Arc<ChannelManager>) {
402 for chan_info in channel_manager.list_channels() {
405 println!("\t\tchannel_id: {},", hex_utils::hex_str(&chan_info.channel_id[..]));
407 "\t\tpeer_pubkey: {},",
408 hex_utils::hex_str(&chan_info.remote_network_id.serialize())
410 let mut pending_channel = false;
411 match chan_info.short_channel_id {
412 Some(id) => println!("\t\tshort_channel_id: {},", id),
414 pending_channel = true;
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);
425 fn list_payments(inbound_payments: PaymentInfoStorage, outbound_payments: PaymentInfoStorage) {
426 let inbound = inbound_payments.lock().unwrap();
427 let outbound = outbound_payments.lock().unwrap();
429 for (payment_hash, payment_info) in inbound.deref() {
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,");
436 "\t\thtlc_status: {},",
437 match payment_info.status {
438 HTLCStatus::Pending => "pending",
439 HTLCStatus::Succeeded => "succeeded",
440 HTLCStatus::Failed => "failed",
447 for (payment_hash, payment_info) in outbound.deref() {
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,");
454 "\t\thtlc_status: {},",
455 match payment_info.status {
456 HTLCStatus::Pending => "pending",
457 HTLCStatus::Succeeded => "succeeded",
458 HTLCStatus::Failed => "failed",
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 {
476 match TcpStream::connect_timeout(&peer_addr, Duration::from_secs(10)) {
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;
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;
493 println!("ERROR: failed to connect to peer: {:?}", e);
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;
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) {
512 println!("EVENT: initiated channel with peer {}. ", peer_pubkey);
516 println!("ERROR: failed to open channel: {:?}", e);
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>,
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();
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),
542 base_msat: last_hop.fee_base_msat,
543 proportional_millionths: last_hop.fee_proportional_millionths,
545 cltv_expiry_delta: last_hop.cltv_expiry_delta,
546 htlc_minimum_msat: None,
547 htlc_maximum_msat: None,
550 let route = router::get_route(
555 Some(&first_hops.iter().collect::<Vec<_>>()),
556 &hints.iter().collect::<Vec<_>>(),
561 if let Err(e) = route {
562 println!("ERROR: failed to find route: {}", e.err);
565 let status = match channel_manager.send_payment(&route.unwrap(), payment_hash, &payment_secret)
568 println!("EVENT: initiated sending {} msats to {}", amt_msat, payee);
572 println!("ERROR: failed to send payment: {:?}", e);
576 let mut payments = payment_storage.lock().unwrap();
581 secret: payment_secret,
583 amt_msat: MillisatAmount(Some(amt_msat)),
589 amt_msat: u64, payment_storage: PaymentInfoStorage, our_node_privkey: SecretKey,
590 channel_manager: Arc<ChannelManager>, network: Network,
592 let mut payments = payment_storage.lock().unwrap();
593 let secp_ctx = Secp256k1::new();
595 let mut preimage = [0; 32];
596 rand::thread_rng().fill_bytes(&mut preimage);
597 let payment_hash = Sha256Hash::hash(&preimage);
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"),
606 .payment_hash(payment_hash)
607 .description("rust-lightning-bitcoinrpc invoice".to_string())
608 .amount_pico_btc(amt_msat * 10)
610 .payee_pub_key(our_node_pubkey);
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(),
620 let forwarding_info = match channel.counterparty_forwarding_info {
624 if forwarding_info.cltv_expiry_delta > min_final_cltv_expiry {
625 min_final_cltv_expiry = forwarding_info.cltv_expiry_delta;
627 invoice = invoice.route(vec![lightning_invoice::RouteHop {
628 pubkey: channel.remote_network_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,
635 invoice = invoice.min_final_cltv_expiry(min_final_cltv_expiry.into());
639 invoice.build_signed(|msg_hash| secp_ctx.sign_recoverable(msg_hash, &our_node_privkey));
642 Ok(invoice) => println!("SUCCESS: generated invoice: {}", invoice),
643 Err(e) => println!("ERROR: failed to create invoice: {:?}", e),
647 PaymentHash(payment_hash.into_inner()),
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").
654 status: HTLCStatus::Pending,
655 amt_msat: MillisatAmount(Some(amt_msat)),
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),
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),
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`",
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",
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",
704 Ok((pubkey.unwrap(), peer_addr.unwrap()))