4 ChannelManager, HTLCStatus, InvoicePayer, MillisatAmount, NetworkGraph, PaymentInfo,
5 PaymentInfoStorage, PeerManager,
7 use bitcoin::hashes::sha256::Hash as Sha256;
8 use bitcoin::hashes::Hash;
9 use bitcoin::network::constants::Network;
10 use bitcoin::secp256k1::PublicKey;
11 use lightning::chain::keysinterface::{KeysInterface, KeysManager, Recipient};
12 use lightning::ln::msgs::NetAddress;
13 use lightning::ln::{PaymentHash, PaymentPreimage};
14 use lightning::routing::gossip::NodeId;
15 use lightning::util::config::{ChannelHandshakeConfig, ChannelHandshakeLimits, UserConfig};
16 use lightning::util::events::EventHandler;
17 use lightning_invoice::payment::PaymentError;
18 use lightning_invoice::{utils, Currency, Invoice};
21 use std::io::{BufRead, Write};
22 use std::net::{IpAddr, SocketAddr, ToSocketAddrs};
25 use std::str::FromStr;
27 use std::time::Duration;
29 pub(crate) struct LdkUserInfo {
30 pub(crate) bitcoind_rpc_username: String,
31 pub(crate) bitcoind_rpc_password: String,
32 pub(crate) bitcoind_rpc_port: u16,
33 pub(crate) bitcoind_rpc_host: String,
34 pub(crate) ldk_storage_dir_path: String,
35 pub(crate) ldk_peer_listening_port: u16,
36 pub(crate) ldk_announced_listen_addr: Vec<NetAddress>,
37 pub(crate) ldk_announced_node_name: [u8; 32],
38 pub(crate) network: Network,
41 pub(crate) fn parse_startup_args() -> Result<LdkUserInfo, ()> {
42 if env::args().len() < 3 {
43 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] [announced-node-name announced-listen-addr*]`");
46 let bitcoind_rpc_info = env::args().skip(1).next().unwrap();
47 let bitcoind_rpc_info_parts: Vec<&str> = bitcoind_rpc_info.rsplitn(2, "@").collect();
48 if bitcoind_rpc_info_parts.len() != 2 {
49 println!("ERROR: bad bitcoind RPC URL provided");
52 let rpc_user_and_password: Vec<&str> = bitcoind_rpc_info_parts[1].split(":").collect();
53 if rpc_user_and_password.len() != 2 {
54 println!("ERROR: bad bitcoind RPC username/password combo provided");
57 let bitcoind_rpc_username = rpc_user_and_password[0].to_string();
58 let bitcoind_rpc_password = rpc_user_and_password[1].to_string();
59 let bitcoind_rpc_path: Vec<&str> = bitcoind_rpc_info_parts[0].split(":").collect();
60 if bitcoind_rpc_path.len() != 2 {
61 println!("ERROR: bad bitcoind RPC path provided");
64 let bitcoind_rpc_host = bitcoind_rpc_path[0].to_string();
65 let bitcoind_rpc_port = bitcoind_rpc_path[1].parse::<u16>().unwrap();
67 let ldk_storage_dir_path = env::args().skip(2).next().unwrap();
69 let mut ldk_peer_port_set = true;
70 let ldk_peer_listening_port: u16 = match env::args().skip(3).next().map(|p| p.parse()) {
73 ldk_peer_port_set = false;
77 ldk_peer_port_set = false;
82 let mut arg_idx = match ldk_peer_port_set {
86 let network: Network = match env::args().skip(arg_idx).next().as_ref().map(String::as_str) {
87 Some("testnet") => Network::Testnet,
88 Some("regtest") => Network::Regtest,
89 Some("signet") => Network::Signet,
91 panic!("Unsupported network provided. Options are: `regtest`, `testnet`, and `signet`. Got {}", net);
93 None => Network::Testnet,
96 let ldk_announced_node_name = match env::args().skip(arg_idx + 1).next().as_ref() {
99 panic!("Node Alias can not be longer than 32 bytes");
102 let mut bytes = [0; 32];
103 bytes[..s.len()].copy_from_slice(s.as_bytes());
109 let mut ldk_announced_listen_addr = Vec::new();
111 match env::args().skip(arg_idx + 1).next().as_ref() {
112 Some(s) => match IpAddr::from_str(s) {
113 Ok(IpAddr::V4(a)) => {
114 ldk_announced_listen_addr
115 .push(NetAddress::IPv4 { addr: a.octets(), port: ldk_peer_listening_port });
118 Ok(IpAddr::V6(a)) => {
119 ldk_announced_listen_addr
120 .push(NetAddress::IPv6 { addr: a.octets(), port: ldk_peer_listening_port });
123 Err(_) => panic!("Failed to parse announced-listen-addr into an IP address"),
130 bitcoind_rpc_username,
131 bitcoind_rpc_password,
134 ldk_storage_dir_path,
135 ldk_peer_listening_port,
136 ldk_announced_listen_addr,
137 ldk_announced_node_name,
142 pub(crate) async fn poll_for_user_input<E: EventHandler>(
143 invoice_payer: Arc<InvoicePayer<E>>, peer_manager: Arc<PeerManager>,
144 channel_manager: Arc<ChannelManager>, keys_manager: Arc<KeysManager>,
145 network_graph: Arc<NetworkGraph>, inbound_payments: PaymentInfoStorage,
146 outbound_payments: PaymentInfoStorage, ldk_data_dir: String, network: Network,
148 println!("LDK startup successful. To view available commands: \"help\".");
149 println!("LDK logs are available at <your-supplied-ldk-data-dir-path>/.ldk/logs");
150 println!("Local Node ID is {}.", channel_manager.get_our_node_id());
151 let stdin = io::stdin();
152 let mut line_reader = stdin.lock().lines();
155 io::stdout().flush().unwrap(); // Without flushing, the `>` doesn't print
156 let line = match line_reader.next() {
157 Some(l) => l.unwrap(),
160 let mut words = line.split_whitespace();
161 if let Some(word) = words.next() {
165 let peer_pubkey_and_ip_addr = words.next();
166 let channel_value_sat = words.next();
167 if peer_pubkey_and_ip_addr.is_none() || channel_value_sat.is_none() {
168 println!("ERROR: openchannel has 2 required arguments: `openchannel pubkey@host:port channel_amt_satoshis` [--public]");
171 let peer_pubkey_and_ip_addr = peer_pubkey_and_ip_addr.unwrap();
172 let (pubkey, peer_addr) =
173 match parse_peer_info(peer_pubkey_and_ip_addr.to_string()) {
176 println!("{:?}", e.into_inner().unwrap());
181 let chan_amt_sat: Result<u64, _> = channel_value_sat.unwrap().parse();
182 if chan_amt_sat.is_err() {
183 println!("ERROR: channel amount must be a number");
187 if connect_peer_if_necessary(pubkey, peer_addr, peer_manager.clone())
194 let announce_channel = match words.next() {
195 Some("--public") | Some("--public=true") => true,
196 Some("--public=false") => false,
198 println!("ERROR: invalid `--public` command format. Valid formats: `--public`, `--public=true` `--public=false`");
206 chan_amt_sat.unwrap(),
208 channel_manager.clone(),
212 let peer_data_path = format!("{}/channel_peer_data", ldk_data_dir.clone());
213 let _ = disk::persist_channel_peer(
214 Path::new(&peer_data_path),
215 peer_pubkey_and_ip_addr,
220 let invoice_str = words.next();
221 if invoice_str.is_none() {
222 println!("ERROR: sendpayment requires an invoice: `sendpayment <invoice>`");
226 let invoice = match Invoice::from_str(invoice_str.unwrap()) {
229 println!("ERROR: invalid invoice: {:?}", e);
234 send_payment(&*invoice_payer, &invoice, outbound_payments.clone());
237 let dest_pubkey = match words.next() {
238 Some(dest) => match hex_utils::to_compressed_pubkey(dest) {
241 println!("ERROR: couldn't parse destination pubkey");
246 println!("ERROR: keysend requires a destination pubkey: `keysend <dest_pubkey> <amt_msat>`");
250 let amt_msat_str = match words.next() {
253 println!("ERROR: keysend requires an amount in millisatoshis: `keysend <dest_pubkey> <amt_msat>`");
257 let amt_msat: u64 = match amt_msat_str.parse() {
260 println!("ERROR: couldn't parse amount_msat: {}", e);
269 outbound_payments.clone(),
273 let amt_str = words.next();
274 if amt_str.is_none() {
275 println!("ERROR: getinvoice requires an amount in millisatoshis");
279 let amt_msat: Result<u64, _> = amt_str.unwrap().parse();
280 if amt_msat.is_err() {
281 println!("ERROR: getinvoice provided payment amount was not a number");
285 let expiry_secs_str = words.next();
286 if expiry_secs_str.is_none() {
287 println!("ERROR: getinvoice requires an expiry in seconds");
291 let expiry_secs: Result<u32, _> = expiry_secs_str.unwrap().parse();
292 if expiry_secs.is_err() {
293 println!("ERROR: getinvoice provided expiry was not a number");
299 inbound_payments.clone(),
300 channel_manager.clone(),
301 keys_manager.clone(),
303 expiry_secs.unwrap(),
307 let peer_pubkey_and_ip_addr = words.next();
308 if peer_pubkey_and_ip_addr.is_none() {
309 println!("ERROR: connectpeer requires peer connection info: `connectpeer pubkey@host:port`");
312 let (pubkey, peer_addr) =
313 match parse_peer_info(peer_pubkey_and_ip_addr.unwrap().to_string()) {
316 println!("{:?}", e.into_inner().unwrap());
320 if connect_peer_if_necessary(pubkey, peer_addr, peer_manager.clone())
324 println!("SUCCESS: connected to peer {}", pubkey);
327 "listchannels" => list_channels(&channel_manager, &network_graph),
329 list_payments(inbound_payments.clone(), outbound_payments.clone())
332 let channel_id_str = words.next();
333 if channel_id_str.is_none() {
334 println!("ERROR: closechannel requires a channel ID: `closechannel <channel_id> <peer_pubkey>`");
337 let channel_id_vec = hex_utils::to_vec(channel_id_str.unwrap());
338 if channel_id_vec.is_none() || channel_id_vec.as_ref().unwrap().len() != 32 {
339 println!("ERROR: couldn't parse channel_id");
342 let mut channel_id = [0; 32];
343 channel_id.copy_from_slice(&channel_id_vec.unwrap());
345 let peer_pubkey_str = words.next();
346 if peer_pubkey_str.is_none() {
347 println!("ERROR: closechannel requires a peer pubkey: `closechannel <channel_id> <peer_pubkey>`");
350 let peer_pubkey_vec = match hex_utils::to_vec(peer_pubkey_str.unwrap()) {
351 Some(peer_pubkey_vec) => peer_pubkey_vec,
353 println!("ERROR: couldn't parse peer_pubkey");
357 let peer_pubkey = match PublicKey::from_slice(&peer_pubkey_vec) {
358 Ok(peer_pubkey) => peer_pubkey,
360 println!("ERROR: couldn't parse peer_pubkey");
365 close_channel(channel_id, peer_pubkey, channel_manager.clone());
367 "forceclosechannel" => {
368 let channel_id_str = words.next();
369 if channel_id_str.is_none() {
370 println!("ERROR: forceclosechannel requires a channel ID: `forceclosechannel <channel_id> <peer_pubkey>`");
373 let channel_id_vec = hex_utils::to_vec(channel_id_str.unwrap());
374 if channel_id_vec.is_none() || channel_id_vec.as_ref().unwrap().len() != 32 {
375 println!("ERROR: couldn't parse channel_id");
378 let mut channel_id = [0; 32];
379 channel_id.copy_from_slice(&channel_id_vec.unwrap());
381 let peer_pubkey_str = words.next();
382 if peer_pubkey_str.is_none() {
383 println!("ERROR: forceclosechannel requires a peer pubkey: `forceclosechannel <channel_id> <peer_pubkey>`");
386 let peer_pubkey_vec = match hex_utils::to_vec(peer_pubkey_str.unwrap()) {
387 Some(peer_pubkey_vec) => peer_pubkey_vec,
389 println!("ERROR: couldn't parse peer_pubkey");
393 let peer_pubkey = match PublicKey::from_slice(&peer_pubkey_vec) {
394 Ok(peer_pubkey) => peer_pubkey,
396 println!("ERROR: couldn't parse peer_pubkey");
401 force_close_channel(channel_id, peer_pubkey, channel_manager.clone());
403 "nodeinfo" => node_info(&channel_manager, &peer_manager),
404 "listpeers" => list_peers(peer_manager.clone()),
406 const MSG_STARTPOS: usize = "signmessage".len() + 1;
407 if line.as_bytes().len() <= MSG_STARTPOS {
408 println!("ERROR: signmsg requires a message");
413 lightning::util::message_signing::sign(
414 &line.as_bytes()[MSG_STARTPOS..],
415 &keys_manager.get_node_secret(Recipient::Node).unwrap()
419 _ => println!("Unknown command. See `\"help\" for available commands."),
426 println!("openchannel pubkey@host:port <amt_satoshis>");
427 println!("sendpayment <invoice>");
428 println!("keysend <dest_pubkey> <amt_msats>");
429 println!("getinvoice <amt_msats> <expiry_secs>");
430 println!("connectpeer pubkey@host:port");
431 println!("listchannels");
432 println!("listpayments");
433 println!("closechannel <channel_id> <peer_pubkey>");
434 println!("forceclosechannel <channel_id> <peer_pubkey>");
435 println!("nodeinfo");
436 println!("listpeers");
437 println!("signmessage <message>");
440 fn node_info(channel_manager: &Arc<ChannelManager>, peer_manager: &Arc<PeerManager>) {
442 println!("\t\t node_pubkey: {}", channel_manager.get_our_node_id());
443 let chans = channel_manager.list_channels();
444 println!("\t\t num_channels: {}", chans.len());
445 println!("\t\t num_usable_channels: {}", chans.iter().filter(|c| c.is_usable).count());
446 let local_balance_msat = chans.iter().map(|c| c.balance_msat).sum::<u64>();
447 println!("\t\t local_balance_msat: {}", local_balance_msat);
448 println!("\t\t num_peers: {}", peer_manager.get_peer_node_ids().len());
452 fn list_peers(peer_manager: Arc<PeerManager>) {
454 for pubkey in peer_manager.get_peer_node_ids() {
455 println!("\t\t pubkey: {}", pubkey);
460 fn list_channels(channel_manager: &Arc<ChannelManager>, network_graph: &Arc<NetworkGraph>) {
462 for chan_info in channel_manager.list_channels() {
465 println!("\t\tchannel_id: {},", hex_utils::hex_str(&chan_info.channel_id[..]));
466 if let Some(funding_txo) = chan_info.funding_txo {
467 println!("\t\tfunding_txid: {},", funding_txo.txid);
471 "\t\tpeer_pubkey: {},",
472 hex_utils::hex_str(&chan_info.counterparty.node_id.serialize())
474 if let Some(node_info) = network_graph
477 .get(&NodeId::from_pubkey(&chan_info.counterparty.node_id))
479 if let Some(announcement) = &node_info.announcement_info {
480 println!("\t\tpeer_alias: {}", announcement.alias);
484 if let Some(id) = chan_info.short_channel_id {
485 println!("\t\tshort_channel_id: {},", id);
487 println!("\t\tis_channel_ready: {},", chan_info.is_channel_ready);
488 println!("\t\tchannel_value_satoshis: {},", chan_info.channel_value_satoshis);
489 println!("\t\tlocal_balance_msat: {},", chan_info.balance_msat);
490 if chan_info.is_usable {
491 println!("\t\tavailable_balance_for_send_msat: {},", chan_info.outbound_capacity_msat);
492 println!("\t\tavailable_balance_for_recv_msat: {},", chan_info.inbound_capacity_msat);
494 println!("\t\tchannel_can_send_payments: {},", chan_info.is_usable);
495 println!("\t\tpublic: {},", chan_info.is_public);
501 fn list_payments(inbound_payments: PaymentInfoStorage, outbound_payments: PaymentInfoStorage) {
502 let inbound = inbound_payments.lock().unwrap();
503 let outbound = outbound_payments.lock().unwrap();
505 for (payment_hash, payment_info) in inbound.deref() {
508 println!("\t\tamount_millisatoshis: {},", payment_info.amt_msat);
509 println!("\t\tpayment_hash: {},", hex_utils::hex_str(&payment_hash.0));
510 println!("\t\thtlc_direction: inbound,");
512 "\t\thtlc_status: {},",
513 match payment_info.status {
514 HTLCStatus::Pending => "pending",
515 HTLCStatus::Succeeded => "succeeded",
516 HTLCStatus::Failed => "failed",
523 for (payment_hash, payment_info) in outbound.deref() {
526 println!("\t\tamount_millisatoshis: {},", payment_info.amt_msat);
527 println!("\t\tpayment_hash: {},", hex_utils::hex_str(&payment_hash.0));
528 println!("\t\thtlc_direction: outbound,");
530 "\t\thtlc_status: {},",
531 match payment_info.status {
532 HTLCStatus::Pending => "pending",
533 HTLCStatus::Succeeded => "succeeded",
534 HTLCStatus::Failed => "failed",
543 pub(crate) async fn connect_peer_if_necessary(
544 pubkey: PublicKey, peer_addr: SocketAddr, peer_manager: Arc<PeerManager>,
545 ) -> Result<(), ()> {
546 for node_pubkey in peer_manager.get_peer_node_ids() {
547 if node_pubkey == pubkey {
551 let res = do_connect_peer(pubkey, peer_addr, peer_manager).await;
553 println!("ERROR: failed to connect to peer");
558 pub(crate) async fn do_connect_peer(
559 pubkey: PublicKey, peer_addr: SocketAddr, peer_manager: Arc<PeerManager>,
560 ) -> Result<(), ()> {
561 match lightning_net_tokio::connect_outbound(Arc::clone(&peer_manager), pubkey, peer_addr).await
563 Some(connection_closed_future) => {
564 let mut connection_closed_future = Box::pin(connection_closed_future);
566 match futures::poll!(&mut connection_closed_future) {
567 std::task::Poll::Ready(_) => {
570 std::task::Poll::Pending => {}
572 // Avoid blocking the tokio context by sleeping a bit
573 match peer_manager.get_peer_node_ids().iter().find(|id| **id == pubkey) {
574 Some(_) => return Ok(()),
575 None => tokio::time::sleep(Duration::from_millis(10)).await,
584 peer_pubkey: PublicKey, channel_amt_sat: u64, announced_channel: bool,
585 channel_manager: Arc<ChannelManager>,
586 ) -> Result<(), ()> {
587 let config = UserConfig {
588 channel_handshake_limits: ChannelHandshakeLimits {
589 // lnd's max to_self_delay is 2016, so we want to be compatible.
590 their_to_self_delay: 2016,
593 channel_handshake_config: ChannelHandshakeConfig {
600 match channel_manager.create_channel(peer_pubkey, channel_amt_sat, 0, 0, Some(config)) {
602 println!("EVENT: initiated channel with peer {}. ", peer_pubkey);
606 println!("ERROR: failed to open channel: {:?}", e);
612 fn send_payment<E: EventHandler>(
613 invoice_payer: &InvoicePayer<E>, invoice: &Invoice, payment_storage: PaymentInfoStorage,
615 let status = match invoice_payer.pay_invoice(invoice) {
617 let payee_pubkey = invoice.recover_payee_pub_key();
618 let amt_msat = invoice.amount_milli_satoshis().unwrap();
619 println!("EVENT: initiated sending {} msats to {}", amt_msat, payee_pubkey);
623 Err(PaymentError::Invoice(e)) => {
624 println!("ERROR: invalid invoice: {}", e);
628 Err(PaymentError::Routing(e)) => {
629 println!("ERROR: failed to find route: {}", e.err);
633 Err(PaymentError::Sending(e)) => {
634 println!("ERROR: failed to send payment: {:?}", e);
639 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
640 let payment_secret = Some(invoice.payment_secret().clone());
642 let mut payments = payment_storage.lock().unwrap();
647 secret: payment_secret,
649 amt_msat: MillisatAmount(invoice.amount_milli_satoshis()),
654 fn keysend<E: EventHandler, K: KeysInterface>(
655 invoice_payer: &InvoicePayer<E>, payee_pubkey: PublicKey, amt_msat: u64, keys: &K,
656 payment_storage: PaymentInfoStorage,
658 let payment_preimage = keys.get_secure_random_bytes();
660 let status = match invoice_payer.pay_pubkey(
662 PaymentPreimage(payment_preimage),
667 println!("EVENT: initiated sending {} msats to {}", amt_msat, payee_pubkey);
671 Err(PaymentError::Invoice(e)) => {
672 println!("ERROR: invalid payee: {}", e);
676 Err(PaymentError::Routing(e)) => {
677 println!("ERROR: failed to find route: {}", e.err);
681 Err(PaymentError::Sending(e)) => {
682 println!("ERROR: failed to send payment: {:?}", e);
688 let mut payments = payment_storage.lock().unwrap();
690 PaymentHash(Sha256::hash(&payment_preimage).into_inner()),
695 amt_msat: MillisatAmount(Some(amt_msat)),
701 amt_msat: u64, payment_storage: PaymentInfoStorage, channel_manager: Arc<ChannelManager>,
702 keys_manager: Arc<KeysManager>, network: Network, expiry_secs: u32,
704 let mut payments = payment_storage.lock().unwrap();
705 let currency = match network {
706 Network::Bitcoin => Currency::Bitcoin,
707 Network::Testnet => Currency::BitcoinTestnet,
708 Network::Regtest => Currency::Regtest,
709 Network::Signet => Currency::Signet,
711 let invoice = match utils::create_invoice_from_channelmanager(
716 "ldk-tutorial-node".to_string(),
720 println!("SUCCESS: generated invoice: {}", inv);
724 println!("ERROR: failed to create invoice: {:?}", e);
729 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
734 secret: Some(invoice.payment_secret().clone()),
735 status: HTLCStatus::Pending,
736 amt_msat: MillisatAmount(Some(amt_msat)),
742 channel_id: [u8; 32], counterparty_node_id: PublicKey, channel_manager: Arc<ChannelManager>,
744 match channel_manager.close_channel(&channel_id, &counterparty_node_id) {
745 Ok(()) => println!("EVENT: initiating channel close"),
746 Err(e) => println!("ERROR: failed to close channel: {:?}", e),
750 fn force_close_channel(
751 channel_id: [u8; 32], counterparty_node_id: PublicKey, channel_manager: Arc<ChannelManager>,
753 match channel_manager.force_close_broadcasting_latest_txn(&channel_id, &counterparty_node_id) {
754 Ok(()) => println!("EVENT: initiating channel force-close"),
755 Err(e) => println!("ERROR: failed to force-close channel: {:?}", e),
759 pub(crate) fn parse_peer_info(
760 peer_pubkey_and_ip_addr: String,
761 ) -> Result<(PublicKey, SocketAddr), std::io::Error> {
762 let mut pubkey_and_addr = peer_pubkey_and_ip_addr.split("@");
763 let pubkey = pubkey_and_addr.next();
764 let peer_addr_str = pubkey_and_addr.next();
765 if peer_addr_str.is_none() || peer_addr_str.is_none() {
766 return Err(std::io::Error::new(
767 std::io::ErrorKind::Other,
768 "ERROR: incorrectly formatted peer info. Should be formatted as: `pubkey@host:port`",
772 let peer_addr = peer_addr_str.unwrap().to_socket_addrs().map(|mut r| r.next());
773 if peer_addr.is_err() || peer_addr.as_ref().unwrap().is_none() {
774 return Err(std::io::Error::new(
775 std::io::ErrorKind::Other,
776 "ERROR: couldn't parse pubkey@host:port into a socket address",
780 let pubkey = hex_utils::to_compressed_pubkey(pubkey.unwrap());
781 if pubkey.is_none() {
782 return Err(std::io::Error::new(
783 std::io::ErrorKind::Other,
784 "ERROR: unable to parse given pubkey for node",
788 Ok((pubkey.unwrap(), peer_addr.unwrap().unwrap()))