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::{utils, Bolt11Invoice, Currency};
25 use lightning_persister::fs_store::FilesystemStore;
29 use std::net::{SocketAddr, ToSocketAddrs};
31 use std::str::FromStr;
32 use std::sync::{Arc, Mutex};
33 use std::time::Duration;
35 pub(crate) struct LdkUserInfo {
36 pub(crate) bitcoind_rpc_username: String,
37 pub(crate) bitcoind_rpc_password: String,
38 pub(crate) bitcoind_rpc_port: u16,
39 pub(crate) bitcoind_rpc_host: String,
40 pub(crate) ldk_storage_dir_path: String,
41 pub(crate) ldk_peer_listening_port: u16,
42 pub(crate) ldk_announced_listen_addr: Vec<SocketAddress>,
43 pub(crate) ldk_announced_node_name: [u8; 32],
44 pub(crate) network: Network,
48 struct UserOnionMessageContents {
53 impl OnionMessageContents for UserOnionMessageContents {
54 fn tlv_type(&self) -> u64 {
59 impl Writeable for UserOnionMessageContents {
60 fn write<W: Writer>(&self, w: &mut W) -> Result<(), std::io::Error> {
61 w.write_all(&self.data)
65 pub(crate) fn poll_for_user_input(
66 peer_manager: Arc<PeerManager>, channel_manager: Arc<ChannelManager>,
67 keys_manager: Arc<KeysManager>, network_graph: Arc<NetworkGraph>,
68 onion_messenger: Arc<OnionMessenger>, inbound_payments: Arc<Mutex<InboundPaymentInfoStorage>>,
69 outbound_payments: Arc<Mutex<OutboundPaymentInfoStorage>>, ldk_data_dir: String,
70 network: Network, logger: Arc<disk::FilesystemLogger>, fs_store: Arc<FilesystemStore>,
73 "LDK startup successful. Enter \"help\" to view available commands. Press Ctrl-D to quit."
75 println!("LDK logs are available at <your-supplied-ldk-data-dir-path>/.ldk/logs");
76 println!("Local Node ID is {}.", channel_manager.get_our_node_id());
79 io::stdout().flush().unwrap(); // Without flushing, the `>` doesn't print
80 let mut line = String::new();
81 if let Err(e) = io::stdin().read_line(&mut line) {
82 break println!("ERROR: {}", e);
86 // We hit EOF / Ctrl-D
90 let mut words = line.split_whitespace();
91 if let Some(word) = words.next() {
95 let peer_pubkey_and_ip_addr = words.next();
96 let channel_value_sat = words.next();
97 if peer_pubkey_and_ip_addr.is_none() || channel_value_sat.is_none() {
98 println!("ERROR: openchannel has 2 required arguments: `openchannel pubkey@host:port channel_amt_satoshis` [--public] [--with-anchors]");
101 let peer_pubkey_and_ip_addr = peer_pubkey_and_ip_addr.unwrap();
102 let (pubkey, peer_addr) =
103 match parse_peer_info(peer_pubkey_and_ip_addr.to_string()) {
106 println!("{:?}", e.into_inner().unwrap());
111 let chan_amt_sat: Result<u64, _> = channel_value_sat.unwrap().parse();
112 if chan_amt_sat.is_err() {
113 println!("ERROR: channel amount must be a number");
117 if tokio::runtime::Handle::current()
118 .block_on(connect_peer_if_necessary(
121 peer_manager.clone(),
128 let (mut announce_channel, mut with_anchors) = (false, false);
129 while let Some(word) = words.next() {
131 "--public" | "--public=true" => announce_channel = true,
132 "--public=false" => announce_channel = false,
133 "--with-anchors" | "--with-anchors=true" => with_anchors = true,
134 "--with-anchors=false" => with_anchors = false,
136 println!("ERROR: invalid boolean flag format. Valid formats: `--option`, `--option=true` `--option=false`");
144 chan_amt_sat.unwrap(),
147 channel_manager.clone(),
151 let peer_data_path = format!("{}/channel_peer_data", ldk_data_dir.clone());
152 let _ = disk::persist_channel_peer(
153 Path::new(&peer_data_path),
154 peer_pubkey_and_ip_addr,
159 let invoice_str = words.next();
160 if invoice_str.is_none() {
161 println!("ERROR: sendpayment requires an invoice: `sendpayment <invoice>`");
165 if let Ok(offer) = Offer::from_str(invoice_str.unwrap()) {
166 let offer_hash = Sha256::hash(invoice_str.unwrap().as_bytes());
167 let payment_id = PaymentId(*offer_hash.as_ref());
170 match offer.amount() {
171 Some(offer::Amount::Bitcoin { amount_msats }) => *amount_msats,
173 println!("ERROR: Cannot process non-Bitcoin-denominated offer value {:?}", amt);
179 print!("Paying offer for {} msat. Continue (Y/N)? >", amt_msat);
180 io::stdout().flush().unwrap();
182 if let Err(e) = io::stdin().read_line(&mut line) {
183 println!("ERROR: {}", e);
188 // We hit EOF / Ctrl-D
192 if line.starts_with("Y") {
195 if line.starts_with("N") {
196 continue 'read_command;
200 outbound_payments.lock().unwrap().payments.insert(
205 status: HTLCStatus::Pending,
206 amt_msat: MillisatAmount(Some(amt_msat)),
210 .write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode())
213 let retry = Retry::Timeout(Duration::from_secs(10));
214 let pay = channel_manager
215 .pay_for_offer(&offer, None, None, None, payment_id, retry, None);
217 println!("ERROR: Failed to pay: {:?}", pay);
220 match Bolt11Invoice::from_str(invoice_str.unwrap()) {
221 Ok(invoice) => send_payment(
224 &mut outbound_payments.lock().unwrap(),
225 Arc::clone(&fs_store),
228 println!("ERROR: invalid invoice: {:?}", e);
234 let dest_pubkey = match words.next() {
235 Some(dest) => match hex_utils::to_compressed_pubkey(dest) {
238 println!("ERROR: couldn't parse destination pubkey");
243 println!("ERROR: keysend requires a destination pubkey: `keysend <dest_pubkey> <amt_msat>`");
247 let amt_msat_str = match words.next() {
250 println!("ERROR: keysend requires an amount in millisatoshis: `keysend <dest_pubkey> <amt_msat>`");
254 let amt_msat: u64 = match amt_msat_str.parse() {
257 println!("ERROR: couldn't parse amount_msat: {}", e);
266 &mut outbound_payments.lock().unwrap(),
267 Arc::clone(&fs_store),
271 let offer_builder = channel_manager.create_offer_builder(String::new());
272 if let Err(e) = offer_builder {
273 println!("ERROR: Failed to initiate offer building: {:?}", e);
277 let amt_str = words.next();
278 let offer = if amt_str.is_some() {
279 let amt_msat: Result<u64, _> = amt_str.unwrap().parse();
280 if amt_msat.is_err() {
281 println!("ERROR: getoffer provided payment amount was not a number");
284 offer_builder.unwrap().amount_msats(amt_msat.unwrap()).build()
286 offer_builder.unwrap().build()
290 println!("ERROR: Failed to build offer: {:?}", offer.unwrap_err());
292 // Note that unlike BOLT11 invoice creation we don't bother to add a
293 // pending inbound payment here, as offers can be reused and don't
294 // correspond with individual payments.
295 println!("{}", offer.unwrap());
299 let amt_str = words.next();
300 if amt_str.is_none() {
301 println!("ERROR: getinvoice requires an amount in millisatoshis");
305 let amt_msat: Result<u64, _> = amt_str.unwrap().parse();
306 if amt_msat.is_err() {
307 println!("ERROR: getinvoice provided payment amount was not a number");
311 let expiry_secs_str = words.next();
312 if expiry_secs_str.is_none() {
313 println!("ERROR: getinvoice requires an expiry in seconds");
317 let expiry_secs: Result<u32, _> = expiry_secs_str.unwrap().parse();
318 if expiry_secs.is_err() {
319 println!("ERROR: getinvoice provided expiry was not a number");
323 let mut inbound_payments = inbound_payments.lock().unwrap();
326 &mut inbound_payments,
328 Arc::clone(&keys_manager),
330 expiry_secs.unwrap(),
334 .write("", "", INBOUND_PAYMENTS_FNAME, &inbound_payments.encode())
338 let peer_pubkey_and_ip_addr = words.next();
339 if peer_pubkey_and_ip_addr.is_none() {
340 println!("ERROR: connectpeer requires peer connection info: `connectpeer pubkey@host:port`");
343 let (pubkey, peer_addr) =
344 match parse_peer_info(peer_pubkey_and_ip_addr.unwrap().to_string()) {
347 println!("{:?}", e.into_inner().unwrap());
351 if tokio::runtime::Handle::current()
352 .block_on(connect_peer_if_necessary(
355 peer_manager.clone(),
359 println!("SUCCESS: connected to peer {}", pubkey);
362 "disconnectpeer" => {
363 let peer_pubkey = words.next();
364 if peer_pubkey.is_none() {
365 println!("ERROR: disconnectpeer requires peer public key: `disconnectpeer <peer_pubkey>`");
370 match bitcoin::secp256k1::PublicKey::from_str(peer_pubkey.unwrap()) {
371 Ok(pubkey) => pubkey,
373 println!("ERROR: {}", e.to_string());
378 if do_disconnect_peer(
380 peer_manager.clone(),
381 channel_manager.clone(),
385 println!("SUCCESS: disconnected from peer {}", peer_pubkey);
388 "listchannels" => list_channels(&channel_manager, &network_graph),
389 "listpayments" => list_payments(
390 &inbound_payments.lock().unwrap(),
391 &outbound_payments.lock().unwrap(),
394 let channel_id_str = words.next();
395 if channel_id_str.is_none() {
396 println!("ERROR: closechannel requires a channel ID: `closechannel <channel_id> <peer_pubkey>`");
399 let channel_id_vec = hex_utils::to_vec(channel_id_str.unwrap());
400 if channel_id_vec.is_none() || channel_id_vec.as_ref().unwrap().len() != 32 {
401 println!("ERROR: couldn't parse channel_id");
404 let mut channel_id = [0; 32];
405 channel_id.copy_from_slice(&channel_id_vec.unwrap());
407 let peer_pubkey_str = words.next();
408 if peer_pubkey_str.is_none() {
409 println!("ERROR: closechannel requires a peer pubkey: `closechannel <channel_id> <peer_pubkey>`");
412 let peer_pubkey_vec = match hex_utils::to_vec(peer_pubkey_str.unwrap()) {
413 Some(peer_pubkey_vec) => peer_pubkey_vec,
415 println!("ERROR: couldn't parse peer_pubkey");
419 let peer_pubkey = match PublicKey::from_slice(&peer_pubkey_vec) {
420 Ok(peer_pubkey) => peer_pubkey,
422 println!("ERROR: couldn't parse peer_pubkey");
427 close_channel(channel_id, peer_pubkey, channel_manager.clone());
429 "forceclosechannel" => {
430 let channel_id_str = words.next();
431 if channel_id_str.is_none() {
432 println!("ERROR: forceclosechannel requires a channel ID: `forceclosechannel <channel_id> <peer_pubkey>`");
435 let channel_id_vec = hex_utils::to_vec(channel_id_str.unwrap());
436 if channel_id_vec.is_none() || channel_id_vec.as_ref().unwrap().len() != 32 {
437 println!("ERROR: couldn't parse channel_id");
440 let mut channel_id = [0; 32];
441 channel_id.copy_from_slice(&channel_id_vec.unwrap());
443 let peer_pubkey_str = words.next();
444 if peer_pubkey_str.is_none() {
445 println!("ERROR: forceclosechannel requires a peer pubkey: `forceclosechannel <channel_id> <peer_pubkey>`");
448 let peer_pubkey_vec = match hex_utils::to_vec(peer_pubkey_str.unwrap()) {
449 Some(peer_pubkey_vec) => peer_pubkey_vec,
451 println!("ERROR: couldn't parse peer_pubkey");
455 let peer_pubkey = match PublicKey::from_slice(&peer_pubkey_vec) {
456 Ok(peer_pubkey) => peer_pubkey,
458 println!("ERROR: couldn't parse peer_pubkey");
463 force_close_channel(channel_id, peer_pubkey, channel_manager.clone());
465 "nodeinfo" => node_info(&channel_manager, &peer_manager),
466 "listpeers" => list_peers(peer_manager.clone()),
468 const MSG_STARTPOS: usize = "signmessage".len() + 1;
469 if line.trim().as_bytes().len() <= MSG_STARTPOS {
470 println!("ERROR: signmsg requires a message");
475 lightning::util::message_signing::sign(
476 &line.trim().as_bytes()[MSG_STARTPOS..],
477 &keys_manager.get_node_secret_key()
481 "sendonionmessage" => {
482 let path_pks_str = words.next();
483 if path_pks_str.is_none() {
485 "ERROR: sendonionmessage requires at least one node id for the path"
489 let mut intermediate_nodes = Vec::new();
490 let mut errored = false;
491 for pk_str in path_pks_str.unwrap().split(",") {
492 let node_pubkey_vec = match hex_utils::to_vec(pk_str) {
493 Some(peer_pubkey_vec) => peer_pubkey_vec,
495 println!("ERROR: couldn't parse peer_pubkey");
500 let node_pubkey = match PublicKey::from_slice(&node_pubkey_vec) {
501 Ok(peer_pubkey) => peer_pubkey,
503 println!("ERROR: couldn't parse peer_pubkey");
508 intermediate_nodes.push(node_pubkey);
513 let tlv_type = match words.next().map(|ty_str| ty_str.parse()) {
514 Some(Ok(ty)) if ty >= 64 => ty,
516 println!("Need an integral message type above 64");
520 let data = match words.next().map(|s| hex_utils::to_vec(s)) {
521 Some(Some(data)) => data,
523 println!("Need a hex data string");
527 let destination = Destination::Node(intermediate_nodes.pop().unwrap());
528 match onion_messenger.send_onion_message(
529 UserOnionMessageContents { tlv_type, data },
534 println!("SUCCESS: forwarded onion message to first hop {:?}", success)
536 Err(e) => println!("ERROR: failed to send onion message: {:?}", e),
539 "quit" | "exit" => break,
540 _ => println!("Unknown command. See `\"help\" for available commands."),
547 let package_version = env!("CARGO_PKG_VERSION");
548 let package_name = env!("CARGO_PKG_NAME");
549 println!("\nVERSION:");
550 println!(" {} v{}", package_name, package_version);
551 println!("\nUSAGE:");
552 println!(" Command [arguments]");
553 println!("\nCOMMANDS:");
554 println!(" help\tShows a list of commands.");
555 println!(" quit\tClose the application.");
556 println!("\n Channels:");
557 println!(" openchannel pubkey@host:port <amt_satoshis> [--public] [--with-anchors]");
558 println!(" closechannel <channel_id> <peer_pubkey>");
559 println!(" forceclosechannel <channel_id> <peer_pubkey>");
560 println!(" listchannels");
561 println!("\n Peers:");
562 println!(" connectpeer pubkey@host:port");
563 println!(" disconnectpeer <peer_pubkey>");
564 println!(" listpeers");
565 println!("\n Payments:");
566 println!(" sendpayment <invoice|offer>");
567 println!(" keysend <dest_pubkey> <amt_msats>");
568 println!(" listpayments");
569 println!("\n Invoices:");
570 println!(" getinvoice <amt_msats> <expiry_secs>");
571 println!(" getoffer [<amt_msats>]");
572 println!("\n Other:");
573 println!(" signmessage <message>");
575 " sendonionmessage <node_id_1,node_id_2,..,destination_node_id> <type> <hex_bytes>"
577 println!(" nodeinfo");
580 fn node_info(channel_manager: &Arc<ChannelManager>, peer_manager: &Arc<PeerManager>) {
582 println!("\t\t node_pubkey: {}", channel_manager.get_our_node_id());
583 let chans = channel_manager.list_channels();
584 println!("\t\t num_channels: {}", chans.len());
585 println!("\t\t num_usable_channels: {}", chans.iter().filter(|c| c.is_usable).count());
586 let local_balance_msat = chans.iter().map(|c| c.balance_msat).sum::<u64>();
587 println!("\t\t local_balance_msat: {}", local_balance_msat);
588 println!("\t\t num_peers: {}", peer_manager.get_peer_node_ids().len());
592 fn list_peers(peer_manager: Arc<PeerManager>) {
594 for (pubkey, _) in peer_manager.get_peer_node_ids() {
595 println!("\t\t pubkey: {}", pubkey);
600 fn list_channels(channel_manager: &Arc<ChannelManager>, network_graph: &Arc<NetworkGraph>) {
602 for chan_info in channel_manager.list_channels() {
605 println!("\t\tchannel_id: {},", chan_info.channel_id);
606 if let Some(funding_txo) = chan_info.funding_txo {
607 println!("\t\tfunding_txid: {},", funding_txo.txid);
611 "\t\tpeer_pubkey: {},",
612 hex_utils::hex_str(&chan_info.counterparty.node_id.serialize())
614 if let Some(node_info) = network_graph
617 .get(&NodeId::from_pubkey(&chan_info.counterparty.node_id))
619 if let Some(announcement) = &node_info.announcement_info {
620 println!("\t\tpeer_alias: {}", announcement.alias);
624 if let Some(id) = chan_info.short_channel_id {
625 println!("\t\tshort_channel_id: {},", id);
627 println!("\t\tis_channel_ready: {},", chan_info.is_channel_ready);
628 println!("\t\tchannel_value_satoshis: {},", chan_info.channel_value_satoshis);
629 println!("\t\toutbound_capacity_msat: {},", chan_info.outbound_capacity_msat);
630 if chan_info.is_usable {
631 println!("\t\tavailable_balance_for_send_msat: {},", chan_info.outbound_capacity_msat);
632 println!("\t\tavailable_balance_for_recv_msat: {},", chan_info.inbound_capacity_msat);
634 println!("\t\tchannel_can_send_payments: {},", chan_info.is_usable);
635 println!("\t\tpublic: {},", chan_info.is_public);
642 inbound_payments: &InboundPaymentInfoStorage, outbound_payments: &OutboundPaymentInfoStorage,
645 for (payment_hash, payment_info) in &inbound_payments.payments {
648 println!("\t\tamount_millisatoshis: {},", payment_info.amt_msat);
649 println!("\t\tpayment_hash: {},", payment_hash);
650 println!("\t\thtlc_direction: inbound,");
652 "\t\thtlc_status: {},",
653 match payment_info.status {
654 HTLCStatus::Pending => "pending",
655 HTLCStatus::Succeeded => "succeeded",
656 HTLCStatus::Failed => "failed",
663 for (payment_hash, payment_info) in &outbound_payments.payments {
666 println!("\t\tamount_millisatoshis: {},", payment_info.amt_msat);
667 println!("\t\tpayment_hash: {},", payment_hash);
668 println!("\t\thtlc_direction: outbound,");
670 "\t\thtlc_status: {},",
671 match payment_info.status {
672 HTLCStatus::Pending => "pending",
673 HTLCStatus::Succeeded => "succeeded",
674 HTLCStatus::Failed => "failed",
683 pub(crate) async fn connect_peer_if_necessary(
684 pubkey: PublicKey, peer_addr: SocketAddr, peer_manager: Arc<PeerManager>,
685 ) -> Result<(), ()> {
686 for (node_pubkey, _) in peer_manager.get_peer_node_ids() {
687 if node_pubkey == pubkey {
691 let res = do_connect_peer(pubkey, peer_addr, peer_manager).await;
693 println!("ERROR: failed to connect to peer");
698 pub(crate) async fn do_connect_peer(
699 pubkey: PublicKey, peer_addr: SocketAddr, peer_manager: Arc<PeerManager>,
700 ) -> Result<(), ()> {
701 match lightning_net_tokio::connect_outbound(Arc::clone(&peer_manager), pubkey, peer_addr).await
703 Some(connection_closed_future) => {
704 let mut connection_closed_future = Box::pin(connection_closed_future);
707 _ = &mut connection_closed_future => return Err(()),
708 _ = tokio::time::sleep(Duration::from_millis(10)) => {},
710 if peer_manager.get_peer_node_ids().iter().find(|(id, _)| *id == pubkey).is_some() {
719 fn do_disconnect_peer(
720 pubkey: bitcoin::secp256k1::PublicKey, peer_manager: Arc<PeerManager>,
721 channel_manager: Arc<ChannelManager>,
722 ) -> Result<(), ()> {
723 //check for open channels with peer
724 for channel in channel_manager.list_channels() {
725 if channel.counterparty.node_id == pubkey {
726 println!("Error: Node has an active channel with this peer, close any channels first");
731 //check the pubkey matches a valid connected peer
732 let peers = peer_manager.get_peer_node_ids();
733 if !peers.iter().any(|(pk, _)| &pubkey == pk) {
734 println!("Error: Could not find peer {}", pubkey);
738 peer_manager.disconnect_by_node_id(pubkey);
743 peer_pubkey: PublicKey, channel_amt_sat: u64, announced_channel: bool, with_anchors: bool,
744 channel_manager: Arc<ChannelManager>,
745 ) -> Result<(), ()> {
746 let config = UserConfig {
747 channel_handshake_limits: ChannelHandshakeLimits {
748 // lnd's max to_self_delay is 2016, so we want to be compatible.
749 their_to_self_delay: 2016,
752 channel_handshake_config: ChannelHandshakeConfig {
754 negotiate_anchors_zero_fee_htlc_tx: with_anchors,
760 match channel_manager.create_channel(peer_pubkey, channel_amt_sat, 0, 0, None, Some(config)) {
762 println!("EVENT: initiated channel with peer {}. ", peer_pubkey);
766 println!("ERROR: failed to open channel: {:?}", e);
773 channel_manager: &ChannelManager, invoice: &Bolt11Invoice,
774 outbound_payments: &mut OutboundPaymentInfoStorage, fs_store: Arc<FilesystemStore>,
776 let payment_id = PaymentId((*invoice.payment_hash()).to_byte_array());
777 let payment_secret = Some(*invoice.payment_secret());
778 let (payment_hash, recipient_onion, route_params) =
779 match payment_parameters_from_invoice(invoice) {
782 println!("Failed to parse invoice");
787 outbound_payments.payments.insert(
791 secret: payment_secret,
792 status: HTLCStatus::Pending,
793 amt_msat: MillisatAmount(invoice.amount_milli_satoshis()),
796 fs_store.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode()).unwrap();
798 match channel_manager.send_payment(
803 Retry::Timeout(Duration::from_secs(10)),
806 let payee_pubkey = invoice.recover_payee_pub_key();
807 let amt_msat = invoice.amount_milli_satoshis().unwrap();
808 println!("EVENT: initiated sending {} msats to {}", amt_msat, payee_pubkey);
812 println!("ERROR: failed to send payment: {:?}", e);
814 outbound_payments.payments.get_mut(&payment_id).unwrap().status = HTLCStatus::Failed;
815 fs_store.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode()).unwrap();
820 fn keysend<E: EntropySource>(
821 channel_manager: &ChannelManager, payee_pubkey: PublicKey, amt_msat: u64, entropy_source: &E,
822 outbound_payments: &mut OutboundPaymentInfoStorage, fs_store: Arc<FilesystemStore>,
824 let payment_preimage = PaymentPreimage(entropy_source.get_secure_random_bytes());
825 let payment_id = PaymentId(Sha256::hash(&payment_preimage.0[..]).to_byte_array());
827 let route_params = RouteParameters::from_payment_params_and_value(
828 PaymentParameters::for_keysend(payee_pubkey, 40, false),
831 outbound_payments.payments.insert(
836 status: HTLCStatus::Pending,
837 amt_msat: MillisatAmount(Some(amt_msat)),
840 fs_store.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode()).unwrap();
841 match channel_manager.send_spontaneous_payment_with_retry(
842 Some(payment_preimage),
843 RecipientOnionFields::spontaneous_empty(),
846 Retry::Timeout(Duration::from_secs(10)),
848 Ok(_payment_hash) => {
849 println!("EVENT: initiated sending {} msats to {}", amt_msat, payee_pubkey);
853 println!("ERROR: failed to send payment: {:?}", e);
855 outbound_payments.payments.get_mut(&payment_id).unwrap().status = HTLCStatus::Failed;
856 fs_store.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode()).unwrap();
862 amt_msat: u64, inbound_payments: &mut InboundPaymentInfoStorage,
863 channel_manager: &ChannelManager, keys_manager: Arc<KeysManager>, network: Network,
864 expiry_secs: u32, logger: Arc<disk::FilesystemLogger>,
866 let currency = match network {
867 Network::Bitcoin => Currency::Bitcoin,
868 Network::Regtest => Currency::Regtest,
869 Network::Signet => Currency::Signet,
870 Network::Testnet | _ => Currency::BitcoinTestnet,
872 let invoice = match utils::create_invoice_from_channelmanager(
878 "ldk-tutorial-node".to_string(),
883 println!("SUCCESS: generated invoice: {}", inv);
887 println!("ERROR: failed to create invoice: {:?}", e);
892 let payment_hash = PaymentHash(invoice.payment_hash().to_byte_array());
893 inbound_payments.payments.insert(
897 secret: Some(invoice.payment_secret().clone()),
898 status: HTLCStatus::Pending,
899 amt_msat: MillisatAmount(Some(amt_msat)),
905 channel_id: [u8; 32], counterparty_node_id: PublicKey, channel_manager: Arc<ChannelManager>,
907 match channel_manager.close_channel(&ChannelId(channel_id), &counterparty_node_id) {
908 Ok(()) => println!("EVENT: initiating channel close"),
909 Err(e) => println!("ERROR: failed to close channel: {:?}", e),
913 fn force_close_channel(
914 channel_id: [u8; 32], counterparty_node_id: PublicKey, channel_manager: Arc<ChannelManager>,
916 match channel_manager
917 .force_close_broadcasting_latest_txn(&ChannelId(channel_id), &counterparty_node_id)
919 Ok(()) => println!("EVENT: initiating channel force-close"),
920 Err(e) => println!("ERROR: failed to force-close channel: {:?}", e),
924 pub(crate) fn parse_peer_info(
925 peer_pubkey_and_ip_addr: String,
926 ) -> Result<(PublicKey, SocketAddr), std::io::Error> {
927 let mut pubkey_and_addr = peer_pubkey_and_ip_addr.split("@");
928 let pubkey = pubkey_and_addr.next();
929 let peer_addr_str = pubkey_and_addr.next();
930 if peer_addr_str.is_none() {
931 return Err(std::io::Error::new(
932 std::io::ErrorKind::Other,
933 "ERROR: incorrectly formatted peer info. Should be formatted as: `pubkey@host:port`",
937 let peer_addr = peer_addr_str.unwrap().to_socket_addrs().map(|mut r| r.next());
938 if peer_addr.is_err() || peer_addr.as_ref().unwrap().is_none() {
939 return Err(std::io::Error::new(
940 std::io::ErrorKind::Other,
941 "ERROR: couldn't parse pubkey@host:port into a socket address",
945 let pubkey = hex_utils::to_compressed_pubkey(pubkey.unwrap());
946 if pubkey.is_none() {
947 return Err(std::io::Error::new(
948 std::io::ErrorKind::Other,
949 "ERROR: unable to parse given pubkey for node",
953 Ok((pubkey.unwrap(), peer_addr.unwrap().unwrap()))