Keysend support
[ldk-sample] / src / cli.rs
index ca1b84fed66fbe6f64f3cf4d63ddc141c0978ace..f8597e33a19439b94c4c7516bce42671fe8eda81 100644 (file)
@@ -1,33 +1,31 @@
 use crate::disk;
 use crate::hex_utils;
 use crate::{
-       ChannelManager, FilesystemLogger, HTLCDirection, HTLCStatus, PaymentInfoStorage, PeerManager,
-       SatoshiAmount,
+       ChannelManager, FilesystemLogger, HTLCStatus, MillisatAmount, PaymentInfo, PaymentInfoStorage,
+       PeerManager,
 };
-use bitcoin::hashes::sha256::Hash as Sha256Hash;
 use bitcoin::hashes::Hash;
 use bitcoin::network::constants::Network;
-use bitcoin::secp256k1::key::{PublicKey, SecretKey};
-use bitcoin::secp256k1::Secp256k1;
+use bitcoin::secp256k1::key::PublicKey;
 use lightning::chain;
-use lightning::ln::channelmanager::{PaymentHash, PaymentPreimage, PaymentSecret};
+use lightning::chain::keysinterface::KeysManager;
 use lightning::ln::features::InvoiceFeatures;
+use lightning::ln::msgs::NetAddress;
+use lightning::ln::{PaymentHash, PaymentSecret};
 use lightning::routing::network_graph::NetGraphMsgHandler;
 use lightning::routing::router;
-use lightning::util::config::UserConfig;
-use rand;
-use rand::Rng;
+use lightning::routing::router::RouteHint;
+use lightning::util::config::{ChannelConfig, ChannelHandshakeLimits, UserConfig};
+use lightning_invoice::{utils, Currency, Invoice};
 use std::env;
 use std::io;
 use std::io::{BufRead, Write};
-use std::net::{SocketAddr, TcpStream};
+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::runtime::Handle;
-use tokio::sync::mpsc;
 
 pub(crate) struct LdkUserInfo {
        pub(crate) bitcoind_rpc_username: String,
@@ -36,12 +34,14 @@ 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() < 4 {
-               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]`");
+       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] [announced-node-name announced-listen-addr*]`");
                return Err(());
        }
        let bitcoind_rpc_info = env::args().skip(1).next().unwrap();
@@ -70,14 +70,14 @@ 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(e)) => panic!("{}", e),
                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,
        };
@@ -87,6 +87,40 @@ pub(crate) fn parse_startup_args() -> Result<LdkUserInfo, ()> {
                Some(_) => panic!("Unsupported network provided. Options are: `regtest`, `testnet`"),
                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,
@@ -94,22 +128,26 @@ 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) fn poll_for_user_input(
+pub(crate) async fn poll_for_user_input(
        peer_manager: Arc<PeerManager>, channel_manager: Arc<ChannelManager>,
-       router: Arc<NetGraphMsgHandler<Arc<dyn chain::Access>, Arc<FilesystemLogger>>>,
-       payment_storage: PaymentInfoStorage, node_privkey: SecretKey, event_notifier: mpsc::Sender<()>,
-       ldk_data_dir: String, logger: Arc<FilesystemLogger>, runtime_handle: Handle, network: Network,
+       keys_manager: Arc<KeysManager>,
+       router: Arc<NetGraphMsgHandler<Arc<dyn chain::Access + Send + Sync>, Arc<FilesystemLogger>>>,
+       inbound_payments: PaymentInfoStorage, outbound_payments: PaymentInfoStorage,
+       ldk_data_dir: String, logger: Arc<FilesystemLogger>, network: Network,
 ) {
-       println!("LDK startup successful. To view available commands: \"help\".\nLDK logs are available at <your-supplied-ldk-data-dir-path>/.ldk/logs");
+       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 words = line.split_whitespace();
                if let Some(word) = words.next() {
@@ -144,21 +182,15 @@ pub(crate) fn poll_for_user_input(
                                                continue;
                                        }
 
-                                       if connect_peer_if_necessary(
-                                               pubkey,
-                                               peer_addr,
-                                               peer_manager.clone(),
-                                               event_notifier.clone(),
-                                               runtime_handle.clone(),
-                                       )
-                                       .is_err()
+                                       if connect_peer_if_necessary(pubkey, peer_addr, peer_manager.clone())
+                                               .await
+                                               .is_err()
                                        {
                                                print!("> ");
                                                io::stdout().flush().unwrap();
                                                continue;
                                        };
 
-                                       // let private_channel = match words.next().as_ref().map(String::as_str) {
                                        let announce_channel = match words.next() {
                                                Some("--public") | Some("--public=true") => true,
                                                Some("--public=false") => false,
@@ -195,14 +227,16 @@ pub(crate) fn poll_for_user_input(
                                                continue;
                                        }
 
-                                       let invoice_res = lightning_invoice::Invoice::from_str(invoice_str.unwrap());
-                                       if invoice_res.is_err() {
-                                               println!("ERROR: invalid invoice: {:?}", invoice_res.unwrap_err());
-                                               print!("> ");
-                                               io::stdout().flush().unwrap();
-                                               continue;
-                                       }
-                                       let invoice = invoice_res.unwrap();
+                                       let invoice = match Invoice::from_str(invoice_str.unwrap()) {
+                                               Ok(inv) => inv,
+                                               Err(e) => {
+                                                       println!("ERROR: invalid invoice: {:?}", e);
+                                                       print!("> ");
+                                                       io::stdout().flush().unwrap();
+                                                       continue;
+                                               }
+                                       };
+                                       let last_hops = invoice.route_hints();
 
                                        let amt_pico_btc = invoice.amount_pico_btc();
                                        if amt_pico_btc.is_none() {
@@ -214,94 +248,92 @@ pub(crate) fn poll_for_user_input(
                                        let amt_msat = amt_pico_btc.unwrap() / 10;
 
                                        let payee_pubkey = invoice.recover_payee_pub_key();
-                                       let final_cltv = *invoice.min_final_cltv_expiry().unwrap_or(&9) as u32;
-
-                                       let mut payment_hash = PaymentHash([0; 32]);
-                                       payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
+                                       let final_cltv = invoice.min_final_cltv_expiry() as u32;
+                                       let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
+                                       let payment_secret = invoice.payment_secret().cloned();
+                                       let invoice_features = invoice.features().cloned();
 
-                                       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)
-                                               }
-                                               None => None,
-                                       };
-
-                                       // rust-lightning-invoice doesn't currently support features, so we parse features
-                                       // manually from the invoice.
-                                       let mut invoice_features = InvoiceFeatures::empty();
-                                       for field in &invoice.into_signed_raw().raw_invoice().data.tagged_fields {
-                                               match field {
-                                                       lightning_invoice::RawTaggedField::UnknownSemantics(vec) => {
-                                                               if vec[0] == bech32::u5::try_from_u8(5).unwrap() {
-                                                                       if vec.len() >= 6 && vec[5].to_u8() & 0b10000 != 0 {
-                                                                               invoice_features =
-                                                                                       invoice_features.set_variable_length_onion_optional();
-                                                                       }
-                                                                       if vec.len() >= 6 && vec[5].to_u8() & 0b01000 != 0 {
-                                                                               invoice_features =
-                                                                                       invoice_features.set_variable_length_onion_required();
-                                                                       }
-                                                                       if vec.len() >= 4 && vec[3].to_u8() & 0b00001 != 0 {
-                                                                               invoice_features =
-                                                                                       invoice_features.set_payment_secret_optional();
-                                                                       }
-                                                                       if vec.len() >= 5 && vec[4].to_u8() & 0b10000 != 0 {
-                                                                               invoice_features =
-                                                                                       invoice_features.set_payment_secret_required();
-                                                                       }
-                                                                       if vec.len() >= 4 && vec[3].to_u8() & 0b00100 != 0 {
-                                                                               invoice_features =
-                                                                                       invoice_features.set_basic_mpp_optional();
-                                                                       }
-                                                                       if vec.len() >= 4 && vec[3].to_u8() & 0b00010 != 0 {
-                                                                               invoice_features =
-                                                                                       invoice_features.set_basic_mpp_required();
-                                                                       }
-                                                               }
-                                                       }
-                                                       _ => {}
-                                               }
-                                       }
-                                       let invoice_features_opt = match invoice_features == InvoiceFeatures::empty() {
-                                               true => None,
-                                               false => Some(invoice_features),
-                                       };
                                        send_payment(
                                                payee_pubkey,
                                                amt_msat,
                                                final_cltv,
                                                payment_hash,
                                                payment_secret,
-                                               invoice_features_opt,
+                                               invoice_features,
+                                               last_hops,
+                                               router.clone(),
+                                               channel_manager.clone(),
+                                               outbound_payments.clone(),
+                                               logger.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");
+                                                               print!("> ");
+                                                               io::stdout().flush().unwrap();
+                                                               continue;
+                                                       }
+                                               },
+                                               None => {
+                                                       println!("ERROR: keysend requires a destination pubkey: `keysend <dest_pubkey> <amt_msat>`");
+                                                       print!("> ");
+                                                       io::stdout().flush().unwrap();
+                                                       continue;
+                                               }
+                                       };
+                                       let amt_msat_str = match words.next() {
+                                               Some(amt) => amt,
+                                               None => {
+                                                       println!("ERROR: keysend requires an amount in millisatoshis: `keysend <dest_pubkey> <amt_msat>`");
+
+                                                       print!("> ");
+                                                       io::stdout().flush().unwrap();
+                                                       continue;
+                                               }
+                                       };
+                                       let amt_msat: u64 = match amt_msat_str.parse() {
+                                               Ok(amt) => amt,
+                                               Err(e) => {
+                                                       println!("ERROR: couldn't parse amount_msat: {}", e);
+                                                       print!("> ");
+                                                       io::stdout().flush().unwrap();
+                                                       continue;
+                                               }
+                                       };
+                                       keysend(
+                                               dest_pubkey,
+                                               amt_msat,
                                                router.clone(),
                                                channel_manager.clone(),
-                                               payment_storage.clone(),
+                                               outbound_payments.clone(),
                                                logger.clone(),
                                        );
                                }
                                "getinvoice" => {
                                        let amt_str = words.next();
                                        if amt_str.is_none() {
-                                               println!("ERROR: getinvoice requires an amount in satoshis");
+                                               println!("ERROR: getinvoice requires an amount in millisatoshis");
                                                print!("> ");
                                                io::stdout().flush().unwrap();
                                                continue;
                                        }
 
-                                       let amt_sat: Result<u64, _> = amt_str.unwrap().parse();
-                                       if amt_sat.is_err() {
+                                       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;
                                        }
                                        get_invoice(
-                                               amt_sat.unwrap(),
-                                               payment_storage.clone(),
-                                               node_privkey.clone(),
+                                               amt_msat.unwrap(),
+                                               inbound_payments.clone(),
                                                channel_manager.clone(),
+                                               keys_manager.clone(),
                                                network,
                                        );
                                }
@@ -323,20 +355,17 @@ pub(crate) fn poll_for_user_input(
                                                                continue;
                                                        }
                                                };
-                                       if connect_peer_if_necessary(
-                                               pubkey,
-                                               peer_addr,
-                                               peer_manager.clone(),
-                                               event_notifier.clone(),
-                                               runtime_handle.clone(),
-                                       )
-                                       .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()),
-                               "listpayments" => list_payments(payment_storage.clone()),
+                               "listpayments" => {
+                                       list_payments(inbound_payments.clone(), outbound_payments.clone())
+                               }
                                "closechannel" => {
                                        let channel_id_str = words.next();
                                        if channel_id_str.is_none() {
@@ -375,6 +404,8 @@ pub(crate) fn poll_for_user_input(
                                        channel_id.copy_from_slice(&channel_id_vec.unwrap());
                                        force_close_channel(channel_id, channel_manager.clone());
                                }
+                               "nodeinfo" => node_info(channel_manager.clone(), peer_manager.clone()),
+                               "listpeers" => list_peers(peer_manager.clone()),
                                _ => println!("Unknown command. See `\"help\" for available commands."),
                        }
                }
@@ -384,14 +415,33 @@ pub(crate) fn poll_for_user_input(
 }
 
 fn help() {
-       println!("openchannel pubkey@host:port <channel_amt_satoshis>");
+       println!("openchannel pubkey@host:port <amt_satoshis>");
        println!("sendpayment <invoice>");
-       println!("getinvoice <amt_in_satoshis>");
+       println!("getinvoice <amt_millisatoshis>");
        println!("connectpeer pubkey@host:port");
        println!("listchannels");
        println!("listpayments");
        println!("closechannel <channel_id>");
        println!("forceclosechannel <channel_id>");
+       println!("nodeinfo");
+       println!("listpeers");
+}
+
+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());
+       println!("\t\t num_peers: {}", peer_manager.get_peer_node_ids().len());
+       println!("\t}},");
+}
+
+fn list_peers(peer_manager: Arc<PeerManager>) {
+       println!("\t{{");
+       for pubkey in peer_manager.get_peer_node_ids() {
+               println!("\t\t pubkey: {}", pubkey);
+       }
+       println!("\t}},");
 }
 
 fn list_channels(channel_manager: Arc<ChannelManager>) {
@@ -400,41 +450,60 @@ fn list_channels(channel_manager: Arc<ChannelManager>) {
                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(id) = chan_info.short_channel_id {
+                       println!("\t\tshort_channel_id: {},", id);
                }
-               println!("\t\tpending_open: {},", pending_channel);
+               println!("\t\tis_confirmed_onchain: {},", chan_info.is_funding_locked);
                println!("\t\tchannel_value_satoshis: {},", chan_info.channel_value_satoshis);
-               println!("\t\tchannel_can_send_payments: {},", chan_info.is_live);
+               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!("]");
 }
 
-fn list_payments(payment_storage: PaymentInfoStorage) {
-       let payments = payment_storage.lock().unwrap();
+fn list_payments(inbound_payments: PaymentInfoStorage, outbound_payments: PaymentInfoStorage) {
+       let inbound = inbound_payments.lock().unwrap();
+       let outbound = outbound_payments.lock().unwrap();
        print!("[");
-       for (payment_hash, payment_info) in payments.deref() {
-               let direction_str = match payment_info.1 {
-                       HTLCDirection::Inbound => "inbound",
-                       HTLCDirection::Outbound => "outbound",
-               };
+       for (payment_hash, payment_info) in inbound.deref() {
                println!("");
                println!("\t{{");
-               println!("\t\tamount_satoshis: {},", payment_info.3);
+               println!("\t\tamount_millisatoshis: {},", payment_info.amt_msat);
                println!("\t\tpayment_hash: {},", hex_utils::hex_str(&payment_hash.0));
-               println!("\t\thtlc_direction: {},", direction_str);
+               println!("\t\thtlc_direction: inbound,");
                println!(
                        "\t\thtlc_status: {},",
-                       match payment_info.2 {
+                       match payment_info.status {
+                               HTLCStatus::Pending => "pending",
+                               HTLCStatus::Succeeded => "succeeded",
+                               HTLCStatus::Failed => "failed",
+                       }
+               );
+
+               println!("\t}},");
+       }
+
+       for (payment_hash, payment_info) in outbound.deref() {
+               println!("");
+               println!("\t{{");
+               println!("\t\tamount_millisatoshis: {},", payment_info.amt_msat);
+               println!("\t\tpayment_hash: {},", hex_utils::hex_str(&payment_hash.0));
+               println!("\t\thtlc_direction: outbound,");
+               println!(
+                       "\t\thtlc_status: {},",
+                       match payment_info.status {
                                HTLCStatus::Pending => "pending",
                                HTLCStatus::Succeeded => "succeeded",
                                HTLCStatus::Failed => "failed",
@@ -446,33 +515,35 @@ fn list_payments(payment_storage: PaymentInfoStorage) {
        println!("]");
 }
 
-pub(crate) fn connect_peer_if_necessary(
+pub(crate) async fn connect_peer_if_necessary(
        pubkey: PublicKey, peer_addr: SocketAddr, peer_manager: Arc<PeerManager>,
-       event_notifier: mpsc::Sender<()>, runtime: Handle,
 ) -> Result<(), ()> {
        for node_pubkey in peer_manager.get_peer_node_ids() {
                if node_pubkey == pubkey {
                        return Ok(());
                }
        }
-       match TcpStream::connect_timeout(&peer_addr, Duration::from_secs(10)) {
-               Ok(stream) => {
-                       let peer_mgr = peer_manager.clone();
-                       let event_ntfns = event_notifier.clone();
-                       runtime.spawn(async move {
-                               lightning_net_tokio::setup_outbound(peer_mgr, event_ntfns, pubkey, stream).await;
-                       });
-                       let mut peer_connected = false;
-                       while !peer_connected {
-                               for node_pubkey in peer_manager.get_peer_node_ids() {
-                                       if node_pubkey == pubkey {
-                                               peer_connected = true;
+       match lightning_net_tokio::connect_outbound(Arc::clone(&peer_manager), pubkey, peer_addr).await
+       {
+               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 => {}
+                               }
+                               // Avoid blocking the tokio context by sleeping a bit
+                               match peer_manager.get_peer_node_ids().iter().find(|id| **id == pubkey) {
+                                       Some(_) => break,
+                                       None => tokio::time::sleep(Duration::from_millis(10)).await,
                                }
                        }
                }
-               Err(e) => {
-                       println!("ERROR: failed to connect to peer: {:?}", e);
+               None => {
+                       println!("ERROR: failed to connect to peer");
                        return Err(());
                }
        }
@@ -480,16 +551,20 @@ pub(crate) fn connect_peer_if_necessary(
 }
 
 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 {
+               peer_channel_config_limits: ChannelHandshakeLimits {
+                       // lnd's max to_self_delay is 2016, so we want to be compatible.
+                       their_to_self_delay: 2016,
+                       ..Default::default()
+               },
+               channel_options: ChannelConfig { 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(());
@@ -504,7 +579,8 @@ 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>,
-       router: Arc<NetGraphMsgHandler<Arc<dyn chain::Access>, Arc<FilesystemLogger>>>,
+       route_hints: Vec<&RouteHint>,
+       router: Arc<NetGraphMsgHandler<Arc<dyn chain::Access + Send + Sync>, Arc<FilesystemLogger>>>,
        channel_manager: Arc<ChannelManager>, payment_storage: PaymentInfoStorage,
        logger: Arc<FilesystemLogger>,
 ) {
@@ -518,7 +594,7 @@ fn send_payment(
                &payee,
                payee_features,
                Some(&first_hops.iter().collect::<Vec<_>>()),
-               &vec![],
+               &route_hints,
                amt_msat,
                final_cltv,
                logger,
@@ -541,72 +617,92 @@ fn send_payment(
        let mut payments = payment_storage.lock().unwrap();
        payments.insert(
                payment_hash,
-               (None, HTLCDirection::Outbound, status, SatoshiAmount(Some(amt_msat / 1000))),
+               PaymentInfo {
+                       preimage: None,
+                       secret: payment_secret,
+                       status,
+                       amt_msat: MillisatAmount(Some(amt_msat)),
+               },
        );
 }
 
-fn get_invoice(
-       amt_sat: u64, payment_storage: PaymentInfoStorage, our_node_privkey: SecretKey,
-       channel_manager: Arc<ChannelManager>, network: Network,
+fn keysend(
+       payee: PublicKey, amt_msat: u64,
+       router: Arc<NetGraphMsgHandler<Arc<dyn chain::Access + Send + Sync>, Arc<FilesystemLogger>>>,
+       channel_manager: Arc<ChannelManager>, payment_storage: PaymentInfoStorage,
+       logger: Arc<FilesystemLogger>,
 ) {
-       let mut payments = payment_storage.lock().unwrap();
-       let secp_ctx = Secp256k1::new();
-
-       let mut preimage = [0; 32];
-       rand::thread_rng().fill_bytes(&mut preimage);
-       let payment_hash = Sha256Hash::hash(&preimage);
-
-       let our_node_pubkey = channel_manager.get_our_node_id();
-       let mut invoice = lightning_invoice::InvoiceBuilder::new(match network {
-               Network::Bitcoin => lightning_invoice::Currency::Bitcoin,
-               Network::Testnet => lightning_invoice::Currency::BitcoinTestnet,
-               Network::Regtest => lightning_invoice::Currency::Regtest,
-               Network::Signet => panic!("Signet invoices not supported"),
-       })
-       .payment_hash(payment_hash)
-       .description("rust-lightning-bitcoinrpc invoice".to_string())
-       .amount_pico_btc(amt_sat * 10_000)
-       .current_timestamp()
-       .payee_pub_key(our_node_pubkey);
-
-       // Add route hints to the invoice.
-       let our_channels = channel_manager.list_usable_channels();
-       for channel in our_channels {
-               let short_channel_id = match channel.short_channel_id {
-                       Some(id) => id.to_be_bytes(),
-                       None => continue,
-               };
-               let forwarding_info = match channel.counterparty_forwarding_info {
-                       Some(info) => info,
-                       None => continue,
-               };
-               println!("VMW: adding routehop, info.fee base: {}", forwarding_info.fee_base_msat);
-               invoice = invoice.route(vec![lightning_invoice::RouteHop {
-                       pubkey: channel.remote_network_id,
-                       short_channel_id,
-                       fee_base_msat: forwarding_info.fee_base_msat,
-                       fee_proportional_millionths: forwarding_info.fee_proportional_millionths,
-                       cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
-               }]);
-       }
+       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();
 
-       // Sign the invoice.
-       let invoice =
-               invoice.build_signed(|msg_hash| secp_ctx.sign_recoverable(msg_hash, &our_node_privkey));
+       let route = match router::get_keysend_route(
+               &payer_pubkey,
+               &network_graph,
+               &payee,
+               Some(&first_hops.iter().collect::<Vec<_>>()),
+               &vec![],
+               amt_msat,
+               40,
+               logger,
+       ) {
+               Ok(r) => r,
+               Err(e) => {
+                       println!("ERROR: failed to find route: {}", e.err);
+                       return;
+               }
+       };
 
-       match invoice {
-               Ok(invoice) => println!("SUCCESS: generated invoice: {}", invoice),
-               Err(e) => println!("ERROR: failed to create invoice: {:?}", e),
-       }
+       let mut payments = payment_storage.lock().unwrap();
+       let payment_hash = channel_manager.send_spontaneous_payment(&route, None).unwrap();
+       payments.insert(
+               payment_hash,
+               PaymentInfo {
+                       preimage: None,
+                       secret: None,
+                       status: HTLCStatus::Pending,
+                       amt_msat: MillisatAmount(Some(amt_msat)),
+               },
+       );
+}
 
+fn get_invoice(
+       amt_msat: u64, payment_storage: PaymentInfoStorage, channel_manager: Arc<ChannelManager>,
+       keys_manager: Arc<KeysManager>, network: Network,
+) {
+       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"),
+       };
+       let invoice = match utils::create_invoice_from_channelmanager(
+               &channel_manager,
+               keys_manager,
+               currency,
+               Some(amt_msat),
+               "ldk-tutorial-node".to_string(),
+       ) {
+               Ok(inv) => {
+                       println!("SUCCESS: generated invoice: {}", inv);
+                       inv
+               }
+               Err(e) => {
+                       println!("ERROR: failed to create invoice: {:?}", e);
+                       return;
+               }
+       };
+
+       let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
        payments.insert(
-               PaymentHash(payment_hash.into_inner()),
-               (
-                       Some(PaymentPreimage(preimage)),
-                       HTLCDirection::Inbound,
-                       HTLCStatus::Pending,
-                       SatoshiAmount(Some(amt_sat)),
-               ),
+               payment_hash,
+               PaymentInfo {
+                       preimage: None,
+                       secret: invoice.payment_secret().cloned(),
+                       status: HTLCStatus::Pending,
+                       amt_msat: MillisatAmount(Some(amt_msat)),
+               },
        );
 }
 
@@ -633,13 +729,12 @@ pub(crate) fn parse_peer_info(
        if peer_addr_str.is_none() || 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`",
                ));
        }
 
-       let peer_addr: Result<SocketAddr, _> = peer_addr_str.unwrap().parse();
-       if peer_addr.is_err() {
+       let peer_addr = peer_addr_str.unwrap().to_socket_addrs().map(|mut r| r.next());
+       if peer_addr.is_err() || peer_addr.as_ref().unwrap().is_none() {
                return Err(std::io::Error::new(
                        std::io::ErrorKind::Other,
                        "ERROR: couldn't parse pubkey@host:port into a socket address",
@@ -654,5 +749,5 @@ pub(crate) fn parse_peer_info(
                ));
        }
 
-       Ok((pubkey.unwrap(), peer_addr.unwrap()))
+       Ok((pubkey.unwrap(), peer_addr.unwrap().unwrap()))
 }