]> git.bitcoin.ninja Git - ldk-sample/blob - src/cli.rs
Correct logging on forwarded HTLCs
[ldk-sample] / src / cli.rs
1 use crate::disk;
2 use crate::hex_utils;
3 use crate::{
4         ChannelManager, HTLCStatus, InvoicePayer, MillisatAmount, NetworkGraph, PaymentInfo,
5         PaymentInfoStorage, PeerManager,
6 };
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::chain::keysinterface::{KeysInterface, KeysManager, Recipient};
12 use lightning::ln::msgs::NetAddress;
13 use lightning::ln::{PaymentHash, PaymentPreimage};
14 use lightning::routing::gossip::NodeId;
15 use lightning::util::config::{ChannelHandshakeConfig, ChannelHandshakeLimits, UserConfig};
16 use lightning::util::events::EventHandler;
17 use lightning_invoice::payment::PaymentError;
18 use lightning_invoice::{utils, Currency, Invoice};
19 use std::env;
20 use std::io;
21 use std::io::{BufRead, Write};
22 use std::net::{IpAddr, SocketAddr, ToSocketAddrs};
23 use std::ops::Deref;
24 use std::path::Path;
25 use std::str::FromStr;
26 use std::sync::Arc;
27 use std::time::Duration;
28
29 pub(crate) struct LdkUserInfo {
30         pub(crate) bitcoind_rpc_username: String,
31         pub(crate) bitcoind_rpc_password: String,
32         pub(crate) bitcoind_rpc_port: u16,
33         pub(crate) bitcoind_rpc_host: String,
34         pub(crate) ldk_storage_dir_path: String,
35         pub(crate) ldk_peer_listening_port: u16,
36         pub(crate) ldk_announced_listen_addr: Vec<NetAddress>,
37         pub(crate) ldk_announced_node_name: [u8; 32],
38         pub(crate) network: Network,
39 }
40
41 pub(crate) fn parse_startup_args() -> Result<LdkUserInfo, ()> {
42         if env::args().len() < 3 {
43                 println!("ldk-tutorial-node requires 3 arguments: `cargo run <bitcoind-rpc-username>:<bitcoind-rpc-password>@<bitcoind-rpc-host>:<bitcoind-rpc-port> ldk_storage_directory_path [<ldk-incoming-peer-listening-port>] [bitcoin-network] [announced-node-name announced-listen-addr*]`");
44                 return Err(());
45         }
46         let bitcoind_rpc_info = env::args().skip(1).next().unwrap();
47         let bitcoind_rpc_info_parts: Vec<&str> = bitcoind_rpc_info.rsplitn(2, "@").collect();
48         if bitcoind_rpc_info_parts.len() != 2 {
49                 println!("ERROR: bad bitcoind RPC URL provided");
50                 return Err(());
51         }
52         let rpc_user_and_password: Vec<&str> = bitcoind_rpc_info_parts[1].split(":").collect();
53         if rpc_user_and_password.len() != 2 {
54                 println!("ERROR: bad bitcoind RPC username/password combo provided");
55                 return Err(());
56         }
57         let bitcoind_rpc_username = rpc_user_and_password[0].to_string();
58         let bitcoind_rpc_password = rpc_user_and_password[1].to_string();
59         let bitcoind_rpc_path: Vec<&str> = bitcoind_rpc_info_parts[0].split(":").collect();
60         if bitcoind_rpc_path.len() != 2 {
61                 println!("ERROR: bad bitcoind RPC path provided");
62                 return Err(());
63         }
64         let bitcoind_rpc_host = bitcoind_rpc_path[0].to_string();
65         let bitcoind_rpc_port = bitcoind_rpc_path[1].parse::<u16>().unwrap();
66
67         let ldk_storage_dir_path = env::args().skip(2).next().unwrap();
68
69         let mut ldk_peer_port_set = true;
70         let ldk_peer_listening_port: u16 = match env::args().skip(3).next().map(|p| p.parse()) {
71                 Some(Ok(p)) => p,
72                 Some(Err(_)) => {
73                         ldk_peer_port_set = false;
74                         9735
75                 }
76                 None => {
77                         ldk_peer_port_set = false;
78                         9735
79                 }
80         };
81
82         let mut arg_idx = match ldk_peer_port_set {
83                 true => 4,
84                 false => 3,
85         };
86         let network: Network = match env::args().skip(arg_idx).next().as_ref().map(String::as_str) {
87                 Some("testnet") => Network::Testnet,
88                 Some("regtest") => Network::Regtest,
89                 Some("signet") => Network::Signet,
90                 Some(net) => {
91                         panic!("Unsupported network provided. Options are: `regtest`, `testnet`, and `signet`. Got {}", net);
92                 }
93                 None => Network::Testnet,
94         };
95
96         let ldk_announced_node_name = match env::args().skip(arg_idx + 1).next().as_ref() {
97                 Some(s) => {
98                         if s.len() > 32 {
99                                 panic!("Node Alias can not be longer than 32 bytes");
100                         }
101                         arg_idx += 1;
102                         let mut bytes = [0; 32];
103                         bytes[..s.len()].copy_from_slice(s.as_bytes());
104                         bytes
105                 }
106                 None => [0; 32],
107         };
108
109         let mut ldk_announced_listen_addr = Vec::new();
110         loop {
111                 match env::args().skip(arg_idx + 1).next().as_ref() {
112                         Some(s) => match IpAddr::from_str(s) {
113                                 Ok(IpAddr::V4(a)) => {
114                                         ldk_announced_listen_addr
115                                                 .push(NetAddress::IPv4 { addr: a.octets(), port: ldk_peer_listening_port });
116                                         arg_idx += 1;
117                                 }
118                                 Ok(IpAddr::V6(a)) => {
119                                         ldk_announced_listen_addr
120                                                 .push(NetAddress::IPv6 { addr: a.octets(), port: ldk_peer_listening_port });
121                                         arg_idx += 1;
122                                 }
123                                 Err(_) => panic!("Failed to parse announced-listen-addr into an IP address"),
124                         },
125                         None => break,
126                 }
127         }
128
129         Ok(LdkUserInfo {
130                 bitcoind_rpc_username,
131                 bitcoind_rpc_password,
132                 bitcoind_rpc_host,
133                 bitcoind_rpc_port,
134                 ldk_storage_dir_path,
135                 ldk_peer_listening_port,
136                 ldk_announced_listen_addr,
137                 ldk_announced_node_name,
138                 network,
139         })
140 }
141
142 pub(crate) async fn poll_for_user_input<E: EventHandler>(
143         invoice_payer: Arc<InvoicePayer<E>>, peer_manager: Arc<PeerManager>,
144         channel_manager: Arc<ChannelManager>, keys_manager: Arc<KeysManager>,
145         network_graph: Arc<NetworkGraph>, inbound_payments: PaymentInfoStorage,
146         outbound_payments: PaymentInfoStorage, ldk_data_dir: String, network: Network,
147 ) {
148         println!("LDK startup successful. To view available commands: \"help\".");
149         println!("LDK logs are available at <your-supplied-ldk-data-dir-path>/.ldk/logs");
150         println!("Local Node ID is {}.", channel_manager.get_our_node_id());
151         let stdin = io::stdin();
152         let mut line_reader = stdin.lock().lines();
153         loop {
154                 print!("> ");
155                 io::stdout().flush().unwrap(); // Without flushing, the `>` doesn't print
156                 let line = match line_reader.next() {
157                         Some(l) => l.unwrap(),
158                         None => break,
159                 };
160                 let mut words = line.split_whitespace();
161                 if let Some(word) = words.next() {
162                         match word {
163                                 "help" => help(),
164                                 "openchannel" => {
165                                         let peer_pubkey_and_ip_addr = words.next();
166                                         let channel_value_sat = words.next();
167                                         if peer_pubkey_and_ip_addr.is_none() || channel_value_sat.is_none() {
168                                                 println!("ERROR: openchannel has 2 required arguments: `openchannel pubkey@host:port channel_amt_satoshis` [--public]");
169                                                 continue;
170                                         }
171                                         let peer_pubkey_and_ip_addr = peer_pubkey_and_ip_addr.unwrap();
172                                         let (pubkey, peer_addr) =
173                                                 match parse_peer_info(peer_pubkey_and_ip_addr.to_string()) {
174                                                         Ok(info) => info,
175                                                         Err(e) => {
176                                                                 println!("{:?}", e.into_inner().unwrap());
177                                                                 continue;
178                                                         }
179                                                 };
180
181                                         let chan_amt_sat: Result<u64, _> = channel_value_sat.unwrap().parse();
182                                         if chan_amt_sat.is_err() {
183                                                 println!("ERROR: channel amount must be a number");
184                                                 continue;
185                                         }
186
187                                         if connect_peer_if_necessary(pubkey, peer_addr, peer_manager.clone())
188                                                 .await
189                                                 .is_err()
190                                         {
191                                                 continue;
192                                         };
193
194                                         let announce_channel = match words.next() {
195                                                 Some("--public") | Some("--public=true") => true,
196                                                 Some("--public=false") => false,
197                                                 Some(_) => {
198                                                         println!("ERROR: invalid `--public` command format. Valid formats: `--public`, `--public=true` `--public=false`");
199                                                         continue;
200                                                 }
201                                                 None => false,
202                                         };
203
204                                         if open_channel(
205                                                 pubkey,
206                                                 chan_amt_sat.unwrap(),
207                                                 announce_channel,
208                                                 channel_manager.clone(),
209                                         )
210                                         .is_ok()
211                                         {
212                                                 let peer_data_path = format!("{}/channel_peer_data", ldk_data_dir.clone());
213                                                 let _ = disk::persist_channel_peer(
214                                                         Path::new(&peer_data_path),
215                                                         peer_pubkey_and_ip_addr,
216                                                 );
217                                         }
218                                 }
219                                 "sendpayment" => {
220                                         let invoice_str = words.next();
221                                         if invoice_str.is_none() {
222                                                 println!("ERROR: sendpayment requires an invoice: `sendpayment <invoice>`");
223                                                 continue;
224                                         }
225
226                                         let invoice = match Invoice::from_str(invoice_str.unwrap()) {
227                                                 Ok(inv) => inv,
228                                                 Err(e) => {
229                                                         println!("ERROR: invalid invoice: {:?}", e);
230                                                         continue;
231                                                 }
232                                         };
233
234                                         send_payment(&*invoice_payer, &invoice, outbound_payments.clone());
235                                 }
236                                 "keysend" => {
237                                         let dest_pubkey = match words.next() {
238                                                 Some(dest) => match hex_utils::to_compressed_pubkey(dest) {
239                                                         Some(pk) => pk,
240                                                         None => {
241                                                                 println!("ERROR: couldn't parse destination pubkey");
242                                                                 continue;
243                                                         }
244                                                 },
245                                                 None => {
246                                                         println!("ERROR: keysend requires a destination pubkey: `keysend <dest_pubkey> <amt_msat>`");
247                                                         continue;
248                                                 }
249                                         };
250                                         let amt_msat_str = match words.next() {
251                                                 Some(amt) => amt,
252                                                 None => {
253                                                         println!("ERROR: keysend requires an amount in millisatoshis: `keysend <dest_pubkey> <amt_msat>`");
254                                                         continue;
255                                                 }
256                                         };
257                                         let amt_msat: u64 = match amt_msat_str.parse() {
258                                                 Ok(amt) => amt,
259                                                 Err(e) => {
260                                                         println!("ERROR: couldn't parse amount_msat: {}", e);
261                                                         continue;
262                                                 }
263                                         };
264                                         keysend(
265                                                 &*invoice_payer,
266                                                 dest_pubkey,
267                                                 amt_msat,
268                                                 &*keys_manager,
269                                                 outbound_payments.clone(),
270                                         );
271                                 }
272                                 "getinvoice" => {
273                                         let amt_str = words.next();
274                                         if amt_str.is_none() {
275                                                 println!("ERROR: getinvoice requires an amount in millisatoshis");
276                                                 continue;
277                                         }
278
279                                         let amt_msat: Result<u64, _> = amt_str.unwrap().parse();
280                                         if amt_msat.is_err() {
281                                                 println!("ERROR: getinvoice provided payment amount was not a number");
282                                                 continue;
283                                         }
284
285                                         let expiry_secs_str = words.next();
286                                         if expiry_secs_str.is_none() {
287                                                 println!("ERROR: getinvoice requires an expiry in seconds");
288                                                 continue;
289                                         }
290
291                                         let expiry_secs: Result<u32, _> = expiry_secs_str.unwrap().parse();
292                                         if expiry_secs.is_err() {
293                                                 println!("ERROR: getinvoice provided expiry was not a number");
294                                                 continue;
295                                         }
296
297                                         get_invoice(
298                                                 amt_msat.unwrap(),
299                                                 inbound_payments.clone(),
300                                                 channel_manager.clone(),
301                                                 keys_manager.clone(),
302                                                 network,
303                                                 expiry_secs.unwrap(),
304                                         );
305                                 }
306                                 "connectpeer" => {
307                                         let peer_pubkey_and_ip_addr = words.next();
308                                         if peer_pubkey_and_ip_addr.is_none() {
309                                                 println!("ERROR: connectpeer requires peer connection info: `connectpeer pubkey@host:port`");
310                                                 continue;
311                                         }
312                                         let (pubkey, peer_addr) =
313                                                 match parse_peer_info(peer_pubkey_and_ip_addr.unwrap().to_string()) {
314                                                         Ok(info) => info,
315                                                         Err(e) => {
316                                                                 println!("{:?}", e.into_inner().unwrap());
317                                                                 continue;
318                                                         }
319                                                 };
320                                         if connect_peer_if_necessary(pubkey, peer_addr, peer_manager.clone())
321                                                 .await
322                                                 .is_ok()
323                                         {
324                                                 println!("SUCCESS: connected to peer {}", pubkey);
325                                         }
326                                 }
327                                 "listchannels" => list_channels(&channel_manager, &network_graph),
328                                 "listpayments" => {
329                                         list_payments(inbound_payments.clone(), outbound_payments.clone())
330                                 }
331                                 "closechannel" => {
332                                         let channel_id_str = words.next();
333                                         if channel_id_str.is_none() {
334                                                 println!("ERROR: closechannel requires a channel ID: `closechannel <channel_id> <peer_pubkey>`");
335                                                 continue;
336                                         }
337                                         let channel_id_vec = hex_utils::to_vec(channel_id_str.unwrap());
338                                         if channel_id_vec.is_none() || channel_id_vec.as_ref().unwrap().len() != 32 {
339                                                 println!("ERROR: couldn't parse channel_id");
340                                                 continue;
341                                         }
342                                         let mut channel_id = [0; 32];
343                                         channel_id.copy_from_slice(&channel_id_vec.unwrap());
344
345                                         let peer_pubkey_str = words.next();
346                                         if peer_pubkey_str.is_none() {
347                                                 println!("ERROR: closechannel requires a peer pubkey: `closechannel <channel_id> <peer_pubkey>`");
348                                                 continue;
349                                         }
350                                         let peer_pubkey_vec = match hex_utils::to_vec(peer_pubkey_str.unwrap()) {
351                                                 Some(peer_pubkey_vec) => peer_pubkey_vec,
352                                                 None => {
353                                                         println!("ERROR: couldn't parse peer_pubkey");
354                                                         continue;
355                                                 }
356                                         };
357                                         let peer_pubkey = match PublicKey::from_slice(&peer_pubkey_vec) {
358                                                 Ok(peer_pubkey) => peer_pubkey,
359                                                 Err(_) => {
360                                                         println!("ERROR: couldn't parse peer_pubkey");
361                                                         continue;
362                                                 }
363                                         };
364
365                                         close_channel(channel_id, peer_pubkey, channel_manager.clone());
366                                 }
367                                 "forceclosechannel" => {
368                                         let channel_id_str = words.next();
369                                         if channel_id_str.is_none() {
370                                                 println!("ERROR: forceclosechannel requires a channel ID: `forceclosechannel <channel_id> <peer_pubkey>`");
371                                                 continue;
372                                         }
373                                         let channel_id_vec = hex_utils::to_vec(channel_id_str.unwrap());
374                                         if channel_id_vec.is_none() || channel_id_vec.as_ref().unwrap().len() != 32 {
375                                                 println!("ERROR: couldn't parse channel_id");
376                                                 continue;
377                                         }
378                                         let mut channel_id = [0; 32];
379                                         channel_id.copy_from_slice(&channel_id_vec.unwrap());
380
381                                         let peer_pubkey_str = words.next();
382                                         if peer_pubkey_str.is_none() {
383                                                 println!("ERROR: forceclosechannel requires a peer pubkey: `forceclosechannel <channel_id> <peer_pubkey>`");
384                                                 continue;
385                                         }
386                                         let peer_pubkey_vec = match hex_utils::to_vec(peer_pubkey_str.unwrap()) {
387                                                 Some(peer_pubkey_vec) => peer_pubkey_vec,
388                                                 None => {
389                                                         println!("ERROR: couldn't parse peer_pubkey");
390                                                         continue;
391                                                 }
392                                         };
393                                         let peer_pubkey = match PublicKey::from_slice(&peer_pubkey_vec) {
394                                                 Ok(peer_pubkey) => peer_pubkey,
395                                                 Err(_) => {
396                                                         println!("ERROR: couldn't parse peer_pubkey");
397                                                         continue;
398                                                 }
399                                         };
400
401                                         force_close_channel(channel_id, peer_pubkey, channel_manager.clone());
402                                 }
403                                 "nodeinfo" => node_info(&channel_manager, &peer_manager),
404                                 "listpeers" => list_peers(peer_manager.clone()),
405                                 "signmessage" => {
406                                         const MSG_STARTPOS: usize = "signmessage".len() + 1;
407                                         if line.as_bytes().len() <= MSG_STARTPOS {
408                                                 println!("ERROR: signmsg requires a message");
409                                                 continue;
410                                         }
411                                         println!(
412                                                 "{:?}",
413                                                 lightning::util::message_signing::sign(
414                                                         &line.as_bytes()[MSG_STARTPOS..],
415                                                         &keys_manager.get_node_secret(Recipient::Node).unwrap()
416                                                 )
417                                         );
418                                 }
419                                 _ => println!("Unknown command. See `\"help\" for available commands."),
420                         }
421                 }
422         }
423 }
424
425 fn help() {
426         println!("openchannel pubkey@host:port <amt_satoshis>");
427         println!("sendpayment <invoice>");
428         println!("keysend <dest_pubkey> <amt_msats>");
429         println!("getinvoice <amt_msats> <expiry_secs>");
430         println!("connectpeer pubkey@host:port");
431         println!("listchannels");
432         println!("listpayments");
433         println!("closechannel <channel_id> <peer_pubkey>");
434         println!("forceclosechannel <channel_id> <peer_pubkey>");
435         println!("nodeinfo");
436         println!("listpeers");
437         println!("signmessage <message>");
438 }
439
440 fn node_info(channel_manager: &Arc<ChannelManager>, peer_manager: &Arc<PeerManager>) {
441         println!("\t{{");
442         println!("\t\t node_pubkey: {}", channel_manager.get_our_node_id());
443         let chans = channel_manager.list_channels();
444         println!("\t\t num_channels: {}", chans.len());
445         println!("\t\t num_usable_channels: {}", chans.iter().filter(|c| c.is_usable).count());
446         let local_balance_msat = chans.iter().map(|c| c.balance_msat).sum::<u64>();
447         println!("\t\t local_balance_msat: {}", local_balance_msat);
448         println!("\t\t num_peers: {}", peer_manager.get_peer_node_ids().len());
449         println!("\t}},");
450 }
451
452 fn list_peers(peer_manager: Arc<PeerManager>) {
453         println!("\t{{");
454         for pubkey in peer_manager.get_peer_node_ids() {
455                 println!("\t\t pubkey: {}", pubkey);
456         }
457         println!("\t}},");
458 }
459
460 fn list_channels(channel_manager: &Arc<ChannelManager>, network_graph: &Arc<NetworkGraph>) {
461         print!("[");
462         for chan_info in channel_manager.list_channels() {
463                 println!("");
464                 println!("\t{{");
465                 println!("\t\tchannel_id: {},", hex_utils::hex_str(&chan_info.channel_id[..]));
466                 if let Some(funding_txo) = chan_info.funding_txo {
467                         println!("\t\tfunding_txid: {},", funding_txo.txid);
468                 }
469
470                 println!(
471                         "\t\tpeer_pubkey: {},",
472                         hex_utils::hex_str(&chan_info.counterparty.node_id.serialize())
473                 );
474                 if let Some(node_info) = network_graph
475                         .read_only()
476                         .nodes()
477                         .get(&NodeId::from_pubkey(&chan_info.counterparty.node_id))
478                 {
479                         if let Some(announcement) = &node_info.announcement_info {
480                                 println!("\t\tpeer_alias: {}", announcement.alias);
481                         }
482                 }
483
484                 if let Some(id) = chan_info.short_channel_id {
485                         println!("\t\tshort_channel_id: {},", id);
486                 }
487                 println!("\t\tis_channel_ready: {},", chan_info.is_channel_ready);
488                 println!("\t\tchannel_value_satoshis: {},", chan_info.channel_value_satoshis);
489                 println!("\t\tlocal_balance_msat: {},", chan_info.balance_msat);
490                 if chan_info.is_usable {
491                         println!("\t\tavailable_balance_for_send_msat: {},", chan_info.outbound_capacity_msat);
492                         println!("\t\tavailable_balance_for_recv_msat: {},", chan_info.inbound_capacity_msat);
493                 }
494                 println!("\t\tchannel_can_send_payments: {},", chan_info.is_usable);
495                 println!("\t\tpublic: {},", chan_info.is_public);
496                 println!("\t}},");
497         }
498         println!("]");
499 }
500
501 fn list_payments(inbound_payments: PaymentInfoStorage, outbound_payments: PaymentInfoStorage) {
502         let inbound = inbound_payments.lock().unwrap();
503         let outbound = outbound_payments.lock().unwrap();
504         print!("[");
505         for (payment_hash, payment_info) in inbound.deref() {
506                 println!("");
507                 println!("\t{{");
508                 println!("\t\tamount_millisatoshis: {},", payment_info.amt_msat);
509                 println!("\t\tpayment_hash: {},", hex_utils::hex_str(&payment_hash.0));
510                 println!("\t\thtlc_direction: inbound,");
511                 println!(
512                         "\t\thtlc_status: {},",
513                         match payment_info.status {
514                                 HTLCStatus::Pending => "pending",
515                                 HTLCStatus::Succeeded => "succeeded",
516                                 HTLCStatus::Failed => "failed",
517                         }
518                 );
519
520                 println!("\t}},");
521         }
522
523         for (payment_hash, payment_info) in outbound.deref() {
524                 println!("");
525                 println!("\t{{");
526                 println!("\t\tamount_millisatoshis: {},", payment_info.amt_msat);
527                 println!("\t\tpayment_hash: {},", hex_utils::hex_str(&payment_hash.0));
528                 println!("\t\thtlc_direction: outbound,");
529                 println!(
530                         "\t\thtlc_status: {},",
531                         match payment_info.status {
532                                 HTLCStatus::Pending => "pending",
533                                 HTLCStatus::Succeeded => "succeeded",
534                                 HTLCStatus::Failed => "failed",
535                         }
536                 );
537
538                 println!("\t}},");
539         }
540         println!("]");
541 }
542
543 pub(crate) async fn connect_peer_if_necessary(
544         pubkey: PublicKey, peer_addr: SocketAddr, peer_manager: Arc<PeerManager>,
545 ) -> Result<(), ()> {
546         for node_pubkey in peer_manager.get_peer_node_ids() {
547                 if node_pubkey == pubkey {
548                         return Ok(());
549                 }
550         }
551         let res = do_connect_peer(pubkey, peer_addr, peer_manager).await;
552         if res.is_err() {
553                 println!("ERROR: failed to connect to peer");
554         }
555         res
556 }
557
558 pub(crate) async fn do_connect_peer(
559         pubkey: PublicKey, peer_addr: SocketAddr, peer_manager: Arc<PeerManager>,
560 ) -> Result<(), ()> {
561         match lightning_net_tokio::connect_outbound(Arc::clone(&peer_manager), pubkey, peer_addr).await
562         {
563                 Some(connection_closed_future) => {
564                         let mut connection_closed_future = Box::pin(connection_closed_future);
565                         loop {
566                                 match futures::poll!(&mut connection_closed_future) {
567                                         std::task::Poll::Ready(_) => {
568                                                 return Err(());
569                                         }
570                                         std::task::Poll::Pending => {}
571                                 }
572                                 // Avoid blocking the tokio context by sleeping a bit
573                                 match peer_manager.get_peer_node_ids().iter().find(|id| **id == pubkey) {
574                                         Some(_) => return Ok(()),
575                                         None => tokio::time::sleep(Duration::from_millis(10)).await,
576                                 }
577                         }
578                 }
579                 None => Err(()),
580         }
581 }
582
583 fn open_channel(
584         peer_pubkey: PublicKey, channel_amt_sat: u64, announced_channel: bool,
585         channel_manager: Arc<ChannelManager>,
586 ) -> Result<(), ()> {
587         let config = UserConfig {
588                 channel_handshake_limits: ChannelHandshakeLimits {
589                         // lnd's max to_self_delay is 2016, so we want to be compatible.
590                         their_to_self_delay: 2016,
591                         ..Default::default()
592                 },
593                 channel_handshake_config: ChannelHandshakeConfig {
594                         announced_channel,
595                         ..Default::default()
596                 },
597                 ..Default::default()
598         };
599
600         match channel_manager.create_channel(peer_pubkey, channel_amt_sat, 0, 0, Some(config)) {
601                 Ok(_) => {
602                         println!("EVENT: initiated channel with peer {}. ", peer_pubkey);
603                         return Ok(());
604                 }
605                 Err(e) => {
606                         println!("ERROR: failed to open channel: {:?}", e);
607                         return Err(());
608                 }
609         }
610 }
611
612 fn send_payment<E: EventHandler>(
613         invoice_payer: &InvoicePayer<E>, invoice: &Invoice, payment_storage: PaymentInfoStorage,
614 ) {
615         let status = match invoice_payer.pay_invoice(invoice) {
616                 Ok(_payment_id) => {
617                         let payee_pubkey = invoice.recover_payee_pub_key();
618                         let amt_msat = invoice.amount_milli_satoshis().unwrap();
619                         println!("EVENT: initiated sending {} msats to {}", amt_msat, payee_pubkey);
620                         print!("> ");
621                         HTLCStatus::Pending
622                 }
623                 Err(PaymentError::Invoice(e)) => {
624                         println!("ERROR: invalid invoice: {}", e);
625                         print!("> ");
626                         return;
627                 }
628                 Err(PaymentError::Routing(e)) => {
629                         println!("ERROR: failed to find route: {}", e.err);
630                         print!("> ");
631                         return;
632                 }
633                 Err(PaymentError::Sending(e)) => {
634                         println!("ERROR: failed to send payment: {:?}", e);
635                         print!("> ");
636                         HTLCStatus::Failed
637                 }
638         };
639         let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
640         let payment_secret = Some(invoice.payment_secret().clone());
641
642         let mut payments = payment_storage.lock().unwrap();
643         payments.insert(
644                 payment_hash,
645                 PaymentInfo {
646                         preimage: None,
647                         secret: payment_secret,
648                         status,
649                         amt_msat: MillisatAmount(invoice.amount_milli_satoshis()),
650                 },
651         );
652 }
653
654 fn keysend<E: EventHandler, K: KeysInterface>(
655         invoice_payer: &InvoicePayer<E>, payee_pubkey: PublicKey, amt_msat: u64, keys: &K,
656         payment_storage: PaymentInfoStorage,
657 ) {
658         let payment_preimage = keys.get_secure_random_bytes();
659
660         let status = match invoice_payer.pay_pubkey(
661                 payee_pubkey,
662                 PaymentPreimage(payment_preimage),
663                 amt_msat,
664                 40,
665         ) {
666                 Ok(_payment_id) => {
667                         println!("EVENT: initiated sending {} msats to {}", amt_msat, payee_pubkey);
668                         print!("> ");
669                         HTLCStatus::Pending
670                 }
671                 Err(PaymentError::Invoice(e)) => {
672                         println!("ERROR: invalid payee: {}", e);
673                         print!("> ");
674                         return;
675                 }
676                 Err(PaymentError::Routing(e)) => {
677                         println!("ERROR: failed to find route: {}", e.err);
678                         print!("> ");
679                         return;
680                 }
681                 Err(PaymentError::Sending(e)) => {
682                         println!("ERROR: failed to send payment: {:?}", e);
683                         print!("> ");
684                         HTLCStatus::Failed
685                 }
686         };
687
688         let mut payments = payment_storage.lock().unwrap();
689         payments.insert(
690                 PaymentHash(Sha256::hash(&payment_preimage).into_inner()),
691                 PaymentInfo {
692                         preimage: None,
693                         secret: None,
694                         status,
695                         amt_msat: MillisatAmount(Some(amt_msat)),
696                 },
697         );
698 }
699
700 fn get_invoice(
701         amt_msat: u64, payment_storage: PaymentInfoStorage, channel_manager: Arc<ChannelManager>,
702         keys_manager: Arc<KeysManager>, network: Network, expiry_secs: u32,
703 ) {
704         let mut payments = payment_storage.lock().unwrap();
705         let currency = match network {
706                 Network::Bitcoin => Currency::Bitcoin,
707                 Network::Testnet => Currency::BitcoinTestnet,
708                 Network::Regtest => Currency::Regtest,
709                 Network::Signet => Currency::Signet,
710         };
711         let invoice = match utils::create_invoice_from_channelmanager(
712                 &channel_manager,
713                 keys_manager,
714                 currency,
715                 Some(amt_msat),
716                 "ldk-tutorial-node".to_string(),
717                 expiry_secs,
718         ) {
719                 Ok(inv) => {
720                         println!("SUCCESS: generated invoice: {}", inv);
721                         inv
722                 }
723                 Err(e) => {
724                         println!("ERROR: failed to create invoice: {:?}", e);
725                         return;
726                 }
727         };
728
729         let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
730         payments.insert(
731                 payment_hash,
732                 PaymentInfo {
733                         preimage: None,
734                         secret: Some(invoice.payment_secret().clone()),
735                         status: HTLCStatus::Pending,
736                         amt_msat: MillisatAmount(Some(amt_msat)),
737                 },
738         );
739 }
740
741 fn close_channel(
742         channel_id: [u8; 32], counterparty_node_id: PublicKey, channel_manager: Arc<ChannelManager>,
743 ) {
744         match channel_manager.close_channel(&channel_id, &counterparty_node_id) {
745                 Ok(()) => println!("EVENT: initiating channel close"),
746                 Err(e) => println!("ERROR: failed to close channel: {:?}", e),
747         }
748 }
749
750 fn force_close_channel(
751         channel_id: [u8; 32], counterparty_node_id: PublicKey, channel_manager: Arc<ChannelManager>,
752 ) {
753         match channel_manager.force_close_broadcasting_latest_txn(&channel_id, &counterparty_node_id) {
754                 Ok(()) => println!("EVENT: initiating channel force-close"),
755                 Err(e) => println!("ERROR: failed to force-close channel: {:?}", e),
756         }
757 }
758
759 pub(crate) fn parse_peer_info(
760         peer_pubkey_and_ip_addr: String,
761 ) -> Result<(PublicKey, SocketAddr), std::io::Error> {
762         let mut pubkey_and_addr = peer_pubkey_and_ip_addr.split("@");
763         let pubkey = pubkey_and_addr.next();
764         let peer_addr_str = pubkey_and_addr.next();
765         if peer_addr_str.is_none() || peer_addr_str.is_none() {
766                 return Err(std::io::Error::new(
767                         std::io::ErrorKind::Other,
768                         "ERROR: incorrectly formatted peer info. Should be formatted as: `pubkey@host:port`",
769                 ));
770         }
771
772         let peer_addr = peer_addr_str.unwrap().to_socket_addrs().map(|mut r| r.next());
773         if peer_addr.is_err() || peer_addr.as_ref().unwrap().is_none() {
774                 return Err(std::io::Error::new(
775                         std::io::ErrorKind::Other,
776                         "ERROR: couldn't parse pubkey@host:port into a socket address",
777                 ));
778         }
779
780         let pubkey = hex_utils::to_compressed_pubkey(pubkey.unwrap());
781         if pubkey.is_none() {
782                 return Err(std::io::Error::new(
783                         std::io::ErrorKind::Other,
784                         "ERROR: unable to parse given pubkey for node",
785                 ));
786         }
787
788         Ok((pubkey.unwrap(), peer_addr.unwrap().unwrap()))
789 }