Add BOLT12 Offer generation and payment support
[ldk-sample] / src / cli.rs
index 1856cbdda42dac90d01718dedd73b50d5819d2c6..72cc484220d818e8cd2a54e4cdd9537dc6383648 100644 (file)
@@ -11,15 +11,16 @@ use bitcoin::secp256k1::PublicKey;
 use lightning::ln::channelmanager::{PaymentId, RecipientOnionFields, Retry};
 use lightning::ln::msgs::SocketAddress;
 use lightning::ln::{ChannelId, PaymentHash, PaymentPreimage};
-use lightning::onion_message::OnionMessagePath;
-use lightning::onion_message::{Destination, OnionMessageContents};
+use lightning::offers::offer::{self, Offer};
+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::KVStore;
 use lightning::util::ser::{Writeable, Writer};
-use lightning_invoice::payment::pay_invoice;
+use lightning_invoice::payment::payment_parameters_from_invoice;
 use lightning_invoice::{utils, Bolt11Invoice, Currency};
 use lightning_persister::fs_store::FilesystemStore;
 use std::env;
@@ -43,6 +44,7 @@ pub(crate) struct LdkUserInfo {
        pub(crate) network: Network,
 }
 
+#[derive(Debug)]
 struct UserOnionMessageContents {
        tlv_type: u64,
        data: Vec<u8>,
@@ -72,7 +74,7 @@ pub(crate) fn poll_for_user_input(
        );
        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());
-       loop {
+       'read_command: loop {
                print!("> ");
                io::stdout().flush().unwrap(); // Without flushing, the `>` doesn't print
                let mut line = String::new();
@@ -160,20 +162,73 @@ pub(crate) fn poll_for_user_input(
                                                continue;
                                        }
 
-                                       let invoice = match Bolt11Invoice::from_str(invoice_str.unwrap()) {
-                                               Ok(inv) => inv,
-                                               Err(e) => {
-                                                       println!("ERROR: invalid invoice: {:?}", e);
-                                                       continue;
+                                       if let Ok(offer) = Offer::from_str(invoice_str.unwrap()) {
+                                               let offer_hash = Sha256::hash(invoice_str.unwrap().as_bytes());
+                                               let payment_id = PaymentId(*offer_hash.as_ref());
+
+                                               let amt_msat =
+                                                       match offer.amount() {
+                                                               Some(offer::Amount::Bitcoin { amount_msats }) => *amount_msats,
+                                                               amt => {
+                                                                       println!("ERROR: Cannot process non-Bitcoin-denominated offer value {:?}", amt);
+                                                                       continue;
+                                                               }
+                                                       };
+
+                                               loop {
+                                                       print!("Paying offer for {} msat. Continue (Y/N)? >", amt_msat);
+                                                       io::stdout().flush().unwrap();
+
+                                                       if let Err(e) = io::stdin().read_line(&mut line) {
+                                                               println!("ERROR: {}", e);
+                                                               break 'read_command;
+                                                       }
+
+                                                       if line.len() == 0 {
+                                                               // We hit EOF / Ctrl-D
+                                                               break 'read_command;
+                                                       }
+
+                                                       if line.starts_with("Y") {
+                                                               break;
+                                                       }
+                                                       if line.starts_with("N") {
+                                                               continue 'read_command;
+                                                       }
                                                }
-                                       };
 
-                                       send_payment(
-                                               &channel_manager,
-                                               &invoice,
-                                               &mut outbound_payments.lock().unwrap(),
-                                               Arc::clone(&fs_store),
-                                       );
+                                               outbound_payments.lock().unwrap().payments.insert(
+                                                       payment_id,
+                                                       PaymentInfo {
+                                                               preimage: None,
+                                                               secret: None,
+                                                               status: HTLCStatus::Pending,
+                                                               amt_msat: MillisatAmount(Some(amt_msat)),
+                                                       },
+                                               );
+                                               fs_store
+                                                       .write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode())
+                                                       .unwrap();
+
+                                               let retry = Retry::Timeout(Duration::from_secs(10));
+                                               let pay = channel_manager
+                                                       .pay_for_offer(&offer, None, None, None, payment_id, retry, None);
+                                               if pay.is_err() {
+                                                       println!("ERROR: Failed to pay: {:?}", pay);
+                                               }
+                                       } else {
+                                               match Bolt11Invoice::from_str(invoice_str.unwrap()) {
+                                                       Ok(invoice) => send_payment(
+                                                               &channel_manager,
+                                                               &invoice,
+                                                               &mut outbound_payments.lock().unwrap(),
+                                                               Arc::clone(&fs_store),
+                                                       ),
+                                                       Err(e) => {
+                                                               println!("ERROR: invalid invoice: {:?}", e);
+                                                       }
+                                               }
+                                       }
                                }
                                "keysend" => {
                                        let dest_pubkey = match words.next() {
@@ -212,6 +267,34 @@ pub(crate) fn poll_for_user_input(
                                                Arc::clone(&fs_store),
                                        );
                                }
+                               "getoffer" => {
+                                       let offer_builder = channel_manager.create_offer_builder(String::new());
+                                       if let Err(e) = offer_builder {
+                                               println!("ERROR: Failed to initiate offer building: {:?}", e);
+                                               continue;
+                                       }
+
+                                       let amt_str = words.next();
+                                       let offer = if amt_str.is_some() {
+                                               let amt_msat: Result<u64, _> = amt_str.unwrap().parse();
+                                               if amt_msat.is_err() {
+                                                       println!("ERROR: getoffer provided payment amount was not a number");
+                                                       continue;
+                                               }
+                                               offer_builder.unwrap().amount_msats(amt_msat.unwrap()).build()
+                                       } else {
+                                               offer_builder.unwrap().build()
+                                       };
+
+                                       if offer.is_err() {
+                                               println!("ERROR: Failed to build offer: {:?}", offer.unwrap_err());
+                                       } else {
+                                               // Note that unlike BOLT11 invoice creation we don't bother to add a
+                                               // pending inbound payment here, as offers can be reused and don't
+                                               // correspond with individual payments.
+                                               println!("{}", offer.unwrap());
+                                       }
+                               }
                                "getinvoice" => {
                                        let amt_str = words.next();
                                        if amt_str.is_none() {
@@ -442,13 +525,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,
                                                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),
                                        }
                                }
@@ -479,11 +563,12 @@ fn help() {
        println!("      disconnectpeer <peer_pubkey>");
        println!("      listpeers");
        println!("\n  Payments:");
-       println!("      sendpayment <invoice>");
+       println!("      sendpayment <invoice|offer>");
        println!("      keysend <dest_pubkey> <amt_msats>");
        println!("      listpayments");
        println!("\n  Invoices:");
        println!("      getinvoice <amt_msats> <expiry_secs>");
+       println!("      getoffer [<amt_msats>]");
        println!("\n  Other:");
        println!("      signmessage <message>");
        println!(
@@ -672,7 +757,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(());
@@ -688,8 +773,17 @@ fn send_payment(
        channel_manager: &ChannelManager, invoice: &Bolt11Invoice,
        outbound_payments: &mut OutboundPaymentInfoStorage, fs_store: Arc<FilesystemStore>,
 ) {
-       let payment_id = PaymentId((*invoice.payment_hash()).into_inner());
+       let payment_id = PaymentId((*invoice.payment_hash()).to_byte_array());
        let payment_secret = Some(*invoice.payment_secret());
+       let (payment_hash, recipient_onion, route_params) =
+               match payment_parameters_from_invoice(invoice) {
+                       Ok(res) => res,
+                       Err(e) => {
+                               println!("Failed to parse invoice");
+                               print!("> ");
+                               return;
+                       }
+               };
        outbound_payments.payments.insert(
                payment_id,
                PaymentInfo {
@@ -700,8 +794,15 @@ fn send_payment(
                },
        );
        fs_store.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode()).unwrap();
-       match pay_invoice(invoice, Retry::Timeout(Duration::from_secs(10)), channel_manager) {
-               Ok(_payment_id) => {
+
+       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);
@@ -721,7 +822,7 @@ fn keysend<E: EntropySource>(
        outbound_payments: &mut OutboundPaymentInfoStorage, fs_store: Arc<FilesystemStore>,
 ) {
        let payment_preimage = PaymentPreimage(entropy_source.get_secure_random_bytes());
-       let payment_id = PaymentId(Sha256::hash(&payment_preimage.0[..]).into_inner());
+       let payment_id = PaymentId(Sha256::hash(&payment_preimage.0[..]).to_byte_array());
 
        let route_params = RouteParameters::from_payment_params_and_value(
                PaymentParameters::for_keysend(payee_pubkey, 40, false),
@@ -764,9 +865,9 @@ fn get_invoice(
 ) {
        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,
@@ -788,7 +889,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 {