Update to LDK 0.0.121
[ldk-sample] / src / cli.rs
index 75b79673a11ba8aa342275c78b0042d0a97073f1..e3487421373c74ad6ae862fefe8f53119551edff 100644 (file)
@@ -1,27 +1,26 @@
 use crate::disk::{self, INBOUND_PAYMENTS_FNAME, OUTBOUND_PAYMENTS_FNAME};
 use crate::hex_utils;
 use crate::{
-       ChannelManager, HTLCStatus, MillisatAmount, NetworkGraph, OnionMessenger, PaymentInfo,
-       PaymentInfoStorage, PeerManager,
+       ChannelManager, HTLCStatus, InboundPaymentInfoStorage, MillisatAmount, NetworkGraph,
+       OnionMessenger, OutboundPaymentInfoStorage, PaymentInfo, PeerManager,
 };
 use bitcoin::hashes::sha256::Hash as Sha256;
 use bitcoin::hashes::Hash;
 use bitcoin::network::constants::Network;
 use bitcoin::secp256k1::PublicKey;
 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::ln::msgs::SocketAddress;
+use lightning::ln::{ChannelId, PaymentHash, PaymentPreimage};
+use lightning::onion_message::messenger::Destination;
+use lightning::onion_message::packet::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::persist::KVStore;
 use lightning::util::ser::{Writeable, Writer};
-use lightning_invoice::payment::pay_invoice;
 use lightning_invoice::{utils, Bolt11Invoice, Currency};
-use lightning_persister::FilesystemPersister;
+use lightning_persister::fs_store::FilesystemStore;
 use std::env;
 use std::io;
 use std::io::Write;
@@ -38,17 +37,18 @@ 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_listen_addr: Vec<SocketAddress>,
        pub(crate) ldk_announced_node_name: [u8; 32],
        pub(crate) network: Network,
 }
 
+#[derive(Debug)]
 struct UserOnionMessageContents {
        tlv_type: u64,
        data: Vec<u8>,
 }
 
-impl CustomOnionMessageContents for UserOnionMessageContents {
+impl OnionMessageContents for UserOnionMessageContents {
        fn tlv_type(&self) -> u64 {
                self.tlv_type
        }
@@ -63,9 +63,9 @@ impl Writeable for UserOnionMessageContents {
 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>>,
-       outbound_payments: Arc<Mutex<PaymentInfoStorage>>, ldk_data_dir: String, network: Network,
-       logger: Arc<disk::FilesystemLogger>, persister: Arc<FilesystemPersister>,
+       onion_messenger: Arc<OnionMessenger>, inbound_payments: Arc<Mutex<InboundPaymentInfoStorage>>,
+       outbound_payments: Arc<Mutex<OutboundPaymentInfoStorage>>, ldk_data_dir: String,
+       network: Network, logger: Arc<disk::FilesystemLogger>, fs_store: Arc<FilesystemStore>,
 ) {
        println!(
                "LDK startup successful. Enter \"help\" to view available commands. Press Ctrl-D to quit."
@@ -172,7 +172,7 @@ pub(crate) fn poll_for_user_input(
                                                &channel_manager,
                                                &invoice,
                                                &mut outbound_payments.lock().unwrap(),
-                                               persister.clone(),
+                                               Arc::clone(&fs_store),
                                        );
                                }
                                "keysend" => {
@@ -209,7 +209,7 @@ pub(crate) fn poll_for_user_input(
                                                amt_msat,
                                                &*keys_manager,
                                                &mut outbound_payments.lock().unwrap(),
-                                               persister.clone(),
+                                               Arc::clone(&fs_store),
                                        );
                                }
                                "getinvoice" => {
@@ -247,7 +247,9 @@ pub(crate) fn poll_for_user_input(
                                                expiry_secs.unwrap(),
                                                Arc::clone(&logger),
                                        );
-                                       persister.persist(INBOUND_PAYMENTS_FNAME, &*inbound_payments).unwrap();
+                                       fs_store
+                                               .write("", "", INBOUND_PAYMENTS_FNAME, &inbound_payments.encode())
+                                               .unwrap();
                                }
                                "connectpeer" => {
                                        let peer_pubkey_and_ip_addr = words.next();
@@ -440,13 +442,14 @@ pub(crate) fn poll_for_user_input(
                                                }
                                        };
                                        let destination = Destination::Node(intermediate_nodes.pop().unwrap());
-                                       let message_path = OnionMessagePath { intermediate_nodes, destination };
                                        match onion_messenger.send_onion_message(
-                                               message_path,
-                                               OnionMessageContents::Custom(UserOnionMessageContents { tlv_type, data }),
+                                               UserOnionMessageContents { tlv_type, data },
+                                               destination,
                                                None,
                                        ) {
-                                               Ok(()) => println!("SUCCESS: forwarded onion message to first hop"),
+                                               Ok(success) => {
+                                                       println!("SUCCESS: forwarded onion message to first hop {:?}", success)
+                                               }
                                                Err(e) => println!("ERROR: failed to send onion message: {:?}", e),
                                        }
                                }
@@ -515,7 +518,7 @@ fn list_channels(channel_manager: &Arc<ChannelManager>, network_graph: &Arc<Netw
        for chan_info in channel_manager.list_channels() {
                println!("");
                println!("\t{{");
-               println!("\t\tchannel_id: {},", hex_utils::hex_str(&chan_info.channel_id[..]));
+               println!("\t\tchannel_id: {},", chan_info.channel_id);
                if let Some(funding_txo) = chan_info.funding_txo {
                        println!("\t\tfunding_txid: {},", funding_txo.txid);
                }
@@ -539,7 +542,7 @@ fn list_channels(channel_manager: &Arc<ChannelManager>, network_graph: &Arc<Netw
                }
                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);
+               println!("\t\toutbound_capacity_msat: {},", chan_info.outbound_capacity_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);
@@ -551,13 +554,15 @@ fn list_channels(channel_manager: &Arc<ChannelManager>, network_graph: &Arc<Netw
        println!("]");
 }
 
-fn list_payments(inbound_payments: &PaymentInfoStorage, outbound_payments: &PaymentInfoStorage) {
+fn list_payments(
+       inbound_payments: &InboundPaymentInfoStorage, outbound_payments: &OutboundPaymentInfoStorage,
+) {
        print!("[");
        for (payment_hash, payment_info) in &inbound_payments.payments {
                println!("");
                println!("\t{{");
                println!("\t\tamount_millisatoshis: {},", payment_info.amt_msat);
-               println!("\t\tpayment_hash: {},", hex_utils::hex_str(&payment_hash.0));
+               println!("\t\tpayment_hash: {},", payment_hash);
                println!("\t\thtlc_direction: inbound,");
                println!(
                        "\t\thtlc_status: {},",
@@ -575,7 +580,7 @@ fn list_payments(inbound_payments: &PaymentInfoStorage, outbound_payments: &Paym
                println!("");
                println!("\t{{");
                println!("\t\tamount_millisatoshis: {},", payment_info.amt_msat);
-               println!("\t\tpayment_hash: {},", hex_utils::hex_str(&payment_hash.0));
+               println!("\t\tpayment_hash: {},", payment_hash);
                println!("\t\thtlc_direction: outbound,");
                println!(
                        "\t\thtlc_status: {},",
@@ -668,7 +673,7 @@ fn open_channel(
                ..Default::default()
        };
 
-       match channel_manager.create_channel(peer_pubkey, channel_amt_sat, 0, 0, Some(config)) {
+       match channel_manager.create_channel(peer_pubkey, channel_amt_sat, 0, 0, None, Some(config)) {
                Ok(_) => {
                        println!("EVENT: initiated channel with peer {}. ", peer_pubkey);
                        return Ok(());
@@ -682,12 +687,13 @@ fn open_channel(
 
 fn send_payment(
        channel_manager: &ChannelManager, invoice: &Bolt11Invoice,
-       outbound_payments: &mut PaymentInfoStorage, persister: Arc<FilesystemPersister>,
+       outbound_payments: &mut OutboundPaymentInfoStorage, fs_store: Arc<FilesystemStore>,
 ) {
-       let payment_hash = PaymentHash((*invoice.payment_hash()).into_inner());
+       let payment_id = PaymentId((*invoice.payment_hash()).to_byte_array());
+       let payment_hash = PaymentHash((*invoice.payment_hash()).to_byte_array());
        let payment_secret = Some(*invoice.payment_secret());
        outbound_payments.payments.insert(
-               payment_hash,
+               payment_id,
                PaymentInfo {
                        preimage: None,
                        secret: payment_secret,
@@ -695,9 +701,52 @@ fn send_payment(
                        amt_msat: MillisatAmount(invoice.amount_milli_satoshis()),
                },
        );
-       persister.persist(OUTBOUND_PAYMENTS_FNAME, &*outbound_payments).unwrap();
-       match pay_invoice(invoice, Retry::Timeout(Duration::from_secs(10)), channel_manager) {
-               Ok(_payment_id) => {
+       fs_store.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode()).unwrap();
+
+       let mut recipient_onion = RecipientOnionFields::secret_only(*invoice.payment_secret());
+       recipient_onion.payment_metadata = invoice.payment_metadata().map(|v| v.clone());
+       let mut payment_params = match PaymentParameters::from_node_id(
+               invoice.recover_payee_pub_key(),
+               invoice.min_final_cltv_expiry_delta() as u32,
+       )
+       .with_expiry_time(
+               invoice.duration_since_epoch().as_secs().saturating_add(invoice.expiry_time().as_secs()),
+       )
+       .with_route_hints(invoice.route_hints())
+       {
+               Err(e) => {
+                       println!("ERROR: Could not process invoice to prepare payment parameters, {:?}, invoice: {:?}", e, invoice);
+                       return;
+               }
+               Ok(p) => p,
+       };
+       if let Some(features) = invoice.features() {
+               payment_params = match payment_params.with_bolt11_features(features.clone()) {
+                       Err(e) => {
+                               println!("ERROR: Could not build BOLT11 payment parameters! {:?}", e);
+                               return;
+                       }
+                       Ok(p) => p,
+               };
+       }
+       let invoice_amount = match invoice.amount_milli_satoshis() {
+               None => {
+                       println!("ERROR: An invoice with an amount is expected; {:?}", invoice);
+                       return;
+               }
+               Some(a) => a,
+       };
+       let route_params =
+               RouteParameters::from_payment_params_and_value(payment_params, invoice_amount);
+
+       match channel_manager.send_payment(
+               payment_hash,
+               recipient_onion,
+               payment_id,
+               route_params,
+               Retry::Timeout(Duration::from_secs(10)),
+       ) {
+               Ok(_) => {
                        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);
@@ -706,25 +755,25 @@ fn send_payment(
                Err(e) => {
                        println!("ERROR: failed to send payment: {:?}", e);
                        print!("> ");
-                       outbound_payments.payments.get_mut(&payment_hash).unwrap().status = HTLCStatus::Failed;
-                       persister.persist(OUTBOUND_PAYMENTS_FNAME, &*outbound_payments).unwrap();
+                       outbound_payments.payments.get_mut(&payment_id).unwrap().status = HTLCStatus::Failed;
+                       fs_store.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode()).unwrap();
                }
        };
 }
 
 fn keysend<E: EntropySource>(
        channel_manager: &ChannelManager, payee_pubkey: PublicKey, amt_msat: u64, entropy_source: &E,
-       outbound_payments: &mut PaymentInfoStorage, persister: Arc<FilesystemPersister>,
+       outbound_payments: &mut OutboundPaymentInfoStorage, fs_store: Arc<FilesystemStore>,
 ) {
        let payment_preimage = PaymentPreimage(entropy_source.get_secure_random_bytes());
-       let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
+       let payment_id = PaymentId(Sha256::hash(&payment_preimage.0[..]).to_byte_array());
 
-       let route_params = RouteParameters {
-               payment_params: PaymentParameters::for_keysend(payee_pubkey, 40, false),
-               final_value_msat: amt_msat,
-       };
+       let route_params = RouteParameters::from_payment_params_and_value(
+               PaymentParameters::for_keysend(payee_pubkey, 40, false),
+               amt_msat,
+       );
        outbound_payments.payments.insert(
-               payment_hash,
+               payment_id,
                PaymentInfo {
                        preimage: None,
                        secret: None,
@@ -732,11 +781,11 @@ fn keysend<E: EntropySource>(
                        amt_msat: MillisatAmount(Some(amt_msat)),
                },
        );
-       persister.persist(OUTBOUND_PAYMENTS_FNAME, &*outbound_payments).unwrap();
+       fs_store.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode()).unwrap();
        match channel_manager.send_spontaneous_payment_with_retry(
                Some(payment_preimage),
                RecipientOnionFields::spontaneous_empty(),
-               PaymentId(payment_hash.0),
+               payment_id,
                route_params,
                Retry::Timeout(Duration::from_secs(10)),
        ) {
@@ -747,22 +796,22 @@ fn keysend<E: EntropySource>(
                Err(e) => {
                        println!("ERROR: failed to send payment: {:?}", e);
                        print!("> ");
-                       outbound_payments.payments.get_mut(&payment_hash).unwrap().status = HTLCStatus::Failed;
-                       persister.persist(OUTBOUND_PAYMENTS_FNAME, &*outbound_payments).unwrap();
+                       outbound_payments.payments.get_mut(&payment_id).unwrap().status = HTLCStatus::Failed;
+                       fs_store.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode()).unwrap();
                }
        };
 }
 
 fn get_invoice(
-       amt_msat: u64, inbound_payments: &mut PaymentInfoStorage, channel_manager: &ChannelManager,
-       keys_manager: Arc<KeysManager>, network: Network, expiry_secs: u32,
-       logger: Arc<disk::FilesystemLogger>,
+       amt_msat: u64, inbound_payments: &mut InboundPaymentInfoStorage,
+       channel_manager: &ChannelManager, keys_manager: Arc<KeysManager>, network: Network,
+       expiry_secs: u32, logger: Arc<disk::FilesystemLogger>,
 ) {
        let currency = match network {
                Network::Bitcoin => Currency::Bitcoin,
-               Network::Testnet => Currency::BitcoinTestnet,
                Network::Regtest => Currency::Regtest,
                Network::Signet => Currency::Signet,
+               Network::Testnet | _ => Currency::BitcoinTestnet,
        };
        let invoice = match utils::create_invoice_from_channelmanager(
                channel_manager,
@@ -784,7 +833,7 @@ fn get_invoice(
                }
        };
 
-       let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
+       let payment_hash = PaymentHash(invoice.payment_hash().to_byte_array());
        inbound_payments.payments.insert(
                payment_hash,
                PaymentInfo {
@@ -799,7 +848,7 @@ fn get_invoice(
 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) {
+       match channel_manager.close_channel(&ChannelId(channel_id), &counterparty_node_id) {
                Ok(()) => println!("EVENT: initiating channel close"),
                Err(e) => println!("ERROR: failed to close channel: {:?}", e),
        }
@@ -808,7 +857,9 @@ fn close_channel(
 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) {
+       match channel_manager
+               .force_close_broadcasting_latest_txn(&ChannelId(channel_id), &counterparty_node_id)
+       {
                Ok(()) => println!("EVENT: initiating channel force-close"),
                Err(e) => println!("ERROR: failed to force-close channel: {:?}", e),
        }