72cc484220d818e8cd2a54e4cdd9537dc6383648
[ldk-sample] / src / cli.rs
1 use crate::disk::{self, INBOUND_PAYMENTS_FNAME, OUTBOUND_PAYMENTS_FNAME};
2 use crate::hex_utils;
3 use crate::{
4         ChannelManager, HTLCStatus, InboundPaymentInfoStorage, MillisatAmount, NetworkGraph,
5         OnionMessenger, OutboundPaymentInfoStorage, PaymentInfo, 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::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;
26 use std::env;
27 use std::io;
28 use std::io::Write;
29 use std::net::{SocketAddr, ToSocketAddrs};
30 use std::path::Path;
31 use std::str::FromStr;
32 use std::sync::{Arc, Mutex};
33 use std::time::Duration;
34
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,
45 }
46
47 #[derive(Debug)]
48 struct UserOnionMessageContents {
49         tlv_type: u64,
50         data: Vec<u8>,
51 }
52
53 impl OnionMessageContents for UserOnionMessageContents {
54         fn tlv_type(&self) -> u64 {
55                 self.tlv_type
56         }
57 }
58
59 impl Writeable for UserOnionMessageContents {
60         fn write<W: Writer>(&self, w: &mut W) -> Result<(), std::io::Error> {
61                 w.write_all(&self.data)
62         }
63 }
64
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>,
71 ) {
72         println!(
73                 "LDK startup successful. Enter \"help\" to view available commands. Press Ctrl-D to quit."
74         );
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());
77         'read_command: loop {
78                 print!("> ");
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);
83                 }
84
85                 if line.len() == 0 {
86                         // We hit EOF / Ctrl-D
87                         break;
88                 }
89
90                 let mut words = line.split_whitespace();
91                 if let Some(word) = words.next() {
92                         match word {
93                                 "help" => help(),
94                                 "openchannel" => {
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]");
99                                                 continue;
100                                         }
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()) {
104                                                         Ok(info) => info,
105                                                         Err(e) => {
106                                                                 println!("{:?}", e.into_inner().unwrap());
107                                                                 continue;
108                                                         }
109                                                 };
110
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");
114                                                 continue;
115                                         }
116
117                                         if tokio::runtime::Handle::current()
118                                                 .block_on(connect_peer_if_necessary(
119                                                         pubkey,
120                                                         peer_addr,
121                                                         peer_manager.clone(),
122                                                 ))
123                                                 .is_err()
124                                         {
125                                                 continue;
126                                         };
127
128                                         let (mut announce_channel, mut with_anchors) = (false, false);
129                                         while let Some(word) = words.next() {
130                                                 match word {
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,
135                                                         _ => {
136                                                                 println!("ERROR: invalid boolean flag format. Valid formats: `--option`, `--option=true` `--option=false`");
137                                                                 continue;
138                                                         }
139                                                 }
140                                         }
141
142                                         if open_channel(
143                                                 pubkey,
144                                                 chan_amt_sat.unwrap(),
145                                                 announce_channel,
146                                                 with_anchors,
147                                                 channel_manager.clone(),
148                                         )
149                                         .is_ok()
150                                         {
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,
155                                                 );
156                                         }
157                                 }
158                                 "sendpayment" => {
159                                         let invoice_str = words.next();
160                                         if invoice_str.is_none() {
161                                                 println!("ERROR: sendpayment requires an invoice: `sendpayment <invoice>`");
162                                                 continue;
163                                         }
164
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());
168
169                                                 let amt_msat =
170                                                         match offer.amount() {
171                                                                 Some(offer::Amount::Bitcoin { amount_msats }) => *amount_msats,
172                                                                 amt => {
173                                                                         println!("ERROR: Cannot process non-Bitcoin-denominated offer value {:?}", amt);
174                                                                         continue;
175                                                                 }
176                                                         };
177
178                                                 loop {
179                                                         print!("Paying offer for {} msat. Continue (Y/N)? >", amt_msat);
180                                                         io::stdout().flush().unwrap();
181
182                                                         if let Err(e) = io::stdin().read_line(&mut line) {
183                                                                 println!("ERROR: {}", e);
184                                                                 break 'read_command;
185                                                         }
186
187                                                         if line.len() == 0 {
188                                                                 // We hit EOF / Ctrl-D
189                                                                 break 'read_command;
190                                                         }
191
192                                                         if line.starts_with("Y") {
193                                                                 break;
194                                                         }
195                                                         if line.starts_with("N") {
196                                                                 continue 'read_command;
197                                                         }
198                                                 }
199
200                                                 outbound_payments.lock().unwrap().payments.insert(
201                                                         payment_id,
202                                                         PaymentInfo {
203                                                                 preimage: None,
204                                                                 secret: None,
205                                                                 status: HTLCStatus::Pending,
206                                                                 amt_msat: MillisatAmount(Some(amt_msat)),
207                                                         },
208                                                 );
209                                                 fs_store
210                                                         .write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode())
211                                                         .unwrap();
212
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);
216                                                 if pay.is_err() {
217                                                         println!("ERROR: Failed to pay: {:?}", pay);
218                                                 }
219                                         } else {
220                                                 match Bolt11Invoice::from_str(invoice_str.unwrap()) {
221                                                         Ok(invoice) => send_payment(
222                                                                 &channel_manager,
223                                                                 &invoice,
224                                                                 &mut outbound_payments.lock().unwrap(),
225                                                                 Arc::clone(&fs_store),
226                                                         ),
227                                                         Err(e) => {
228                                                                 println!("ERROR: invalid invoice: {:?}", e);
229                                                         }
230                                                 }
231                                         }
232                                 }
233                                 "keysend" => {
234                                         let dest_pubkey = match words.next() {
235                                                 Some(dest) => match hex_utils::to_compressed_pubkey(dest) {
236                                                         Some(pk) => pk,
237                                                         None => {
238                                                                 println!("ERROR: couldn't parse destination pubkey");
239                                                                 continue;
240                                                         }
241                                                 },
242                                                 None => {
243                                                         println!("ERROR: keysend requires a destination pubkey: `keysend <dest_pubkey> <amt_msat>`");
244                                                         continue;
245                                                 }
246                                         };
247                                         let amt_msat_str = match words.next() {
248                                                 Some(amt) => amt,
249                                                 None => {
250                                                         println!("ERROR: keysend requires an amount in millisatoshis: `keysend <dest_pubkey> <amt_msat>`");
251                                                         continue;
252                                                 }
253                                         };
254                                         let amt_msat: u64 = match amt_msat_str.parse() {
255                                                 Ok(amt) => amt,
256                                                 Err(e) => {
257                                                         println!("ERROR: couldn't parse amount_msat: {}", e);
258                                                         continue;
259                                                 }
260                                         };
261                                         keysend(
262                                                 &channel_manager,
263                                                 dest_pubkey,
264                                                 amt_msat,
265                                                 &*keys_manager,
266                                                 &mut outbound_payments.lock().unwrap(),
267                                                 Arc::clone(&fs_store),
268                                         );
269                                 }
270                                 "getoffer" => {
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);
274                                                 continue;
275                                         }
276
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");
282                                                         continue;
283                                                 }
284                                                 offer_builder.unwrap().amount_msats(amt_msat.unwrap()).build()
285                                         } else {
286                                                 offer_builder.unwrap().build()
287                                         };
288
289                                         if offer.is_err() {
290                                                 println!("ERROR: Failed to build offer: {:?}", offer.unwrap_err());
291                                         } else {
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());
296                                         }
297                                 }
298                                 "getinvoice" => {
299                                         let amt_str = words.next();
300                                         if amt_str.is_none() {
301                                                 println!("ERROR: getinvoice requires an amount in millisatoshis");
302                                                 continue;
303                                         }
304
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");
308                                                 continue;
309                                         }
310
311                                         let expiry_secs_str = words.next();
312                                         if expiry_secs_str.is_none() {
313                                                 println!("ERROR: getinvoice requires an expiry in seconds");
314                                                 continue;
315                                         }
316
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");
320                                                 continue;
321                                         }
322
323                                         let mut inbound_payments = inbound_payments.lock().unwrap();
324                                         get_invoice(
325                                                 amt_msat.unwrap(),
326                                                 &mut inbound_payments,
327                                                 &channel_manager,
328                                                 Arc::clone(&keys_manager),
329                                                 network,
330                                                 expiry_secs.unwrap(),
331                                                 Arc::clone(&logger),
332                                         );
333                                         fs_store
334                                                 .write("", "", INBOUND_PAYMENTS_FNAME, &inbound_payments.encode())
335                                                 .unwrap();
336                                 }
337                                 "connectpeer" => {
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`");
341                                                 continue;
342                                         }
343                                         let (pubkey, peer_addr) =
344                                                 match parse_peer_info(peer_pubkey_and_ip_addr.unwrap().to_string()) {
345                                                         Ok(info) => info,
346                                                         Err(e) => {
347                                                                 println!("{:?}", e.into_inner().unwrap());
348                                                                 continue;
349                                                         }
350                                                 };
351                                         if tokio::runtime::Handle::current()
352                                                 .block_on(connect_peer_if_necessary(
353                                                         pubkey,
354                                                         peer_addr,
355                                                         peer_manager.clone(),
356                                                 ))
357                                                 .is_ok()
358                                         {
359                                                 println!("SUCCESS: connected to peer {}", pubkey);
360                                         }
361                                 }
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>`");
366                                                 continue;
367                                         }
368
369                                         let peer_pubkey =
370                                                 match bitcoin::secp256k1::PublicKey::from_str(peer_pubkey.unwrap()) {
371                                                         Ok(pubkey) => pubkey,
372                                                         Err(e) => {
373                                                                 println!("ERROR: {}", e.to_string());
374                                                                 continue;
375                                                         }
376                                                 };
377
378                                         if do_disconnect_peer(
379                                                 peer_pubkey,
380                                                 peer_manager.clone(),
381                                                 channel_manager.clone(),
382                                         )
383                                         .is_ok()
384                                         {
385                                                 println!("SUCCESS: disconnected from peer {}", peer_pubkey);
386                                         }
387                                 }
388                                 "listchannels" => list_channels(&channel_manager, &network_graph),
389                                 "listpayments" => list_payments(
390                                         &inbound_payments.lock().unwrap(),
391                                         &outbound_payments.lock().unwrap(),
392                                 ),
393                                 "closechannel" => {
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>`");
397                                                 continue;
398                                         }
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");
402                                                 continue;
403                                         }
404                                         let mut channel_id = [0; 32];
405                                         channel_id.copy_from_slice(&channel_id_vec.unwrap());
406
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>`");
410                                                 continue;
411                                         }
412                                         let peer_pubkey_vec = match hex_utils::to_vec(peer_pubkey_str.unwrap()) {
413                                                 Some(peer_pubkey_vec) => peer_pubkey_vec,
414                                                 None => {
415                                                         println!("ERROR: couldn't parse peer_pubkey");
416                                                         continue;
417                                                 }
418                                         };
419                                         let peer_pubkey = match PublicKey::from_slice(&peer_pubkey_vec) {
420                                                 Ok(peer_pubkey) => peer_pubkey,
421                                                 Err(_) => {
422                                                         println!("ERROR: couldn't parse peer_pubkey");
423                                                         continue;
424                                                 }
425                                         };
426
427                                         close_channel(channel_id, peer_pubkey, channel_manager.clone());
428                                 }
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>`");
433                                                 continue;
434                                         }
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");
438                                                 continue;
439                                         }
440                                         let mut channel_id = [0; 32];
441                                         channel_id.copy_from_slice(&channel_id_vec.unwrap());
442
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>`");
446                                                 continue;
447                                         }
448                                         let peer_pubkey_vec = match hex_utils::to_vec(peer_pubkey_str.unwrap()) {
449                                                 Some(peer_pubkey_vec) => peer_pubkey_vec,
450                                                 None => {
451                                                         println!("ERROR: couldn't parse peer_pubkey");
452                                                         continue;
453                                                 }
454                                         };
455                                         let peer_pubkey = match PublicKey::from_slice(&peer_pubkey_vec) {
456                                                 Ok(peer_pubkey) => peer_pubkey,
457                                                 Err(_) => {
458                                                         println!("ERROR: couldn't parse peer_pubkey");
459                                                         continue;
460                                                 }
461                                         };
462
463                                         force_close_channel(channel_id, peer_pubkey, channel_manager.clone());
464                                 }
465                                 "nodeinfo" => node_info(&channel_manager, &peer_manager),
466                                 "listpeers" => list_peers(peer_manager.clone()),
467                                 "signmessage" => {
468                                         const MSG_STARTPOS: usize = "signmessage".len() + 1;
469                                         if line.trim().as_bytes().len() <= MSG_STARTPOS {
470                                                 println!("ERROR: signmsg requires a message");
471                                                 continue;
472                                         }
473                                         println!(
474                                                 "{:?}",
475                                                 lightning::util::message_signing::sign(
476                                                         &line.trim().as_bytes()[MSG_STARTPOS..],
477                                                         &keys_manager.get_node_secret_key()
478                                                 )
479                                         );
480                                 }
481                                 "sendonionmessage" => {
482                                         let path_pks_str = words.next();
483                                         if path_pks_str.is_none() {
484                                                 println!(
485                                                         "ERROR: sendonionmessage requires at least one node id for the path"
486                                                 );
487                                                 continue;
488                                         }
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,
494                                                         None => {
495                                                                 println!("ERROR: couldn't parse peer_pubkey");
496                                                                 errored = true;
497                                                                 break;
498                                                         }
499                                                 };
500                                                 let node_pubkey = match PublicKey::from_slice(&node_pubkey_vec) {
501                                                         Ok(peer_pubkey) => peer_pubkey,
502                                                         Err(_) => {
503                                                                 println!("ERROR: couldn't parse peer_pubkey");
504                                                                 errored = true;
505                                                                 break;
506                                                         }
507                                                 };
508                                                 intermediate_nodes.push(node_pubkey);
509                                         }
510                                         if errored {
511                                                 continue;
512                                         }
513                                         let tlv_type = match words.next().map(|ty_str| ty_str.parse()) {
514                                                 Some(Ok(ty)) if ty >= 64 => ty,
515                                                 _ => {
516                                                         println!("Need an integral message type above 64");
517                                                         continue;
518                                                 }
519                                         };
520                                         let data = match words.next().map(|s| hex_utils::to_vec(s)) {
521                                                 Some(Some(data)) => data,
522                                                 _ => {
523                                                         println!("Need a hex data string");
524                                                         continue;
525                                                 }
526                                         };
527                                         let destination = Destination::Node(intermediate_nodes.pop().unwrap());
528                                         match onion_messenger.send_onion_message(
529                                                 UserOnionMessageContents { tlv_type, data },
530                                                 destination,
531                                                 None,
532                                         ) {
533                                                 Ok(success) => {
534                                                         println!("SUCCESS: forwarded onion message to first hop {:?}", success)
535                                                 }
536                                                 Err(e) => println!("ERROR: failed to send onion message: {:?}", e),
537                                         }
538                                 }
539                                 "quit" | "exit" => break,
540                                 _ => println!("Unknown command. See `\"help\" for available commands."),
541                         }
542                 }
543         }
544 }
545
546 fn help() {
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>");
574         println!(
575                 "      sendonionmessage <node_id_1,node_id_2,..,destination_node_id> <type> <hex_bytes>"
576         );
577         println!("      nodeinfo");
578 }
579
580 fn node_info(channel_manager: &Arc<ChannelManager>, peer_manager: &Arc<PeerManager>) {
581         println!("\t{{");
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());
589         println!("\t}},");
590 }
591
592 fn list_peers(peer_manager: Arc<PeerManager>) {
593         println!("\t{{");
594         for (pubkey, _) in peer_manager.get_peer_node_ids() {
595                 println!("\t\t pubkey: {}", pubkey);
596         }
597         println!("\t}},");
598 }
599
600 fn list_channels(channel_manager: &Arc<ChannelManager>, network_graph: &Arc<NetworkGraph>) {
601         print!("[");
602         for chan_info in channel_manager.list_channels() {
603                 println!("");
604                 println!("\t{{");
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);
608                 }
609
610                 println!(
611                         "\t\tpeer_pubkey: {},",
612                         hex_utils::hex_str(&chan_info.counterparty.node_id.serialize())
613                 );
614                 if let Some(node_info) = network_graph
615                         .read_only()
616                         .nodes()
617                         .get(&NodeId::from_pubkey(&chan_info.counterparty.node_id))
618                 {
619                         if let Some(announcement) = &node_info.announcement_info {
620                                 println!("\t\tpeer_alias: {}", announcement.alias);
621                         }
622                 }
623
624                 if let Some(id) = chan_info.short_channel_id {
625                         println!("\t\tshort_channel_id: {},", id);
626                 }
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);
633                 }
634                 println!("\t\tchannel_can_send_payments: {},", chan_info.is_usable);
635                 println!("\t\tpublic: {},", chan_info.is_public);
636                 println!("\t}},");
637         }
638         println!("]");
639 }
640
641 fn list_payments(
642         inbound_payments: &InboundPaymentInfoStorage, outbound_payments: &OutboundPaymentInfoStorage,
643 ) {
644         print!("[");
645         for (payment_hash, payment_info) in &inbound_payments.payments {
646                 println!("");
647                 println!("\t{{");
648                 println!("\t\tamount_millisatoshis: {},", payment_info.amt_msat);
649                 println!("\t\tpayment_hash: {},", payment_hash);
650                 println!("\t\thtlc_direction: inbound,");
651                 println!(
652                         "\t\thtlc_status: {},",
653                         match payment_info.status {
654                                 HTLCStatus::Pending => "pending",
655                                 HTLCStatus::Succeeded => "succeeded",
656                                 HTLCStatus::Failed => "failed",
657                         }
658                 );
659
660                 println!("\t}},");
661         }
662
663         for (payment_hash, payment_info) in &outbound_payments.payments {
664                 println!("");
665                 println!("\t{{");
666                 println!("\t\tamount_millisatoshis: {},", payment_info.amt_msat);
667                 println!("\t\tpayment_hash: {},", payment_hash);
668                 println!("\t\thtlc_direction: outbound,");
669                 println!(
670                         "\t\thtlc_status: {},",
671                         match payment_info.status {
672                                 HTLCStatus::Pending => "pending",
673                                 HTLCStatus::Succeeded => "succeeded",
674                                 HTLCStatus::Failed => "failed",
675                         }
676                 );
677
678                 println!("\t}},");
679         }
680         println!("]");
681 }
682
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 {
688                         return Ok(());
689                 }
690         }
691         let res = do_connect_peer(pubkey, peer_addr, peer_manager).await;
692         if res.is_err() {
693                 println!("ERROR: failed to connect to peer");
694         }
695         res
696 }
697
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
702         {
703                 Some(connection_closed_future) => {
704                         let mut connection_closed_future = Box::pin(connection_closed_future);
705                         loop {
706                                 tokio::select! {
707                                         _ = &mut connection_closed_future => return Err(()),
708                                         _ = tokio::time::sleep(Duration::from_millis(10)) => {},
709                                 };
710                                 if peer_manager.get_peer_node_ids().iter().find(|(id, _)| *id == pubkey).is_some() {
711                                         return Ok(());
712                                 }
713                         }
714                 }
715                 None => Err(()),
716         }
717 }
718
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");
727                         return Err(());
728                 }
729         }
730
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);
735                 return Err(());
736         }
737
738         peer_manager.disconnect_by_node_id(pubkey);
739         Ok(())
740 }
741
742 fn open_channel(
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,
750                         ..Default::default()
751                 },
752                 channel_handshake_config: ChannelHandshakeConfig {
753                         announced_channel,
754                         negotiate_anchors_zero_fee_htlc_tx: with_anchors,
755                         ..Default::default()
756                 },
757                 ..Default::default()
758         };
759
760         match channel_manager.create_channel(peer_pubkey, channel_amt_sat, 0, 0, None, Some(config)) {
761                 Ok(_) => {
762                         println!("EVENT: initiated channel with peer {}. ", peer_pubkey);
763                         return Ok(());
764                 }
765                 Err(e) => {
766                         println!("ERROR: failed to open channel: {:?}", e);
767                         return Err(());
768                 }
769         }
770 }
771
772 fn send_payment(
773         channel_manager: &ChannelManager, invoice: &Bolt11Invoice,
774         outbound_payments: &mut OutboundPaymentInfoStorage, fs_store: Arc<FilesystemStore>,
775 ) {
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) {
780                         Ok(res) => res,
781                         Err(e) => {
782                                 println!("Failed to parse invoice");
783                                 print!("> ");
784                                 return;
785                         }
786                 };
787         outbound_payments.payments.insert(
788                 payment_id,
789                 PaymentInfo {
790                         preimage: None,
791                         secret: payment_secret,
792                         status: HTLCStatus::Pending,
793                         amt_msat: MillisatAmount(invoice.amount_milli_satoshis()),
794                 },
795         );
796         fs_store.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode()).unwrap();
797
798         match channel_manager.send_payment(
799                 payment_hash,
800                 recipient_onion,
801                 payment_id,
802                 route_params,
803                 Retry::Timeout(Duration::from_secs(10)),
804         ) {
805                 Ok(_) => {
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);
809                         print!("> ");
810                 }
811                 Err(e) => {
812                         println!("ERROR: failed to send payment: {:?}", e);
813                         print!("> ");
814                         outbound_payments.payments.get_mut(&payment_id).unwrap().status = HTLCStatus::Failed;
815                         fs_store.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode()).unwrap();
816                 }
817         };
818 }
819
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>,
823 ) {
824         let payment_preimage = PaymentPreimage(entropy_source.get_secure_random_bytes());
825         let payment_id = PaymentId(Sha256::hash(&payment_preimage.0[..]).to_byte_array());
826
827         let route_params = RouteParameters::from_payment_params_and_value(
828                 PaymentParameters::for_keysend(payee_pubkey, 40, false),
829                 amt_msat,
830         );
831         outbound_payments.payments.insert(
832                 payment_id,
833                 PaymentInfo {
834                         preimage: None,
835                         secret: None,
836                         status: HTLCStatus::Pending,
837                         amt_msat: MillisatAmount(Some(amt_msat)),
838                 },
839         );
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(),
844                 payment_id,
845                 route_params,
846                 Retry::Timeout(Duration::from_secs(10)),
847         ) {
848                 Ok(_payment_hash) => {
849                         println!("EVENT: initiated sending {} msats to {}", amt_msat, payee_pubkey);
850                         print!("> ");
851                 }
852                 Err(e) => {
853                         println!("ERROR: failed to send payment: {:?}", e);
854                         print!("> ");
855                         outbound_payments.payments.get_mut(&payment_id).unwrap().status = HTLCStatus::Failed;
856                         fs_store.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode()).unwrap();
857                 }
858         };
859 }
860
861 fn get_invoice(
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>,
865 ) {
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,
871         };
872         let invoice = match utils::create_invoice_from_channelmanager(
873                 channel_manager,
874                 keys_manager,
875                 logger,
876                 currency,
877                 Some(amt_msat),
878                 "ldk-tutorial-node".to_string(),
879                 expiry_secs,
880                 None,
881         ) {
882                 Ok(inv) => {
883                         println!("SUCCESS: generated invoice: {}", inv);
884                         inv
885                 }
886                 Err(e) => {
887                         println!("ERROR: failed to create invoice: {:?}", e);
888                         return;
889                 }
890         };
891
892         let payment_hash = PaymentHash(invoice.payment_hash().to_byte_array());
893         inbound_payments.payments.insert(
894                 payment_hash,
895                 PaymentInfo {
896                         preimage: None,
897                         secret: Some(invoice.payment_secret().clone()),
898                         status: HTLCStatus::Pending,
899                         amt_msat: MillisatAmount(Some(amt_msat)),
900                 },
901         );
902 }
903
904 fn close_channel(
905         channel_id: [u8; 32], counterparty_node_id: PublicKey, channel_manager: Arc<ChannelManager>,
906 ) {
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),
910         }
911 }
912
913 fn force_close_channel(
914         channel_id: [u8; 32], counterparty_node_id: PublicKey, channel_manager: Arc<ChannelManager>,
915 ) {
916         match channel_manager
917                 .force_close_broadcasting_latest_txn(&ChannelId(channel_id), &counterparty_node_id)
918         {
919                 Ok(()) => println!("EVENT: initiating channel force-close"),
920                 Err(e) => println!("ERROR: failed to force-close channel: {:?}", e),
921         }
922 }
923
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`",
934                 ));
935         }
936
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",
942                 ));
943         }
944
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",
950                 ));
951         }
952
953         Ok((pubkey.unwrap(), peer_addr.unwrap().unwrap()))
954 }