X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=src%2Fcli.rs;h=9cb0f174fa70b3be67d13c4438e2bc011554dcb4;hb=44b7ad33748d85d885e2876d5afc255791523d3f;hp=030109ecf792d353cf41b6adae34f58d3a05f946;hpb=90ff6896459523d237ab2a8401dfddf9e99ae34e;p=ldk-sample diff --git a/src/cli.rs b/src/cli.rs index 030109e..9cb0f17 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -1,31 +1,34 @@ -use crate::disk; +use crate::disk::{self, INBOUND_PAYMENTS_FNAME, OUTBOUND_PAYMENTS_FNAME}; use crate::hex_utils; use crate::{ - ChannelManager, HTLCStatus, InvoicePayer, MillisatAmount, NetworkGraph, OnionMessenger, - PaymentInfo, PaymentInfoStorage, PeerManager, + ChannelManager, HTLCStatus, MillisatAmount, NetworkGraph, OnionMessenger, PaymentInfo, + PaymentInfoStorage, PeerManager, }; use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::Hash; use bitcoin::network::constants::Network; use bitcoin::secp256k1::PublicKey; -use lightning::chain::keysinterface::{KeysInterface, KeysManager, Recipient}; -use lightning::ln::msgs::{DecodeError, NetAddress}; -use lightning::ln::{PaymentHash, PaymentPreimage}; +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::{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::events::EventHandler; -use lightning::util::ser::{MaybeReadableArgs, Writeable, Writer}; -use lightning_invoice::payment::PaymentError; -use lightning_invoice::{utils, Currency, Invoice}; +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::fs_store::FilesystemStore; use std::env; use std::io; use std::io::Write; use std::net::{SocketAddr, ToSocketAddrs}; -use std::ops::Deref; use std::path::Path; use std::str::FromStr; -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use std::time::Duration; pub(crate) struct LdkUserInfo { @@ -35,7 +38,7 @@ 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, + pub(crate) ldk_announced_listen_addr: Vec, pub(crate) ldk_announced_node_name: [u8; 32], pub(crate) network: Network, } @@ -50,25 +53,19 @@ impl CustomOnionMessageContents for UserOnionMessageContents { self.tlv_type } } -impl MaybeReadableArgs for UserOnionMessageContents { - fn read(_r: &mut R, _args: u64) -> Result, DecodeError> { - // UserOnionMessageContents is only ever passed to `send_onion_message`, never to an - // `OnionMessageHandler`, thus it does not need to implement the read side here. - unreachable!(); - } -} + impl Writeable for UserOnionMessageContents { fn write(&self, w: &mut W) -> Result<(), std::io::Error> { w.write_all(&self.data) } } -pub(crate) async fn poll_for_user_input( - invoice_payer: Arc>, peer_manager: Arc, - channel_manager: Arc, keys_manager: Arc, - network_graph: Arc, onion_messenger: Arc, - inbound_payments: PaymentInfoStorage, outbound_payments: PaymentInfoStorage, - ldk_data_dir: String, network: Network, logger: Arc, +pub(crate) fn poll_for_user_input( + peer_manager: Arc, channel_manager: Arc, + keys_manager: Arc, network_graph: Arc, + onion_messenger: Arc, inbound_payments: Arc>, + outbound_payments: Arc>, ldk_data_dir: String, network: Network, + logger: Arc, persister: Arc, ) { println!( "LDK startup successful. Enter \"help\" to view available commands. Press Ctrl-D to quit." @@ -96,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(); @@ -115,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() @@ -154,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); @@ -162,7 +168,12 @@ pub(crate) async fn poll_for_user_input( } }; - send_payment(&*invoice_payer, &invoice, outbound_payments.clone()); + send_payment( + &channel_manager, + &invoice, + &mut outbound_payments.lock().unwrap(), + persister.clone(), + ); } "keysend" => { let dest_pubkey = match words.next() { @@ -193,11 +204,12 @@ pub(crate) async fn poll_for_user_input( } }; keysend( - &*invoice_payer, + &channel_manager, dest_pubkey, amt_msat, &*keys_manager, - outbound_payments.clone(), + &mut outbound_payments.lock().unwrap(), + persister.clone(), ); } "getinvoice" => { @@ -225,15 +237,19 @@ pub(crate) async fn poll_for_user_input( continue; } + let mut inbound_payments = inbound_payments.lock().unwrap(); get_invoice( amt_msat.unwrap(), - Arc::clone(&inbound_payments), - &*channel_manager, + &mut inbound_payments, + &channel_manager, Arc::clone(&keys_manager), network, expiry_secs.unwrap(), Arc::clone(&logger), ); + persister + .write("", "", INBOUND_PAYMENTS_FNAME, &inbound_payments.encode()) + .unwrap(); } "connectpeer" => { let peer_pubkey_and_ip_addr = words.next(); @@ -249,8 +265,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); @@ -283,9 +303,10 @@ pub(crate) async fn poll_for_user_input( } } "listchannels" => list_channels(&channel_manager, &network_graph), - "listpayments" => { - list_payments(inbound_payments.clone(), outbound_payments.clone()) - } + "listpayments" => list_payments( + &inbound_payments.lock().unwrap(), + &outbound_payments.lock().unwrap(), + ), "closechannel" => { let channel_id_str = words.next(); if channel_id_str.is_none() { @@ -362,15 +383,15 @@ 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..], - &keys_manager.get_node_secret(Recipient::Node).unwrap() + &line.trim().as_bytes()[MSG_STARTPOS..], + &keys_manager.get_node_secret_key() ) ); } @@ -382,7 +403,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) { @@ -401,7 +422,7 @@ pub(crate) async fn poll_for_user_input( break; } }; - node_pks.push(node_pubkey); + intermediate_nodes.push(node_pubkey); } if errored { continue; @@ -420,10 +441,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, ) { @@ -449,7 +470,7 @@ fn help() { println!(" help\tShows a list of commands."); println!(" quit\tClose the application."); println!("\n Channels:"); - println!(" openchannel pubkey@host:port [--public]"); + println!(" openchannel pubkey@host:port [--public] [--with-anchors]"); println!(" closechannel "); println!(" forceclosechannel "); println!(" listchannels"); @@ -485,7 +506,7 @@ fn node_info(channel_manager: &Arc, peer_manager: &Arc) { println!("\t{{"); - for pubkey in peer_manager.get_peer_node_ids() { + for (pubkey, _) in peer_manager.get_peer_node_ids() { println!("\t\t pubkey: {}", pubkey); } println!("\t}},"); @@ -496,7 +517,7 @@ fn list_channels(channel_manager: &Arc, network_graph: &Arc, network_graph: &Arc, network_graph: &Arc, ) -> Result<(), ()> { - for node_pubkey in peer_manager.get_peer_node_ids() { + for (node_pubkey, _) in peer_manager.get_peer_node_ids() { if node_pubkey == pubkey { return Ok(()); } @@ -597,16 +616,12 @@ pub(crate) async fn do_connect_peer( 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(_) => { - 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(_) => return Ok(()), - None => tokio::time::sleep(Duration::from_millis(10)).await, + tokio::select! { + _ = &mut connection_closed_future => return Err(()), + _ = tokio::time::sleep(Duration::from_millis(10)) => {}, + }; + if peer_manager.get_peer_node_ids().iter().find(|(id, _)| *id == pubkey).is_some() { + return Ok(()); } } } @@ -628,17 +643,17 @@ fn do_disconnect_peer( //check the pubkey matches a valid connected peer let peers = peer_manager.get_peer_node_ids(); - if !peers.contains(&pubkey) { + if !peers.iter().any(|(pk, _)| &pubkey == pk) { println!("Error: Could not find peer {}", pubkey); return Err(()); } - peer_manager.disconnect_by_node_id(pubkey, false); + peer_manager.disconnect_by_node_id(pubkey); Ok(()) } 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, ) -> Result<(), ()> { let config = UserConfig { @@ -649,6 +664,7 @@ fn open_channel( }, channel_handshake_config: ChannelHandshakeConfig { announced_channel, + negotiate_anchors_zero_fee_htlc_tx: with_anchors, ..Default::default() }, ..Default::default() @@ -666,100 +682,84 @@ fn open_channel( } } -fn send_payment( - invoice_payer: &InvoicePayer, invoice: &Invoice, payment_storage: PaymentInfoStorage, +fn send_payment( + channel_manager: &ChannelManager, invoice: &Bolt11Invoice, + outbound_payments: &mut PaymentInfoStorage, persister: Arc, ) { - let status = match invoice_payer.pay_invoice(invoice) { + let payment_hash = PaymentHash((*invoice.payment_hash()).into_inner()); + let payment_secret = Some(*invoice.payment_secret()); + outbound_payments.payments.insert( + payment_hash, + PaymentInfo { + preimage: None, + secret: payment_secret, + status: HTLCStatus::Pending, + amt_msat: MillisatAmount(invoice.amount_milli_satoshis()), + }, + ); + persister.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode()).unwrap(); + match pay_invoice(invoice, Retry::Timeout(Duration::from_secs(10)), channel_manager) { 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(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)) => { + Err(e) => { println!("ERROR: failed to send payment: {:?}", e); print!("> "); - HTLCStatus::Failed + outbound_payments.payments.get_mut(&payment_hash).unwrap().status = HTLCStatus::Failed; + persister.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode()).unwrap(); } }; - 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( +fn keysend( + channel_manager: &ChannelManager, payee_pubkey: PublicKey, amt_msat: u64, entropy_source: &E, + outbound_payments: &mut PaymentInfoStorage, persister: Arc, +) { + let payment_preimage = PaymentPreimage(entropy_source.get_secure_random_bytes()); + let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()); + + let route_params = RouteParameters::from_payment_params_and_value( + PaymentParameters::for_keysend(payee_pubkey, 40, false), + amt_msat, + ); + outbound_payments.payments.insert( payment_hash, PaymentInfo { preimage: None, - secret: payment_secret, - status, - amt_msat: MillisatAmount(invoice.amount_milli_satoshis()), + secret: None, + status: HTLCStatus::Pending, + amt_msat: MillisatAmount(Some(amt_msat)), }, ); -} - -fn keysend( - invoice_payer: &InvoicePayer, 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, + persister.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), + route_params, + Retry::Timeout(Duration::from_secs(10)), ) { - Ok(_payment_id) => { + Ok(_payment_hash) => { 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)) => { + Err(e) => { println!("ERROR: failed to send payment: {:?}", e); print!("> "); - HTLCStatus::Failed + outbound_payments.payments.get_mut(&payment_hash).unwrap().status = HTLCStatus::Failed; + persister.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode()).unwrap(); } }; - - 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)), - }, - ); } fn get_invoice( - amt_msat: u64, payment_storage: PaymentInfoStorage, channel_manager: &ChannelManager, + amt_msat: u64, inbound_payments: &mut PaymentInfoStorage, channel_manager: &ChannelManager, keys_manager: Arc, network: Network, expiry_secs: u32, logger: Arc, ) { - let mut payments = payment_storage.lock().unwrap(); let currency = match network { Network::Bitcoin => Currency::Bitcoin, Network::Testnet => Currency::BitcoinTestnet, @@ -774,6 +774,7 @@ fn get_invoice( Some(amt_msat), "ldk-tutorial-node".to_string(), expiry_secs, + None, ) { Ok(inv) => { println!("SUCCESS: generated invoice: {}", inv); @@ -786,7 +787,7 @@ fn get_invoice( }; let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner()); - payments.insert( + inbound_payments.payments.insert( payment_hash, PaymentInfo { preimage: None, @@ -800,7 +801,7 @@ fn get_invoice( fn close_channel( channel_id: [u8; 32], counterparty_node_id: PublicKey, channel_manager: Arc, ) { - 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), } @@ -809,7 +810,9 @@ fn close_channel( fn force_close_channel( channel_id: [u8; 32], counterparty_node_id: PublicKey, channel_manager: Arc, ) { - 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), }