Remove redundant `is_none()` check
[ldk-sample] / src / cli.rs
index 34987a8bc4f3e32ad10182fe89923dde627527f9..5863ed0144430dda1fbe18231b7cbe70b0a988b6 100644 (file)
@@ -1,30 +1,30 @@
 use crate::disk;
 use crate::hex_utils;
 use crate::{
-       ChannelManager, FilesystemLogger, HTLCStatus, MillisatAmount, PaymentInfo, PaymentInfoStorage,
-       PeerManager,
+       ChannelManager, HTLCStatus, InvoicePayer, MillisatAmount, NetworkGraph, PaymentInfo,
+       PaymentInfoStorage, PeerManager,
 };
+use bitcoin::hashes::sha256::Hash as Sha256;
+use bitcoin::hashes::Hash;
 use bitcoin::network::constants::Network;
-use bitcoin::secp256k1::key::PublicKey;
-use lightning::chain;
-use lightning::chain::keysinterface::KeysManager;
-use lightning::ln::features::InvoiceFeatures;
-use lightning::ln::{PaymentHash, PaymentSecret};
-use lightning::routing::network_graph::NetGraphMsgHandler;
-use lightning::routing::router;
-use lightning::routing::router::RouteHintHop;
-use lightning::util::config::UserConfig;
+use bitcoin::secp256k1::PublicKey;
+use lightning::chain::keysinterface::{KeysInterface, KeysManager, Recipient};
+use lightning::ln::msgs::NetAddress;
+use lightning::ln::{PaymentHash, PaymentPreimage};
+use lightning::routing::gossip::NodeId;
+use lightning::util::config::{ChannelHandshakeConfig, ChannelHandshakeLimits, UserConfig};
+use lightning::util::events::EventHandler;
+use lightning_invoice::payment::PaymentError;
 use lightning_invoice::{utils, Currency, Invoice};
 use std::env;
 use std::io;
 use std::io::{BufRead, Write};
-use std::net::{SocketAddr, ToSocketAddrs};
+use std::net::{IpAddr, SocketAddr, ToSocketAddrs};
 use std::ops::Deref;
 use std::path::Path;
 use std::str::FromStr;
 use std::sync::Arc;
 use std::time::Duration;
-use tokio::sync::mpsc;
 
 pub(crate) struct LdkUserInfo {
        pub(crate) bitcoind_rpc_username: String,
@@ -33,28 +33,30 @@ pub(crate) struct LdkUserInfo {
        pub(crate) bitcoind_rpc_host: String,
        pub(crate) ldk_storage_dir_path: String,
        pub(crate) ldk_peer_listening_port: u16,
+       pub(crate) ldk_announced_listen_addr: Vec<NetAddress>,
+       pub(crate) ldk_announced_node_name: [u8; 32],
        pub(crate) network: Network,
 }
 
 pub(crate) fn parse_startup_args() -> Result<LdkUserInfo, ()> {
        if env::args().len() < 3 {
-               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]`");
+               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*]`");
                return Err(());
        }
        let bitcoind_rpc_info = env::args().skip(1).next().unwrap();
-       let bitcoind_rpc_info_parts: Vec<&str> = bitcoind_rpc_info.split("@").collect();
+       let bitcoind_rpc_info_parts: Vec<&str> = bitcoind_rpc_info.rsplitn(2, "@").collect();
        if bitcoind_rpc_info_parts.len() != 2 {
                println!("ERROR: bad bitcoind RPC URL provided");
                return Err(());
        }
-       let rpc_user_and_password: Vec<&str> = bitcoind_rpc_info_parts[0].split(":").collect();
+       let rpc_user_and_password: Vec<&str> = bitcoind_rpc_info_parts[1].split(":").collect();
        if rpc_user_and_password.len() != 2 {
                println!("ERROR: bad bitcoind RPC username/password combo provided");
                return Err(());
        }
        let bitcoind_rpc_username = rpc_user_and_password[0].to_string();
        let bitcoind_rpc_password = rpc_user_and_password[1].to_string();
-       let bitcoind_rpc_path: Vec<&str> = bitcoind_rpc_info_parts[1].split(":").collect();
+       let bitcoind_rpc_path: Vec<&str> = bitcoind_rpc_info_parts[0].split(":").collect();
        if bitcoind_rpc_path.len() != 2 {
                println!("ERROR: bad bitcoind RPC path provided");
                return Err(());
@@ -67,23 +69,63 @@ pub(crate) fn parse_startup_args() -> Result<LdkUserInfo, ()> {
        let mut ldk_peer_port_set = true;
        let ldk_peer_listening_port: u16 = match env::args().skip(3).next().map(|p| p.parse()) {
                Some(Ok(p)) => p,
-               Some(Err(e)) => panic!("{}", e),
+               Some(Err(_)) => {
+                       ldk_peer_port_set = false;
+                       9735
+               }
                None => {
                        ldk_peer_port_set = false;
                        9735
                }
        };
 
-       let arg_idx = match ldk_peer_port_set {
+       let mut arg_idx = match ldk_peer_port_set {
                true => 4,
                false => 3,
        };
        let network: Network = match env::args().skip(arg_idx).next().as_ref().map(String::as_str) {
                Some("testnet") => Network::Testnet,
                Some("regtest") => Network::Regtest,
-               Some(_) => panic!("Unsupported network provided. Options are: `regtest`, `testnet`"),
+               Some("signet") => Network::Signet,
+               Some(net) => {
+                       panic!("Unsupported network provided. Options are: `regtest`, `testnet`, and `signet`. Got {}", net);
+               }
                None => Network::Testnet,
        };
+
+       let ldk_announced_node_name = match env::args().skip(arg_idx + 1).next().as_ref() {
+               Some(s) => {
+                       if s.len() > 32 {
+                               panic!("Node Alias can not be longer than 32 bytes");
+                       }
+                       arg_idx += 1;
+                       let mut bytes = [0; 32];
+                       bytes[..s.len()].copy_from_slice(s.as_bytes());
+                       bytes
+               }
+               None => [0; 32],
+       };
+
+       let mut ldk_announced_listen_addr = Vec::new();
+       loop {
+               match env::args().skip(arg_idx + 1).next().as_ref() {
+                       Some(s) => match IpAddr::from_str(s) {
+                               Ok(IpAddr::V4(a)) => {
+                                       ldk_announced_listen_addr
+                                               .push(NetAddress::IPv4 { addr: a.octets(), port: ldk_peer_listening_port });
+                                       arg_idx += 1;
+                               }
+                               Ok(IpAddr::V6(a)) => {
+                                       ldk_announced_listen_addr
+                                               .push(NetAddress::IPv6 { addr: a.octets(), port: ldk_peer_listening_port });
+                                       arg_idx += 1;
+                               }
+                               Err(_) => panic!("Failed to parse announced-listen-addr into an IP address"),
+                       },
+                       None => break,
+               }
+       }
+
        Ok(LdkUserInfo {
                bitcoind_rpc_username,
                bitcoind_rpc_password,
@@ -91,27 +133,30 @@ pub(crate) fn parse_startup_args() -> Result<LdkUserInfo, ()> {
                bitcoind_rpc_port,
                ldk_storage_dir_path,
                ldk_peer_listening_port,
+               ldk_announced_listen_addr,
+               ldk_announced_node_name,
                network,
        })
 }
 
-pub(crate) async fn poll_for_user_input(
-       peer_manager: Arc<PeerManager>, channel_manager: Arc<ChannelManager>,
-       keys_manager: Arc<KeysManager>,
-       router: Arc<NetGraphMsgHandler<Arc<dyn chain::Access + Send + Sync>, Arc<FilesystemLogger>>>,
-       inbound_payments: PaymentInfoStorage, outbound_payments: PaymentInfoStorage,
-       event_notifier: mpsc::Sender<()>, ldk_data_dir: String, logger: Arc<FilesystemLogger>,
-       network: Network,
+pub(crate) async fn poll_for_user_input<E: EventHandler>(
+       invoice_payer: Arc<InvoicePayer<E>>, peer_manager: Arc<PeerManager>,
+       channel_manager: Arc<ChannelManager>, keys_manager: Arc<KeysManager>,
+       network_graph: Arc<NetworkGraph>, inbound_payments: PaymentInfoStorage,
+       outbound_payments: PaymentInfoStorage, ldk_data_dir: String, network: Network,
 ) {
        println!("LDK startup successful. To view available commands: \"help\".");
        println!("LDK logs are available at <your-supplied-ldk-data-dir-path>/.ldk/logs");
        println!("Local Node ID is {}.", channel_manager.get_our_node_id());
        let stdin = io::stdin();
-       print!("> ");
-       io::stdout().flush().unwrap(); // Without flushing, the `>` doesn't print
-       for line in stdin.lock().lines() {
-               let _ = event_notifier.try_send(());
-               let line = line.unwrap();
+       let mut line_reader = stdin.lock().lines();
+       loop {
+               print!("> ");
+               io::stdout().flush().unwrap(); // Without flushing, the `>` doesn't print
+               let line = match line_reader.next() {
+                       Some(l) => l.unwrap(),
+                       None => break,
+               };
                let mut words = line.split_whitespace();
                if let Some(word) = words.next() {
                        match word {
@@ -121,8 +166,6 @@ pub(crate) async fn poll_for_user_input(
                                        let channel_value_sat = words.next();
                                        if peer_pubkey_and_ip_addr.is_none() || channel_value_sat.is_none() {
                                                println!("ERROR: openchannel has 2 required arguments: `openchannel pubkey@host:port channel_amt_satoshis` [--public]");
-                                               print!("> ");
-                                               io::stdout().flush().unwrap();
                                                continue;
                                        }
                                        let peer_pubkey_and_ip_addr = peer_pubkey_and_ip_addr.unwrap();
@@ -131,8 +174,6 @@ pub(crate) async fn poll_for_user_input(
                                                        Ok(info) => info,
                                                        Err(e) => {
                                                                println!("{:?}", e.into_inner().unwrap());
-                                                               print!("> ");
-                                                               io::stdout().flush().unwrap();
                                                                continue;
                                                        }
                                                };
@@ -140,22 +181,13 @@ pub(crate) async fn poll_for_user_input(
                                        let chan_amt_sat: Result<u64, _> = channel_value_sat.unwrap().parse();
                                        if chan_amt_sat.is_err() {
                                                println!("ERROR: channel amount must be a number");
-                                               print!("> ");
-                                               io::stdout().flush().unwrap();
                                                continue;
                                        }
 
-                                       if connect_peer_if_necessary(
-                                               pubkey,
-                                               peer_addr,
-                                               peer_manager.clone(),
-                                               event_notifier.clone(),
-                                       )
-                                       .await
-                                       .is_err()
+                                       if connect_peer_if_necessary(pubkey, peer_addr, peer_manager.clone())
+                                               .await
+                                               .is_err()
                                        {
-                                               print!("> ");
-                                               io::stdout().flush().unwrap();
                                                continue;
                                        };
 
@@ -164,8 +196,6 @@ pub(crate) async fn poll_for_user_input(
                                                Some("--public=false") => false,
                                                Some(_) => {
                                                        println!("ERROR: invalid `--public` command format. Valid formats: `--public`, `--public=true` `--public=false`");
-                                                       print!("> ");
-                                                       io::stdout().flush().unwrap();
                                                        continue;
                                                }
                                                None => false,
@@ -190,8 +220,6 @@ pub(crate) async fn poll_for_user_input(
                                        let invoice_str = words.next();
                                        if invoice_str.is_none() {
                                                println!("ERROR: sendpayment requires an invoice: `sendpayment <invoice>`");
-                                               print!("> ");
-                                               io::stdout().flush().unwrap();
                                                continue;
                                        }
 
@@ -199,90 +227,86 @@ pub(crate) async fn poll_for_user_input(
                                                Ok(inv) => inv,
                                                Err(e) => {
                                                        println!("ERROR: invalid invoice: {:?}", e);
-                                                       print!("> ");
-                                                       io::stdout().flush().unwrap();
                                                        continue;
                                                }
                                        };
-                                       let mut route_hints = invoice.routes().clone();
-                                       let mut last_hops = Vec::new();
-                                       for hint in route_hints.drain(..) {
-                                               last_hops.push(hint[hint.len() - 1].clone());
-                                       }
-
-                                       let amt_pico_btc = invoice.amount_pico_btc();
-                                       if amt_pico_btc.is_none() {
-                                               println!("ERROR: invalid invoice: must contain amount to pay");
-                                               print!("> ");
-                                               io::stdout().flush().unwrap();
-                                               continue;
-                                       }
-                                       let amt_msat = amt_pico_btc.unwrap() / 10;
-
-                                       let payee_pubkey = invoice.recover_payee_pub_key();
-                                       let final_cltv = invoice.min_final_cltv_expiry() as u32;
 
-                                       let mut payment_hash = PaymentHash([0; 32]);
-                                       payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
-
-                                       let payment_secret = match invoice.payment_secret() {
-                                               Some(secret) => {
-                                                       let mut payment_secret = PaymentSecret([0; 32]);
-                                                       payment_secret.0.copy_from_slice(&secret.0);
-                                                       Some(payment_secret)
+                                       send_payment(&*invoice_payer, &invoice, outbound_payments.clone());
+                               }
+                               "keysend" => {
+                                       let dest_pubkey = match words.next() {
+                                               Some(dest) => match hex_utils::to_compressed_pubkey(dest) {
+                                                       Some(pk) => pk,
+                                                       None => {
+                                                               println!("ERROR: couldn't parse destination pubkey");
+                                                               continue;
+                                                       }
+                                               },
+                                               None => {
+                                                       println!("ERROR: keysend requires a destination pubkey: `keysend <dest_pubkey> <amt_msat>`");
+                                                       continue;
                                                }
-                                               None => None,
                                        };
-
-                                       let invoice_features = match invoice.features() {
-                                               Some(feat) => Some(feat.clone()),
-                                               None => None,
+                                       let amt_msat_str = match words.next() {
+                                               Some(amt) => amt,
+                                               None => {
+                                                       println!("ERROR: keysend requires an amount in millisatoshis: `keysend <dest_pubkey> <amt_msat>`");
+                                                       continue;
+                                               }
                                        };
-
-                                       send_payment(
-                                               payee_pubkey,
+                                       let amt_msat: u64 = match amt_msat_str.parse() {
+                                               Ok(amt) => amt,
+                                               Err(e) => {
+                                                       println!("ERROR: couldn't parse amount_msat: {}", e);
+                                                       continue;
+                                               }
+                                       };
+                                       keysend(
+                                               &*invoice_payer,
+                                               dest_pubkey,
                                                amt_msat,
-                                               final_cltv,
-                                               payment_hash,
-                                               payment_secret,
-                                               invoice_features,
-                                               last_hops,
-                                               router.clone(),
-                                               channel_manager.clone(),
+                                               &*keys_manager,
                                                outbound_payments.clone(),
-                                               logger.clone(),
                                        );
                                }
                                "getinvoice" => {
                                        let amt_str = words.next();
                                        if amt_str.is_none() {
                                                println!("ERROR: getinvoice requires an amount in millisatoshis");
-                                               print!("> ");
-                                               io::stdout().flush().unwrap();
                                                continue;
                                        }
 
                                        let amt_msat: Result<u64, _> = amt_str.unwrap().parse();
                                        if amt_msat.is_err() {
                                                println!("ERROR: getinvoice provided payment amount was not a number");
-                                               print!("> ");
-                                               io::stdout().flush().unwrap();
                                                continue;
                                        }
+
+                                       let expiry_secs_str = words.next();
+                                       if expiry_secs_str.is_none() {
+                                               println!("ERROR: getinvoice requires an expiry in seconds");
+                                               continue;
+                                       }
+
+                                       let expiry_secs: Result<u32, _> = expiry_secs_str.unwrap().parse();
+                                       if expiry_secs.is_err() {
+                                               println!("ERROR: getinvoice provided expiry was not a number");
+                                               continue;
+                                       }
+
                                        get_invoice(
                                                amt_msat.unwrap(),
                                                inbound_payments.clone(),
                                                channel_manager.clone(),
                                                keys_manager.clone(),
                                                network,
+                                               expiry_secs.unwrap(),
                                        );
                                }
                                "connectpeer" => {
                                        let peer_pubkey_and_ip_addr = words.next();
                                        if peer_pubkey_and_ip_addr.is_none() {
                                                println!("ERROR: connectpeer requires peer connection info: `connectpeer pubkey@host:port`");
-                                               print!("> ");
-                                               io::stdout().flush().unwrap();
                                                continue;
                                        }
                                        let (pubkey, peer_addr) =
@@ -290,91 +314,137 @@ pub(crate) async fn poll_for_user_input(
                                                        Ok(info) => info,
                                                        Err(e) => {
                                                                println!("{:?}", e.into_inner().unwrap());
-                                                               print!("> ");
-                                                               io::stdout().flush().unwrap();
                                                                continue;
                                                        }
                                                };
-                                       if connect_peer_if_necessary(
-                                               pubkey,
-                                               peer_addr,
-                                               peer_manager.clone(),
-                                               event_notifier.clone(),
-                                       )
-                                       .await
-                                       .is_ok()
+                                       if connect_peer_if_necessary(pubkey, peer_addr, peer_manager.clone())
+                                               .await
+                                               .is_ok()
                                        {
                                                println!("SUCCESS: connected to peer {}", pubkey);
                                        }
                                }
-                               "listchannels" => list_channels(channel_manager.clone()),
+                               "listchannels" => list_channels(&channel_manager, &network_graph),
                                "listpayments" => {
                                        list_payments(inbound_payments.clone(), outbound_payments.clone())
                                }
                                "closechannel" => {
                                        let channel_id_str = words.next();
                                        if channel_id_str.is_none() {
-                                               println!("ERROR: closechannel requires a channel ID: `closechannel <channel_id>`");
-                                               print!("> ");
-                                               io::stdout().flush().unwrap();
+                                               println!("ERROR: closechannel requires a channel ID: `closechannel <channel_id> <peer_pubkey>`");
                                                continue;
                                        }
                                        let channel_id_vec = hex_utils::to_vec(channel_id_str.unwrap());
-                                       if channel_id_vec.is_none() {
-                                               println!("ERROR: couldn't parse channel_id as hex");
-                                               print!("> ");
-                                               io::stdout().flush().unwrap();
+                                       if channel_id_vec.is_none() || channel_id_vec.as_ref().unwrap().len() != 32 {
+                                               println!("ERROR: couldn't parse channel_id");
                                                continue;
                                        }
                                        let mut channel_id = [0; 32];
                                        channel_id.copy_from_slice(&channel_id_vec.unwrap());
-                                       close_channel(channel_id, channel_manager.clone());
+
+                                       let peer_pubkey_str = words.next();
+                                       if peer_pubkey_str.is_none() {
+                                               println!("ERROR: closechannel requires a peer pubkey: `closechannel <channel_id> <peer_pubkey>`");
+                                               continue;
+                                       }
+                                       let peer_pubkey_vec = match hex_utils::to_vec(peer_pubkey_str.unwrap()) {
+                                               Some(peer_pubkey_vec) => peer_pubkey_vec,
+                                               None => {
+                                                       println!("ERROR: couldn't parse peer_pubkey");
+                                                       continue;
+                                               }
+                                       };
+                                       let peer_pubkey = match PublicKey::from_slice(&peer_pubkey_vec) {
+                                               Ok(peer_pubkey) => peer_pubkey,
+                                               Err(_) => {
+                                                       println!("ERROR: couldn't parse peer_pubkey");
+                                                       continue;
+                                               }
+                                       };
+
+                                       close_channel(channel_id, peer_pubkey, channel_manager.clone());
                                }
                                "forceclosechannel" => {
                                        let channel_id_str = words.next();
                                        if channel_id_str.is_none() {
-                                               println!("ERROR: forceclosechannel requires a channel ID: `forceclosechannel <channel_id>`");
-                                               print!("> ");
-                                               io::stdout().flush().unwrap();
+                                               println!("ERROR: forceclosechannel requires a channel ID: `forceclosechannel <channel_id> <peer_pubkey>`");
                                                continue;
                                        }
                                        let channel_id_vec = hex_utils::to_vec(channel_id_str.unwrap());
-                                       if channel_id_vec.is_none() {
-                                               println!("ERROR: couldn't parse channel_id as hex");
-                                               print!("> ");
-                                               io::stdout().flush().unwrap();
+                                       if channel_id_vec.is_none() || channel_id_vec.as_ref().unwrap().len() != 32 {
+                                               println!("ERROR: couldn't parse channel_id");
                                                continue;
                                        }
                                        let mut channel_id = [0; 32];
                                        channel_id.copy_from_slice(&channel_id_vec.unwrap());
-                                       force_close_channel(channel_id, channel_manager.clone());
+
+                                       let peer_pubkey_str = words.next();
+                                       if peer_pubkey_str.is_none() {
+                                               println!("ERROR: forceclosechannel requires a peer pubkey: `forceclosechannel <channel_id> <peer_pubkey>`");
+                                               continue;
+                                       }
+                                       let peer_pubkey_vec = match hex_utils::to_vec(peer_pubkey_str.unwrap()) {
+                                               Some(peer_pubkey_vec) => peer_pubkey_vec,
+                                               None => {
+                                                       println!("ERROR: couldn't parse peer_pubkey");
+                                                       continue;
+                                               }
+                                       };
+                                       let peer_pubkey = match PublicKey::from_slice(&peer_pubkey_vec) {
+                                               Ok(peer_pubkey) => peer_pubkey,
+                                               Err(_) => {
+                                                       println!("ERROR: couldn't parse peer_pubkey");
+                                                       continue;
+                                               }
+                                       };
+
+                                       force_close_channel(channel_id, peer_pubkey, channel_manager.clone());
                                }
-                               "nodeinfo" => node_info(channel_manager.clone(), peer_manager.clone()),
+                               "nodeinfo" => node_info(&channel_manager, &peer_manager),
                                "listpeers" => list_peers(peer_manager.clone()),
+                               "signmessage" => {
+                                       const MSG_STARTPOS: usize = "signmessage".len() + 1;
+                                       if line.as_bytes().len() <= MSG_STARTPOS {
+                                               println!("ERROR: signmsg requires a message");
+                                               continue;
+                                       }
+                                       println!(
+                                               "{:?}",
+                                               lightning::util::message_signing::sign(
+                                                       &line.as_bytes()[MSG_STARTPOS..],
+                                                       &keys_manager.get_node_secret(Recipient::Node).unwrap()
+                                               )
+                                       );
+                               }
                                _ => println!("Unknown command. See `\"help\" for available commands."),
                        }
                }
-               print!("> ");
-               io::stdout().flush().unwrap();
        }
 }
 
 fn help() {
-       println!("openchannel pubkey@host:port <channel_amt_satoshis>");
+       println!("openchannel pubkey@host:port <amt_satoshis> [--public]");
        println!("sendpayment <invoice>");
-       println!("getinvoice <amt_in_millisatoshis>");
+       println!("keysend <dest_pubkey> <amt_msats>");
+       println!("getinvoice <amt_msats> <expiry_secs>");
        println!("connectpeer pubkey@host:port");
        println!("listchannels");
        println!("listpayments");
-       println!("closechannel <channel_id>");
-       println!("forceclosechannel <channel_id>");
+       println!("closechannel <channel_id> <peer_pubkey>");
+       println!("forceclosechannel <channel_id> <peer_pubkey>");
+       println!("nodeinfo");
+       println!("listpeers");
+       println!("signmessage <message>");
 }
 
-fn node_info(channel_manager: Arc<ChannelManager>, peer_manager: Arc<PeerManager>) {
+fn node_info(channel_manager: &Arc<ChannelManager>, peer_manager: &Arc<PeerManager>) {
        println!("\t{{");
        println!("\t\t node_pubkey: {}", channel_manager.get_our_node_id());
-       println!("\t\t num_channels: {}", channel_manager.list_channels().len());
-       println!("\t\t num_usable_channels: {}", channel_manager.list_usable_channels().len());
+       let chans = channel_manager.list_channels();
+       println!("\t\t num_channels: {}", chans.len());
+       println!("\t\t num_usable_channels: {}", chans.iter().filter(|c| c.is_usable).count());
+       let local_balance_msat = chans.iter().map(|c| c.balance_msat).sum::<u64>();
+       println!("\t\t local_balance_msat: {}", local_balance_msat);
        println!("\t\t num_peers: {}", peer_manager.get_peer_node_ids().len());
        println!("\t}},");
 }
@@ -387,26 +457,42 @@ fn list_peers(peer_manager: Arc<PeerManager>) {
        println!("\t}},");
 }
 
-fn list_channels(channel_manager: Arc<ChannelManager>) {
+fn list_channels(channel_manager: &Arc<ChannelManager>, network_graph: &Arc<NetworkGraph>) {
        print!("[");
        for chan_info in channel_manager.list_channels() {
                println!("");
                println!("\t{{");
                println!("\t\tchannel_id: {},", hex_utils::hex_str(&chan_info.channel_id[..]));
+               if let Some(funding_txo) = chan_info.funding_txo {
+                       println!("\t\tfunding_txid: {},", funding_txo.txid);
+               }
+
                println!(
                        "\t\tpeer_pubkey: {},",
-                       hex_utils::hex_str(&chan_info.remote_network_id.serialize())
+                       hex_utils::hex_str(&chan_info.counterparty.node_id.serialize())
                );
-               let mut pending_channel = false;
-               match chan_info.short_channel_id {
-                       Some(id) => println!("\t\tshort_channel_id: {},", id),
-                       None => {
-                               pending_channel = true;
+               if let Some(node_info) = network_graph
+                       .read_only()
+                       .nodes()
+                       .get(&NodeId::from_pubkey(&chan_info.counterparty.node_id))
+               {
+                       if let Some(announcement) = &node_info.announcement_info {
+                               println!("\t\tpeer_alias: {}", announcement.alias);
                        }
                }
-               println!("\t\tpending_open: {},", pending_channel);
+
+               if let Some(id) = chan_info.short_channel_id {
+                       println!("\t\tshort_channel_id: {},", id);
+               }
+               println!("\t\tis_channel_ready: {},", chan_info.is_channel_ready);
                println!("\t\tchannel_value_satoshis: {},", chan_info.channel_value_satoshis);
+               println!("\t\tlocal_balance_msat: {},", chan_info.balance_msat);
+               if chan_info.is_usable {
+                       println!("\t\tavailable_balance_for_send_msat: {},", chan_info.outbound_capacity_msat);
+                       println!("\t\tavailable_balance_for_recv_msat: {},", chan_info.inbound_capacity_msat);
+               }
                println!("\t\tchannel_can_send_payments: {},", chan_info.is_usable);
+               println!("\t\tpublic: {},", chan_info.is_public);
                println!("\t}},");
        }
        println!("]");
@@ -456,60 +542,62 @@ fn list_payments(inbound_payments: PaymentInfoStorage, outbound_payments: Paymen
 
 pub(crate) async fn connect_peer_if_necessary(
        pubkey: PublicKey, peer_addr: SocketAddr, peer_manager: Arc<PeerManager>,
-       event_notifier: mpsc::Sender<()>,
 ) -> Result<(), ()> {
        for node_pubkey in peer_manager.get_peer_node_ids() {
                if node_pubkey == pubkey {
                        return Ok(());
                }
        }
-       match lightning_net_tokio::connect_outbound(
-               Arc::clone(&peer_manager),
-               event_notifier,
-               pubkey,
-               peer_addr,
-       )
-       .await
+       let res = do_connect_peer(pubkey, peer_addr, peer_manager).await;
+       if res.is_err() {
+               println!("ERROR: failed to connect to peer");
+       }
+       res
+}
+
+pub(crate) async fn do_connect_peer(
+       pubkey: PublicKey, peer_addr: SocketAddr, peer_manager: Arc<PeerManager>,
+) -> Result<(), ()> {
+       match lightning_net_tokio::connect_outbound(Arc::clone(&peer_manager), pubkey, peer_addr).await
        {
-               Some(conn_closed_fut) => {
-                       let mut closed_fut_box = Box::pin(conn_closed_fut);
-                       let mut peer_connected = false;
-                       while !peer_connected {
-                               match futures::poll!(&mut closed_fut_box) {
+               Some(connection_closed_future) => {
+                       let mut connection_closed_future = Box::pin(connection_closed_future);
+                       loop {
+                               match futures::poll!(&mut connection_closed_future) {
                                        std::task::Poll::Ready(_) => {
-                                               println!("ERROR: Peer disconnected before we finished the handshake");
                                                return Err(());
                                        }
                                        std::task::Poll::Pending => {}
                                }
-                               for node_pubkey in peer_manager.get_peer_node_ids() {
-                                       if node_pubkey == pubkey {
-                                               peer_connected = true;
-                                       }
-                               }
                                // Avoid blocking the tokio context by sleeping a bit
-                               tokio::time::sleep(Duration::from_millis(10)).await;
+                               match peer_manager.get_peer_node_ids().iter().find(|id| **id == pubkey) {
+                                       Some(_) => return Ok(()),
+                                       None => tokio::time::sleep(Duration::from_millis(10)).await,
+                               }
                        }
                }
-               None => {
-                       println!("ERROR: failed to connect to peer");
-                       return Err(());
-               }
+               None => Err(()),
        }
-       Ok(())
 }
 
 fn open_channel(
-       peer_pubkey: PublicKey, channel_amt_sat: u64, announce_channel: bool,
+       peer_pubkey: PublicKey, channel_amt_sat: u64, announced_channel: bool,
        channel_manager: Arc<ChannelManager>,
 ) -> Result<(), ()> {
-       let mut config = UserConfig::default();
-       if announce_channel {
-               config.channel_options.announced_channel = true;
-       }
-       // lnd's max to_self_delay is 2016, so we want to be compatible.
-       config.peer_channel_config_limits.their_to_self_delay = 2016;
-       match channel_manager.create_channel(peer_pubkey, channel_amt_sat, 0, 0, None) {
+       let config = UserConfig {
+               channel_handshake_limits: ChannelHandshakeLimits {
+                       // lnd's max to_self_delay is 2016, so we want to be compatible.
+                       their_to_self_delay: 2016,
+                       ..Default::default()
+               },
+               channel_handshake_config: ChannelHandshakeConfig {
+                       announced_channel,
+                       ..Default::default()
+               },
+               ..Default::default()
+       };
+
+       match channel_manager.create_channel(peer_pubkey, channel_amt_sat, 0, 0, Some(config)) {
                Ok(_) => {
                        println!("EVENT: initiated channel with peer {}. ", peer_pubkey);
                        return Ok(());
@@ -521,44 +609,36 @@ fn open_channel(
        }
 }
 
-fn send_payment(
-       payee: PublicKey, amt_msat: u64, final_cltv: u32, payment_hash: PaymentHash,
-       payment_secret: Option<PaymentSecret>, payee_features: Option<InvoiceFeatures>,
-       route_hints: Vec<RouteHintHop>,
-       router: Arc<NetGraphMsgHandler<Arc<dyn chain::Access + Send + Sync>, Arc<FilesystemLogger>>>,
-       channel_manager: Arc<ChannelManager>, payment_storage: PaymentInfoStorage,
-       logger: Arc<FilesystemLogger>,
+fn send_payment<E: EventHandler>(
+       invoice_payer: &InvoicePayer<E>, invoice: &Invoice, payment_storage: PaymentInfoStorage,
 ) {
-       let network_graph = router.network_graph.read().unwrap();
-       let first_hops = channel_manager.list_usable_channels();
-       let payer_pubkey = channel_manager.get_our_node_id();
-
-       let route = router::get_route(
-               &payer_pubkey,
-               &network_graph,
-               &payee,
-               payee_features,
-               Some(&first_hops.iter().collect::<Vec<_>>()),
-               &route_hints.iter().collect::<Vec<_>>(),
-               amt_msat,
-               final_cltv,
-               logger,
-       );
-       if let Err(e) = route {
-               println!("ERROR: failed to find route: {}", e.err);
-               return;
-       }
-       let status = match channel_manager.send_payment(&route.unwrap(), payment_hash, &payment_secret)
-       {
-               Ok(()) => {
-                       println!("EVENT: initiated sending {} msats to {}", amt_msat, payee);
+       let status = match invoice_payer.pay_invoice(invoice) {
+               Ok(_payment_id) => {
+                       let payee_pubkey = invoice.recover_payee_pub_key();
+                       let amt_msat = invoice.amount_milli_satoshis().unwrap();
+                       println!("EVENT: initiated sending {} msats to {}", amt_msat, payee_pubkey);
+                       print!("> ");
                        HTLCStatus::Pending
                }
-               Err(e) => {
+               Err(PaymentError::Invoice(e)) => {
+                       println!("ERROR: invalid invoice: {}", e);
+                       print!("> ");
+                       return;
+               }
+               Err(PaymentError::Routing(e)) => {
+                       println!("ERROR: failed to find route: {}", e.err);
+                       print!("> ");
+                       return;
+               }
+               Err(PaymentError::Sending(e)) => {
                        println!("ERROR: failed to send payment: {:?}", e);
+                       print!("> ");
                        HTLCStatus::Failed
                }
        };
+       let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
+       let payment_secret = Some(invoice.payment_secret().clone());
+
        let mut payments = payment_storage.lock().unwrap();
        payments.insert(
                payment_hash,
@@ -566,6 +646,52 @@ fn send_payment(
                        preimage: None,
                        secret: payment_secret,
                        status,
+                       amt_msat: MillisatAmount(invoice.amount_milli_satoshis()),
+               },
+       );
+}
+
+fn keysend<E: EventHandler, K: KeysInterface>(
+       invoice_payer: &InvoicePayer<E>, payee_pubkey: PublicKey, amt_msat: u64, keys: &K,
+       payment_storage: PaymentInfoStorage,
+) {
+       let payment_preimage = keys.get_secure_random_bytes();
+
+       let status = match invoice_payer.pay_pubkey(
+               payee_pubkey,
+               PaymentPreimage(payment_preimage),
+               amt_msat,
+               40,
+       ) {
+               Ok(_payment_id) => {
+                       println!("EVENT: initiated sending {} msats to {}", amt_msat, payee_pubkey);
+                       print!("> ");
+                       HTLCStatus::Pending
+               }
+               Err(PaymentError::Invoice(e)) => {
+                       println!("ERROR: invalid payee: {}", e);
+                       print!("> ");
+                       return;
+               }
+               Err(PaymentError::Routing(e)) => {
+                       println!("ERROR: failed to find route: {}", e.err);
+                       print!("> ");
+                       return;
+               }
+               Err(PaymentError::Sending(e)) => {
+                       println!("ERROR: failed to send payment: {:?}", e);
+                       print!("> ");
+                       HTLCStatus::Failed
+               }
+       };
+
+       let mut payments = payment_storage.lock().unwrap();
+       payments.insert(
+               PaymentHash(Sha256::hash(&payment_preimage).into_inner()),
+               PaymentInfo {
+                       preimage: None,
+                       secret: None,
+                       status,
                        amt_msat: MillisatAmount(Some(amt_msat)),
                },
        );
@@ -573,14 +699,14 @@ fn send_payment(
 
 fn get_invoice(
        amt_msat: u64, payment_storage: PaymentInfoStorage, channel_manager: Arc<ChannelManager>,
-       keys_manager: Arc<KeysManager>, network: Network,
+       keys_manager: Arc<KeysManager>, network: Network, expiry_secs: u32,
 ) {
        let mut payments = payment_storage.lock().unwrap();
        let currency = match network {
                Network::Bitcoin => Currency::Bitcoin,
                Network::Testnet => Currency::BitcoinTestnet,
                Network::Regtest => Currency::Regtest,
-               Network::Signet => panic!("Signet unsupported"),
+               Network::Signet => Currency::Signet,
        };
        let invoice = match utils::create_invoice_from_channelmanager(
                &channel_manager,
@@ -588,6 +714,7 @@ fn get_invoice(
                currency,
                Some(amt_msat),
                "ldk-tutorial-node".to_string(),
+               expiry_secs,
        ) {
                Ok(inv) => {
                        println!("SUCCESS: generated invoice: {}", inv);
@@ -599,31 +726,31 @@ fn get_invoice(
                }
        };
 
-       let mut payment_hash = PaymentHash([0; 32]);
-       payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
+       let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
        payments.insert(
                payment_hash,
                PaymentInfo {
                        preimage: None,
-                       // We can't add payment secrets to invoices until we support features in invoices.
-                       // Otherwise lnd errors with "destination hop doesn't understand payment addresses"
-                       // (for context, lnd calls payment secrets "payment addresses").
-                       secret: Some(invoice.payment_secret().unwrap().clone()),
+                       secret: Some(invoice.payment_secret().clone()),
                        status: HTLCStatus::Pending,
                        amt_msat: MillisatAmount(Some(amt_msat)),
                },
        );
 }
 
-fn close_channel(channel_id: [u8; 32], channel_manager: Arc<ChannelManager>) {
-       match channel_manager.close_channel(&channel_id) {
+fn close_channel(
+       channel_id: [u8; 32], counterparty_node_id: PublicKey, channel_manager: Arc<ChannelManager>,
+) {
+       match channel_manager.close_channel(&channel_id, &counterparty_node_id) {
                Ok(()) => println!("EVENT: initiating channel close"),
                Err(e) => println!("ERROR: failed to close channel: {:?}", e),
        }
 }
 
-fn force_close_channel(channel_id: [u8; 32], channel_manager: Arc<ChannelManager>) {
-       match channel_manager.force_close_channel(&channel_id) {
+fn force_close_channel(
+       channel_id: [u8; 32], counterparty_node_id: PublicKey, channel_manager: Arc<ChannelManager>,
+) {
+       match channel_manager.force_close_broadcasting_latest_txn(&channel_id, &counterparty_node_id) {
                Ok(()) => println!("EVENT: initiating channel force-close"),
                Err(e) => println!("ERROR: failed to force-close channel: {:?}", e),
        }
@@ -635,11 +762,10 @@ pub(crate) fn parse_peer_info(
        let mut pubkey_and_addr = peer_pubkey_and_ip_addr.split("@");
        let pubkey = pubkey_and_addr.next();
        let peer_addr_str = pubkey_and_addr.next();
-       if peer_addr_str.is_none() || peer_addr_str.is_none() {
+       if peer_addr_str.is_none() {
                return Err(std::io::Error::new(
                        std::io::ErrorKind::Other,
-                       "ERROR: incorrectly formatted peer
-               info. Should be formatted as: `pubkey@host:port`",
+                       "ERROR: incorrectly formatted peer info. Should be formatted as: `pubkey@host:port`",
                ));
        }