Dont block tokio reactor waiting on user input
[ldk-sample] / src / cli.rs
index f896721cdfef415d06600a34ac38695bfc4ee007..75b79673a11ba8aa342275c78b0042d0a97073f1 100644 (file)
@@ -8,18 +8,19 @@ use bitcoin::hashes::sha256::Hash as Sha256;
 use bitcoin::hashes::Hash;
 use bitcoin::network::constants::Network;
 use bitcoin::secp256k1::PublicKey;
-use lightning::chain::keysinterface::{EntropySource, KeysManager};
 use lightning::ln::channelmanager::{PaymentId, RecipientOnionFields, Retry};
 use lightning::ln::msgs::NetAddress;
 use lightning::ln::{PaymentHash, PaymentPreimage};
+use lightning::onion_message::OnionMessagePath;
 use lightning::onion_message::{CustomOnionMessageContents, Destination, OnionMessageContents};
 use lightning::routing::gossip::NodeId;
 use lightning::routing::router::{PaymentParameters, RouteParameters};
+use lightning::sign::{EntropySource, KeysManager};
 use lightning::util::config::{ChannelHandshakeConfig, ChannelHandshakeLimits, UserConfig};
 use lightning::util::persist::KVStorePersister;
 use lightning::util::ser::{Writeable, Writer};
 use lightning_invoice::payment::pay_invoice;
-use lightning_invoice::{utils, Currency, Invoice};
+use lightning_invoice::{utils, Bolt11Invoice, Currency};
 use lightning_persister::FilesystemPersister;
 use std::env;
 use std::io;
@@ -59,7 +60,7 @@ impl Writeable for UserOnionMessageContents {
        }
 }
 
-pub(crate) async fn poll_for_user_input(
+pub(crate) fn poll_for_user_input(
        peer_manager: Arc<PeerManager>, channel_manager: Arc<ChannelManager>,
        keys_manager: Arc<KeysManager>, network_graph: Arc<NetworkGraph>,
        onion_messenger: Arc<OnionMessenger>, inbound_payments: Arc<Mutex<PaymentInfoStorage>>,
@@ -92,7 +93,7 @@ pub(crate) async fn poll_for_user_input(
                                        let peer_pubkey_and_ip_addr = words.next();
                                        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]");
+                                               println!("ERROR: openchannel has 2 required arguments: `openchannel pubkey@host:port channel_amt_satoshis` [--public] [--with-anchors]");
                                                continue;
                                        }
                                        let peer_pubkey_and_ip_addr = peer_pubkey_and_ip_addr.unwrap();
@@ -111,27 +112,36 @@ pub(crate) async fn poll_for_user_input(
                                                continue;
                                        }
 
-                                       if connect_peer_if_necessary(pubkey, peer_addr, peer_manager.clone())
-                                               .await
+                                       if tokio::runtime::Handle::current()
+                                               .block_on(connect_peer_if_necessary(
+                                                       pubkey,
+                                                       peer_addr,
+                                                       peer_manager.clone(),
+                                               ))
                                                .is_err()
                                        {
                                                continue;
                                        };
 
-                                       let announce_channel = match words.next() {
-                                               Some("--public") | Some("--public=true") => true,
-                                               Some("--public=false") => false,
-                                               Some(_) => {
-                                                       println!("ERROR: invalid `--public` command format. Valid formats: `--public`, `--public=true` `--public=false`");
-                                                       continue;
+                                       let (mut announce_channel, mut with_anchors) = (false, false);
+                                       while let Some(word) = words.next() {
+                                               match word {
+                                                       "--public" | "--public=true" => announce_channel = true,
+                                                       "--public=false" => announce_channel = false,
+                                                       "--with-anchors" | "--with-anchors=true" => with_anchors = true,
+                                                       "--with-anchors=false" => with_anchors = false,
+                                                       _ => {
+                                                               println!("ERROR: invalid boolean flag format. Valid formats: `--option`, `--option=true` `--option=false`");
+                                                               continue;
+                                                       }
                                                }
-                                               None => false,
-                                       };
+                                       }
 
                                        if open_channel(
                                                pubkey,
                                                chan_amt_sat.unwrap(),
                                                announce_channel,
+                                               with_anchors,
                                                channel_manager.clone(),
                                        )
                                        .is_ok()
@@ -150,7 +160,7 @@ pub(crate) async fn poll_for_user_input(
                                                continue;
                                        }
 
-                                       let invoice = match Invoice::from_str(invoice_str.unwrap()) {
+                                       let invoice = match Bolt11Invoice::from_str(invoice_str.unwrap()) {
                                                Ok(inv) => inv,
                                                Err(e) => {
                                                        println!("ERROR: invalid invoice: {:?}", e);
@@ -253,8 +263,12 @@ pub(crate) async fn poll_for_user_input(
                                                                continue;
                                                        }
                                                };
-                                       if connect_peer_if_necessary(pubkey, peer_addr, peer_manager.clone())
-                                               .await
+                                       if tokio::runtime::Handle::current()
+                                               .block_on(connect_peer_if_necessary(
+                                                       pubkey,
+                                                       peer_addr,
+                                                       peer_manager.clone(),
+                                               ))
                                                .is_ok()
                                        {
                                                println!("SUCCESS: connected to peer {}", pubkey);
@@ -367,14 +381,14 @@ pub(crate) async fn poll_for_user_input(
                                "listpeers" => list_peers(peer_manager.clone()),
                                "signmessage" => {
                                        const MSG_STARTPOS: usize = "signmessage".len() + 1;
-                                       if line.as_bytes().len() <= MSG_STARTPOS {
+                                       if line.trim().as_bytes().len() <= MSG_STARTPOS {
                                                println!("ERROR: signmsg requires a message");
                                                continue;
                                        }
                                        println!(
                                                "{:?}",
                                                lightning::util::message_signing::sign(
-                                                       &line.as_bytes()[MSG_STARTPOS..],
+                                                       &line.trim().as_bytes()[MSG_STARTPOS..],
                                                        &keys_manager.get_node_secret_key()
                                                )
                                        );
@@ -387,7 +401,7 @@ pub(crate) async fn poll_for_user_input(
                                                );
                                                continue;
                                        }
-                                       let mut node_pks = Vec::new();
+                                       let mut intermediate_nodes = Vec::new();
                                        let mut errored = false;
                                        for pk_str in path_pks_str.unwrap().split(",") {
                                                let node_pubkey_vec = match hex_utils::to_vec(pk_str) {
@@ -406,7 +420,7 @@ pub(crate) async fn poll_for_user_input(
                                                                break;
                                                        }
                                                };
-                                               node_pks.push(node_pubkey);
+                                               intermediate_nodes.push(node_pubkey);
                                        }
                                        if errored {
                                                continue;
@@ -425,10 +439,10 @@ pub(crate) async fn poll_for_user_input(
                                                        continue;
                                                }
                                        };
-                                       let destination_pk = node_pks.pop().unwrap();
+                                       let destination = Destination::Node(intermediate_nodes.pop().unwrap());
+                                       let message_path = OnionMessagePath { intermediate_nodes, destination };
                                        match onion_messenger.send_onion_message(
-                                               &node_pks,
-                                               Destination::Node(destination_pk),
+                                               message_path,
                                                OnionMessageContents::Custom(UserOnionMessageContents { tlv_type, data }),
                                                None,
                                        ) {
@@ -454,7 +468,7 @@ fn help() {
        println!("  help\tShows a list of commands.");
        println!("  quit\tClose the application.");
        println!("\n  Channels:");
-       println!("      openchannel pubkey@host:port <amt_satoshis> [--public]");
+       println!("      openchannel pubkey@host:port <amt_satoshis> [--public] [--with-anchors]");
        println!("      closechannel <channel_id> <peer_pubkey>");
        println!("      forceclosechannel <channel_id> <peer_pubkey>");
        println!("      listchannels");
@@ -637,7 +651,7 @@ fn do_disconnect_peer(
 }
 
 fn open_channel(
-       peer_pubkey: PublicKey, channel_amt_sat: u64, announced_channel: bool,
+       peer_pubkey: PublicKey, channel_amt_sat: u64, announced_channel: bool, with_anchors: bool,
        channel_manager: Arc<ChannelManager>,
 ) -> Result<(), ()> {
        let config = UserConfig {
@@ -648,6 +662,7 @@ fn open_channel(
                },
                channel_handshake_config: ChannelHandshakeConfig {
                        announced_channel,
+                       negotiate_anchors_zero_fee_htlc_tx: with_anchors,
                        ..Default::default()
                },
                ..Default::default()
@@ -666,7 +681,7 @@ fn open_channel(
 }
 
 fn send_payment(
-       channel_manager: &ChannelManager, invoice: &Invoice,
+       channel_manager: &ChannelManager, invoice: &Bolt11Invoice,
        outbound_payments: &mut PaymentInfoStorage, persister: Arc<FilesystemPersister>,
 ) {
        let payment_hash = PaymentHash((*invoice.payment_hash()).into_inner());
@@ -705,7 +720,7 @@ fn keysend<E: EntropySource>(
        let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
 
        let route_params = RouteParameters {
-               payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
+               payment_params: PaymentParameters::for_keysend(payee_pubkey, 40, false),
                final_value_msat: amt_msat,
        };
        outbound_payments.payments.insert(