1 use crate::disk::{self, INBOUND_PAYMENTS_FNAME, OUTBOUND_PAYMENTS_FNAME};
4 ChannelManager, HTLCStatus, InboundPaymentInfoStorage, MillisatAmount, NetworkGraph,
5 OnionMessenger, OutboundPaymentInfoStorage, PaymentInfo, PeerManager,
7 use bitcoin::hashes::sha256::Hash as Sha256;
8 use bitcoin::hashes::Hash;
9 use bitcoin::network::constants::Network;
10 use bitcoin::secp256k1::PublicKey;
11 use lightning::ln::channelmanager::{PaymentId, RecipientOnionFields, Retry};
12 use lightning::ln::msgs::SocketAddress;
13 use lightning::ln::{ChannelId, PaymentHash, PaymentPreimage};
14 use lightning::offers::offer::{self, Offer};
15 use lightning::onion_message::messenger::Destination;
16 use lightning::onion_message::packet::OnionMessageContents;
17 use lightning::routing::gossip::NodeId;
18 use lightning::routing::router::{PaymentParameters, RouteParameters};
19 use lightning::sign::{EntropySource, KeysManager};
20 use lightning::util::config::{ChannelHandshakeConfig, ChannelHandshakeLimits, UserConfig};
21 use lightning::util::persist::KVStore;
22 use lightning::util::ser::{Writeable, Writer};
23 use lightning_invoice::payment::payment_parameters_from_invoice;
24 use lightning_invoice::payment::payment_parameters_from_zero_amount_invoice;
25 use lightning_invoice::{utils, Bolt11Invoice, Currency};
26 use lightning_persister::fs_store::FilesystemStore;
30 use std::net::{SocketAddr, ToSocketAddrs};
32 use std::str::FromStr;
33 use std::sync::{Arc, Mutex};
34 use std::time::Duration;
36 pub(crate) struct LdkUserInfo {
37 pub(crate) bitcoind_rpc_username: String,
38 pub(crate) bitcoind_rpc_password: String,
39 pub(crate) bitcoind_rpc_port: u16,
40 pub(crate) bitcoind_rpc_host: String,
41 pub(crate) ldk_storage_dir_path: String,
42 pub(crate) ldk_peer_listening_port: u16,
43 pub(crate) ldk_announced_listen_addr: Vec<SocketAddress>,
44 pub(crate) ldk_announced_node_name: [u8; 32],
45 pub(crate) network: Network,
49 struct UserOnionMessageContents {
54 impl OnionMessageContents for UserOnionMessageContents {
55 fn tlv_type(&self) -> u64 {
60 impl Writeable for UserOnionMessageContents {
61 fn write<W: Writer>(&self, w: &mut W) -> Result<(), std::io::Error> {
62 w.write_all(&self.data)
66 pub(crate) fn poll_for_user_input(
67 peer_manager: Arc<PeerManager>, channel_manager: Arc<ChannelManager>,
68 keys_manager: Arc<KeysManager>, network_graph: Arc<NetworkGraph>,
69 onion_messenger: Arc<OnionMessenger>, inbound_payments: Arc<Mutex<InboundPaymentInfoStorage>>,
70 outbound_payments: Arc<Mutex<OutboundPaymentInfoStorage>>, ldk_data_dir: String,
71 network: Network, logger: Arc<disk::FilesystemLogger>, fs_store: Arc<FilesystemStore>,
74 "LDK startup successful. Enter \"help\" to view available commands. Press Ctrl-D to quit."
76 println!("LDK logs are available at <your-supplied-ldk-data-dir-path>/.ldk/logs");
77 println!("Local Node ID is {}.", channel_manager.get_our_node_id());
80 io::stdout().flush().unwrap(); // Without flushing, the `>` doesn't print
81 let mut line = String::new();
82 if let Err(e) = io::stdin().read_line(&mut line) {
83 break println!("ERROR: {}", e);
87 // We hit EOF / Ctrl-D
91 let mut words = line.split_whitespace();
92 if let Some(word) = words.next() {
96 let peer_pubkey_and_ip_addr = words.next();
97 let channel_value_sat = words.next();
98 if peer_pubkey_and_ip_addr.is_none() || channel_value_sat.is_none() {
99 println!("ERROR: openchannel has 2 required arguments: `openchannel pubkey@host:port channel_amt_satoshis` [--public] [--with-anchors]");
102 let peer_pubkey_and_ip_addr = peer_pubkey_and_ip_addr.unwrap();
103 let (pubkey, peer_addr) =
104 match parse_peer_info(peer_pubkey_and_ip_addr.to_string()) {
107 println!("{:?}", e.into_inner().unwrap());
112 let chan_amt_sat: Result<u64, _> = channel_value_sat.unwrap().parse();
113 if chan_amt_sat.is_err() {
114 println!("ERROR: channel amount must be a number");
118 if tokio::runtime::Handle::current()
119 .block_on(connect_peer_if_necessary(
122 peer_manager.clone(),
129 let (mut announce_channel, mut with_anchors) = (false, false);
130 while let Some(word) = words.next() {
132 "--public" | "--public=true" => announce_channel = true,
133 "--public=false" => announce_channel = false,
134 "--with-anchors" | "--with-anchors=true" => with_anchors = true,
135 "--with-anchors=false" => with_anchors = false,
137 println!("ERROR: invalid boolean flag format. Valid formats: `--option`, `--option=true` `--option=false`");
145 chan_amt_sat.unwrap(),
148 channel_manager.clone(),
152 let peer_data_path = format!("{}/channel_peer_data", ldk_data_dir.clone());
153 let _ = disk::persist_channel_peer(
154 Path::new(&peer_data_path),
155 peer_pubkey_and_ip_addr,
160 let invoice_str = words.next();
161 if invoice_str.is_none() {
162 println!("ERROR: sendpayment requires an invoice: `sendpayment <invoice>`");
166 let mut user_provided_amt: Option<u64> = None;
167 if let Some(amt_msat_str) = words.next() {
168 match amt_msat_str.parse() {
169 Ok(amt) => user_provided_amt = Some(amt),
171 println!("ERROR: couldn't parse amount_msat: {}", e);
177 if let Ok(offer) = Offer::from_str(invoice_str.unwrap()) {
178 let offer_hash = Sha256::hash(invoice_str.unwrap().as_bytes());
179 let payment_id = PaymentId(*offer_hash.as_ref());
181 let amt_msat = match (offer.amount(), user_provided_amt) {
182 (Some(offer::Amount::Bitcoin { amount_msats }), _) => *amount_msats,
183 (_, Some(amt)) => amt,
185 println!("ERROR: Cannot process non-Bitcoin-denominated offer value {:?}", amt);
189 if user_provided_amt.is_some() && user_provided_amt != Some(amt_msat) {
190 println!("Amount didn't match offer of {}msat", amt_msat);
194 while user_provided_amt.is_none() {
195 print!("Paying offer for {} msat. Continue (Y/N)? >", amt_msat);
196 io::stdout().flush().unwrap();
198 if let Err(e) = io::stdin().read_line(&mut line) {
199 println!("ERROR: {}", e);
204 // We hit EOF / Ctrl-D
208 if line.starts_with("Y") {
211 if line.starts_with("N") {
212 continue 'read_command;
216 outbound_payments.lock().unwrap().payments.insert(
221 status: HTLCStatus::Pending,
222 amt_msat: MillisatAmount(Some(amt_msat)),
226 .write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode())
229 let retry = Retry::Timeout(Duration::from_secs(10));
230 let amt = Some(amt_msat);
231 let pay = channel_manager
232 .pay_for_offer(&offer, None, amt, None, payment_id, retry, None);
234 println!("ERROR: Failed to pay: {:?}", pay);
237 match Bolt11Invoice::from_str(invoice_str.unwrap()) {
238 Ok(invoice) => send_payment(
242 &mut outbound_payments.lock().unwrap(),
243 Arc::clone(&fs_store),
246 println!("ERROR: invalid invoice: {:?}", e);
252 let dest_pubkey = match words.next() {
253 Some(dest) => match hex_utils::to_compressed_pubkey(dest) {
256 println!("ERROR: couldn't parse destination pubkey");
261 println!("ERROR: keysend requires a destination pubkey: `keysend <dest_pubkey> <amt_msat>`");
265 let amt_msat_str = match words.next() {
268 println!("ERROR: keysend requires an amount in millisatoshis: `keysend <dest_pubkey> <amt_msat>`");
272 let amt_msat: u64 = match amt_msat_str.parse() {
275 println!("ERROR: couldn't parse amount_msat: {}", e);
284 &mut outbound_payments.lock().unwrap(),
285 Arc::clone(&fs_store),
289 let offer_builder = channel_manager.create_offer_builder(String::new());
290 if let Err(e) = offer_builder {
291 println!("ERROR: Failed to initiate offer building: {:?}", e);
295 let amt_str = words.next();
296 let offer = if amt_str.is_some() {
297 let amt_msat: Result<u64, _> = amt_str.unwrap().parse();
298 if amt_msat.is_err() {
299 println!("ERROR: getoffer provided payment amount was not a number");
302 offer_builder.unwrap().amount_msats(amt_msat.unwrap()).build()
304 offer_builder.unwrap().build()
308 println!("ERROR: Failed to build offer: {:?}", offer.unwrap_err());
310 // Note that unlike BOLT11 invoice creation we don't bother to add a
311 // pending inbound payment here, as offers can be reused and don't
312 // correspond with individual payments.
313 println!("{}", offer.unwrap());
317 let amt_str = words.next();
318 if amt_str.is_none() {
319 println!("ERROR: getinvoice requires an amount in millisatoshis");
323 let amt_msat: Result<u64, _> = amt_str.unwrap().parse();
324 if amt_msat.is_err() {
325 println!("ERROR: getinvoice provided payment amount was not a number");
329 let expiry_secs_str = words.next();
330 if expiry_secs_str.is_none() {
331 println!("ERROR: getinvoice requires an expiry in seconds");
335 let expiry_secs: Result<u32, _> = expiry_secs_str.unwrap().parse();
336 if expiry_secs.is_err() {
337 println!("ERROR: getinvoice provided expiry was not a number");
341 let mut inbound_payments = inbound_payments.lock().unwrap();
344 &mut inbound_payments,
346 Arc::clone(&keys_manager),
348 expiry_secs.unwrap(),
352 .write("", "", INBOUND_PAYMENTS_FNAME, &inbound_payments.encode())
356 let peer_pubkey_and_ip_addr = words.next();
357 if peer_pubkey_and_ip_addr.is_none() {
358 println!("ERROR: connectpeer requires peer connection info: `connectpeer pubkey@host:port`");
361 let (pubkey, peer_addr) =
362 match parse_peer_info(peer_pubkey_and_ip_addr.unwrap().to_string()) {
365 println!("{:?}", e.into_inner().unwrap());
369 if tokio::runtime::Handle::current()
370 .block_on(connect_peer_if_necessary(
373 peer_manager.clone(),
377 println!("SUCCESS: connected to peer {}", pubkey);
380 "disconnectpeer" => {
381 let peer_pubkey = words.next();
382 if peer_pubkey.is_none() {
383 println!("ERROR: disconnectpeer requires peer public key: `disconnectpeer <peer_pubkey>`");
388 match bitcoin::secp256k1::PublicKey::from_str(peer_pubkey.unwrap()) {
389 Ok(pubkey) => pubkey,
391 println!("ERROR: {}", e.to_string());
396 if do_disconnect_peer(
398 peer_manager.clone(),
399 channel_manager.clone(),
403 println!("SUCCESS: disconnected from peer {}", peer_pubkey);
406 "listchannels" => list_channels(&channel_manager, &network_graph),
407 "listpayments" => list_payments(
408 &inbound_payments.lock().unwrap(),
409 &outbound_payments.lock().unwrap(),
412 let channel_id_str = words.next();
413 if channel_id_str.is_none() {
414 println!("ERROR: closechannel requires a channel ID: `closechannel <channel_id> <peer_pubkey>`");
417 let channel_id_vec = hex_utils::to_vec(channel_id_str.unwrap());
418 if channel_id_vec.is_none() || channel_id_vec.as_ref().unwrap().len() != 32 {
419 println!("ERROR: couldn't parse channel_id");
422 let mut channel_id = [0; 32];
423 channel_id.copy_from_slice(&channel_id_vec.unwrap());
425 let peer_pubkey_str = words.next();
426 if peer_pubkey_str.is_none() {
427 println!("ERROR: closechannel requires a peer pubkey: `closechannel <channel_id> <peer_pubkey>`");
430 let peer_pubkey_vec = match hex_utils::to_vec(peer_pubkey_str.unwrap()) {
431 Some(peer_pubkey_vec) => peer_pubkey_vec,
433 println!("ERROR: couldn't parse peer_pubkey");
437 let peer_pubkey = match PublicKey::from_slice(&peer_pubkey_vec) {
438 Ok(peer_pubkey) => peer_pubkey,
440 println!("ERROR: couldn't parse peer_pubkey");
445 close_channel(channel_id, peer_pubkey, channel_manager.clone());
447 "forceclosechannel" => {
448 let channel_id_str = words.next();
449 if channel_id_str.is_none() {
450 println!("ERROR: forceclosechannel requires a channel ID: `forceclosechannel <channel_id> <peer_pubkey>`");
453 let channel_id_vec = hex_utils::to_vec(channel_id_str.unwrap());
454 if channel_id_vec.is_none() || channel_id_vec.as_ref().unwrap().len() != 32 {
455 println!("ERROR: couldn't parse channel_id");
458 let mut channel_id = [0; 32];
459 channel_id.copy_from_slice(&channel_id_vec.unwrap());
461 let peer_pubkey_str = words.next();
462 if peer_pubkey_str.is_none() {
463 println!("ERROR: forceclosechannel requires a peer pubkey: `forceclosechannel <channel_id> <peer_pubkey>`");
466 let peer_pubkey_vec = match hex_utils::to_vec(peer_pubkey_str.unwrap()) {
467 Some(peer_pubkey_vec) => peer_pubkey_vec,
469 println!("ERROR: couldn't parse peer_pubkey");
473 let peer_pubkey = match PublicKey::from_slice(&peer_pubkey_vec) {
474 Ok(peer_pubkey) => peer_pubkey,
476 println!("ERROR: couldn't parse peer_pubkey");
481 force_close_channel(channel_id, peer_pubkey, channel_manager.clone());
483 "nodeinfo" => node_info(&channel_manager, &peer_manager),
484 "listpeers" => list_peers(peer_manager.clone()),
486 const MSG_STARTPOS: usize = "signmessage".len() + 1;
487 if line.trim().as_bytes().len() <= MSG_STARTPOS {
488 println!("ERROR: signmsg requires a message");
493 lightning::util::message_signing::sign(
494 &line.trim().as_bytes()[MSG_STARTPOS..],
495 &keys_manager.get_node_secret_key()
499 "sendonionmessage" => {
500 let path_pks_str = words.next();
501 if path_pks_str.is_none() {
503 "ERROR: sendonionmessage requires at least one node id for the path"
507 let mut intermediate_nodes = Vec::new();
508 let mut errored = false;
509 for pk_str in path_pks_str.unwrap().split(",") {
510 let node_pubkey_vec = match hex_utils::to_vec(pk_str) {
511 Some(peer_pubkey_vec) => peer_pubkey_vec,
513 println!("ERROR: couldn't parse peer_pubkey");
518 let node_pubkey = match PublicKey::from_slice(&node_pubkey_vec) {
519 Ok(peer_pubkey) => peer_pubkey,
521 println!("ERROR: couldn't parse peer_pubkey");
526 intermediate_nodes.push(node_pubkey);
531 let tlv_type = match words.next().map(|ty_str| ty_str.parse()) {
532 Some(Ok(ty)) if ty >= 64 => ty,
534 println!("Need an integral message type above 64");
538 let data = match words.next().map(|s| hex_utils::to_vec(s)) {
539 Some(Some(data)) => data,
541 println!("Need a hex data string");
545 let destination = Destination::Node(intermediate_nodes.pop().unwrap());
546 match onion_messenger.send_onion_message(
547 UserOnionMessageContents { tlv_type, data },
552 println!("SUCCESS: forwarded onion message to first hop {:?}", success)
554 Err(e) => println!("ERROR: failed to send onion message: {:?}", e),
557 "quit" | "exit" => break,
558 _ => println!("Unknown command. See `\"help\" for available commands."),
565 let package_version = env!("CARGO_PKG_VERSION");
566 let package_name = env!("CARGO_PKG_NAME");
567 println!("\nVERSION:");
568 println!(" {} v{}", package_name, package_version);
569 println!("\nUSAGE:");
570 println!(" Command [arguments]");
571 println!("\nCOMMANDS:");
572 println!(" help\tShows a list of commands.");
573 println!(" quit\tClose the application.");
574 println!("\n Channels:");
575 println!(" openchannel pubkey@host:port <amt_satoshis> [--public] [--with-anchors]");
576 println!(" closechannel <channel_id> <peer_pubkey>");
577 println!(" forceclosechannel <channel_id> <peer_pubkey>");
578 println!(" listchannels");
579 println!("\n Peers:");
580 println!(" connectpeer pubkey@host:port");
581 println!(" disconnectpeer <peer_pubkey>");
582 println!(" listpeers");
583 println!("\n Payments:");
584 println!(" sendpayment <invoice|offer> [<amount_msat>]");
585 println!(" keysend <dest_pubkey> <amt_msats>");
586 println!(" listpayments");
587 println!("\n Invoices:");
588 println!(" getinvoice <amt_msats> <expiry_secs>");
589 println!(" getoffer [<amt_msats>]");
590 println!("\n Other:");
591 println!(" signmessage <message>");
593 " sendonionmessage <node_id_1,node_id_2,..,destination_node_id> <type> <hex_bytes>"
595 println!(" nodeinfo");
598 fn node_info(channel_manager: &Arc<ChannelManager>, peer_manager: &Arc<PeerManager>) {
600 println!("\t\t node_pubkey: {}", channel_manager.get_our_node_id());
601 let chans = channel_manager.list_channels();
602 println!("\t\t num_channels: {}", chans.len());
603 println!("\t\t num_usable_channels: {}", chans.iter().filter(|c| c.is_usable).count());
604 let local_balance_msat = chans.iter().map(|c| c.balance_msat).sum::<u64>();
605 println!("\t\t local_balance_msat: {}", local_balance_msat);
606 println!("\t\t num_peers: {}", peer_manager.get_peer_node_ids().len());
610 fn list_peers(peer_manager: Arc<PeerManager>) {
612 for (pubkey, _) in peer_manager.get_peer_node_ids() {
613 println!("\t\t pubkey: {}", pubkey);
618 fn list_channels(channel_manager: &Arc<ChannelManager>, network_graph: &Arc<NetworkGraph>) {
620 for chan_info in channel_manager.list_channels() {
623 println!("\t\tchannel_id: {},", chan_info.channel_id);
624 if let Some(funding_txo) = chan_info.funding_txo {
625 println!("\t\tfunding_txid: {},", funding_txo.txid);
629 "\t\tpeer_pubkey: {},",
630 hex_utils::hex_str(&chan_info.counterparty.node_id.serialize())
632 if let Some(node_info) = network_graph
635 .get(&NodeId::from_pubkey(&chan_info.counterparty.node_id))
637 if let Some(announcement) = &node_info.announcement_info {
638 println!("\t\tpeer_alias: {}", announcement.alias);
642 if let Some(id) = chan_info.short_channel_id {
643 println!("\t\tshort_channel_id: {},", id);
645 println!("\t\tis_channel_ready: {},", chan_info.is_channel_ready);
646 println!("\t\tchannel_value_satoshis: {},", chan_info.channel_value_satoshis);
647 println!("\t\toutbound_capacity_msat: {},", chan_info.outbound_capacity_msat);
648 if chan_info.is_usable {
649 println!("\t\tavailable_balance_for_send_msat: {},", chan_info.outbound_capacity_msat);
650 println!("\t\tavailable_balance_for_recv_msat: {},", chan_info.inbound_capacity_msat);
652 println!("\t\tchannel_can_send_payments: {},", chan_info.is_usable);
653 println!("\t\tpublic: {},", chan_info.is_public);
660 inbound_payments: &InboundPaymentInfoStorage, outbound_payments: &OutboundPaymentInfoStorage,
663 for (payment_hash, payment_info) in &inbound_payments.payments {
666 println!("\t\tamount_millisatoshis: {},", payment_info.amt_msat);
667 println!("\t\tpayment_hash: {},", payment_hash);
668 println!("\t\thtlc_direction: inbound,");
670 "\t\thtlc_status: {},",
671 match payment_info.status {
672 HTLCStatus::Pending => "pending",
673 HTLCStatus::Succeeded => "succeeded",
674 HTLCStatus::Failed => "failed",
681 for (payment_hash, payment_info) in &outbound_payments.payments {
684 println!("\t\tamount_millisatoshis: {},", payment_info.amt_msat);
685 println!("\t\tpayment_hash: {},", payment_hash);
686 println!("\t\thtlc_direction: outbound,");
688 "\t\thtlc_status: {},",
689 match payment_info.status {
690 HTLCStatus::Pending => "pending",
691 HTLCStatus::Succeeded => "succeeded",
692 HTLCStatus::Failed => "failed",
701 pub(crate) async fn connect_peer_if_necessary(
702 pubkey: PublicKey, peer_addr: SocketAddr, peer_manager: Arc<PeerManager>,
703 ) -> Result<(), ()> {
704 for (node_pubkey, _) in peer_manager.get_peer_node_ids() {
705 if node_pubkey == pubkey {
709 let res = do_connect_peer(pubkey, peer_addr, peer_manager).await;
711 println!("ERROR: failed to connect to peer");
716 pub(crate) async fn do_connect_peer(
717 pubkey: PublicKey, peer_addr: SocketAddr, peer_manager: Arc<PeerManager>,
718 ) -> Result<(), ()> {
719 match lightning_net_tokio::connect_outbound(Arc::clone(&peer_manager), pubkey, peer_addr).await
721 Some(connection_closed_future) => {
722 let mut connection_closed_future = Box::pin(connection_closed_future);
725 _ = &mut connection_closed_future => return Err(()),
726 _ = tokio::time::sleep(Duration::from_millis(10)) => {},
728 if peer_manager.get_peer_node_ids().iter().find(|(id, _)| *id == pubkey).is_some() {
737 fn do_disconnect_peer(
738 pubkey: bitcoin::secp256k1::PublicKey, peer_manager: Arc<PeerManager>,
739 channel_manager: Arc<ChannelManager>,
740 ) -> Result<(), ()> {
741 //check for open channels with peer
742 for channel in channel_manager.list_channels() {
743 if channel.counterparty.node_id == pubkey {
744 println!("Error: Node has an active channel with this peer, close any channels first");
749 //check the pubkey matches a valid connected peer
750 let peers = peer_manager.get_peer_node_ids();
751 if !peers.iter().any(|(pk, _)| &pubkey == pk) {
752 println!("Error: Could not find peer {}", pubkey);
756 peer_manager.disconnect_by_node_id(pubkey);
761 peer_pubkey: PublicKey, channel_amt_sat: u64, announced_channel: bool, with_anchors: bool,
762 channel_manager: Arc<ChannelManager>,
763 ) -> Result<(), ()> {
764 let config = UserConfig {
765 channel_handshake_limits: ChannelHandshakeLimits {
766 // lnd's max to_self_delay is 2016, so we want to be compatible.
767 their_to_self_delay: 2016,
770 channel_handshake_config: ChannelHandshakeConfig {
772 negotiate_anchors_zero_fee_htlc_tx: with_anchors,
778 match channel_manager.create_channel(peer_pubkey, channel_amt_sat, 0, 0, None, Some(config)) {
780 println!("EVENT: initiated channel with peer {}. ", peer_pubkey);
784 println!("ERROR: failed to open channel: {:?}", e);
791 channel_manager: &ChannelManager, invoice: &Bolt11Invoice, required_amount_msat: Option<u64>,
792 outbound_payments: &mut OutboundPaymentInfoStorage, fs_store: Arc<FilesystemStore>,
794 let payment_id = PaymentId((*invoice.payment_hash()).to_byte_array());
795 let payment_secret = Some(*invoice.payment_secret());
796 let zero_amt_invoice =
797 invoice.amount_milli_satoshis().is_none() || invoice.amount_milli_satoshis() == Some(0);
798 let pay_params_opt = if zero_amt_invoice {
799 if let Some(amt_msat) = required_amount_msat {
800 payment_parameters_from_zero_amount_invoice(invoice, amt_msat)
802 println!("Need an amount for the given 0-value invoice");
807 if required_amount_msat.is_some() && invoice.amount_milli_satoshis() != required_amount_msat
810 "Amount didn't match invoice value of {}msat",
811 invoice.amount_milli_satoshis().unwrap_or(0)
816 payment_parameters_from_invoice(invoice)
818 let (payment_hash, recipient_onion, route_params) = match pay_params_opt {
821 println!("Failed to parse invoice");
826 outbound_payments.payments.insert(
830 secret: payment_secret,
831 status: HTLCStatus::Pending,
832 amt_msat: MillisatAmount(invoice.amount_milli_satoshis()),
835 fs_store.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode()).unwrap();
837 match channel_manager.send_payment(
842 Retry::Timeout(Duration::from_secs(10)),
845 let payee_pubkey = invoice.recover_payee_pub_key();
846 let amt_msat = invoice.amount_milli_satoshis().unwrap();
847 println!("EVENT: initiated sending {} msats to {}", amt_msat, payee_pubkey);
851 println!("ERROR: failed to send payment: {:?}", e);
853 outbound_payments.payments.get_mut(&payment_id).unwrap().status = HTLCStatus::Failed;
854 fs_store.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode()).unwrap();
859 fn keysend<E: EntropySource>(
860 channel_manager: &ChannelManager, payee_pubkey: PublicKey, amt_msat: u64, entropy_source: &E,
861 outbound_payments: &mut OutboundPaymentInfoStorage, fs_store: Arc<FilesystemStore>,
863 let payment_preimage = PaymentPreimage(entropy_source.get_secure_random_bytes());
864 let payment_id = PaymentId(Sha256::hash(&payment_preimage.0[..]).to_byte_array());
866 let route_params = RouteParameters::from_payment_params_and_value(
867 PaymentParameters::for_keysend(payee_pubkey, 40, false),
870 outbound_payments.payments.insert(
875 status: HTLCStatus::Pending,
876 amt_msat: MillisatAmount(Some(amt_msat)),
879 fs_store.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode()).unwrap();
880 match channel_manager.send_spontaneous_payment_with_retry(
881 Some(payment_preimage),
882 RecipientOnionFields::spontaneous_empty(),
885 Retry::Timeout(Duration::from_secs(10)),
887 Ok(_payment_hash) => {
888 println!("EVENT: initiated sending {} msats to {}", amt_msat, payee_pubkey);
892 println!("ERROR: failed to send payment: {:?}", e);
894 outbound_payments.payments.get_mut(&payment_id).unwrap().status = HTLCStatus::Failed;
895 fs_store.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode()).unwrap();
901 amt_msat: u64, inbound_payments: &mut InboundPaymentInfoStorage,
902 channel_manager: &ChannelManager, keys_manager: Arc<KeysManager>, network: Network,
903 expiry_secs: u32, logger: Arc<disk::FilesystemLogger>,
905 let currency = match network {
906 Network::Bitcoin => Currency::Bitcoin,
907 Network::Regtest => Currency::Regtest,
908 Network::Signet => Currency::Signet,
909 Network::Testnet | _ => Currency::BitcoinTestnet,
911 let invoice = match utils::create_invoice_from_channelmanager(
917 "ldk-tutorial-node".to_string(),
922 println!("SUCCESS: generated invoice: {}", inv);
926 println!("ERROR: failed to create invoice: {:?}", e);
931 let payment_hash = PaymentHash(invoice.payment_hash().to_byte_array());
932 inbound_payments.payments.insert(
936 secret: Some(invoice.payment_secret().clone()),
937 status: HTLCStatus::Pending,
938 amt_msat: MillisatAmount(Some(amt_msat)),
944 channel_id: [u8; 32], counterparty_node_id: PublicKey, channel_manager: Arc<ChannelManager>,
946 match channel_manager.close_channel(&ChannelId(channel_id), &counterparty_node_id) {
947 Ok(()) => println!("EVENT: initiating channel close"),
948 Err(e) => println!("ERROR: failed to close channel: {:?}", e),
952 fn force_close_channel(
953 channel_id: [u8; 32], counterparty_node_id: PublicKey, channel_manager: Arc<ChannelManager>,
955 match channel_manager
956 .force_close_broadcasting_latest_txn(&ChannelId(channel_id), &counterparty_node_id)
958 Ok(()) => println!("EVENT: initiating channel force-close"),
959 Err(e) => println!("ERROR: failed to force-close channel: {:?}", e),
963 pub(crate) fn parse_peer_info(
964 peer_pubkey_and_ip_addr: String,
965 ) -> Result<(PublicKey, SocketAddr), std::io::Error> {
966 let mut pubkey_and_addr = peer_pubkey_and_ip_addr.split("@");
967 let pubkey = pubkey_and_addr.next();
968 let peer_addr_str = pubkey_and_addr.next();
969 if peer_addr_str.is_none() {
970 return Err(std::io::Error::new(
971 std::io::ErrorKind::Other,
972 "ERROR: incorrectly formatted peer info. Should be formatted as: `pubkey@host:port`",
976 let peer_addr = peer_addr_str.unwrap().to_socket_addrs().map(|mut r| r.next());
977 if peer_addr.is_err() || peer_addr.as_ref().unwrap().is_none() {
978 return Err(std::io::Error::new(
979 std::io::ErrorKind::Other,
980 "ERROR: couldn't parse pubkey@host:port into a socket address",
984 let pubkey = hex_utils::to_compressed_pubkey(pubkey.unwrap());
985 if pubkey.is_none() {
986 return Err(std::io::Error::new(
987 std::io::ErrorKind::Other,
988 "ERROR: unable to parse given pubkey for node",
992 Ok((pubkey.unwrap(), peer_addr.unwrap().unwrap()))