1 use bitcoin::network::constants::Network;
2 use bitcoin::hashes::Hash;
3 use bitcoin::hashes::sha256::Hash as Sha256Hash;
4 use bitcoin::secp256k1::Secp256k1;
5 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
6 use crate::{ChannelManager, FilesystemLogger, HTLCDirection, HTLCStatus, NETWORK,
7 PaymentInfoStorage, PeerManager};
11 use lightning::ln::channelmanager::{PaymentHash, PaymentPreimage, PaymentSecret};
12 use lightning::ln::features::InvoiceFeatures;
13 use lightning::routing::network_graph::NetGraphMsgHandler;
14 use lightning::routing::router;
15 use lightning::util::config::UserConfig;
20 use std::io::{BufRead, Write};
21 use std::net::{SocketAddr, TcpStream};
24 use std::str::FromStr;
26 use std::time::Duration;
27 use tokio::runtime::Handle;
28 use tokio::sync::mpsc;
30 pub(crate) struct LdkUserInfo {
31 pub(crate) bitcoind_rpc_username: String,
32 pub(crate) bitcoind_rpc_password: String,
33 pub(crate) bitcoind_rpc_port: u16,
34 pub(crate) bitcoind_rpc_host: String,
35 pub(crate) ldk_storage_dir_path: String,
36 pub(crate) ldk_peer_listening_port: u16,
39 pub(crate) fn parse_startup_args() -> Result<LdkUserInfo, ()> {
40 if env::args().len() < 4 {
41 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 [optional: <ldk-incoming-peer-listening-port>]`");
44 let bitcoind_rpc_info = env::args().skip(1).next().unwrap();
45 let bitcoind_rpc_info_parts: Vec<&str> = bitcoind_rpc_info.split("@").collect();
46 if bitcoind_rpc_info_parts.len() != 2 {
47 println!("ERROR: bad bitcoind RPC URL provided");
50 let rpc_user_and_password: Vec<&str> = bitcoind_rpc_info_parts[0].split(":").collect();
51 if rpc_user_and_password.len() != 2 {
52 println!("ERROR: bad bitcoind RPC username/password combo provided");
55 let bitcoind_rpc_username = rpc_user_and_password[0].to_string();
56 let bitcoind_rpc_password = rpc_user_and_password[1].to_string();
57 let bitcoind_rpc_path: Vec<&str> = bitcoind_rpc_info_parts[1].split(":").collect();
58 if bitcoind_rpc_path.len() != 2 {
59 println!("ERROR: bad bitcoind RPC path provided");
62 let bitcoind_rpc_host = bitcoind_rpc_path[0].to_string();
63 let bitcoind_rpc_port = bitcoind_rpc_path[1].parse::<u16>().unwrap();
65 let ldk_storage_dir_path = env::args().skip(2).next().unwrap();
67 let ldk_peer_listening_port: u16 = match env::args().skip(3).next().map(|p| p.parse()) {
69 Some(Err(e)) => panic!(e),
73 bitcoind_rpc_username,
74 bitcoind_rpc_password,
78 ldk_peer_listening_port,
82 pub(crate) fn poll_for_user_input(peer_manager: Arc<PeerManager>, channel_manager:
83 Arc<ChannelManager>, router: Arc<NetGraphMsgHandler<Arc<dyn
84 chain::Access>, Arc<FilesystemLogger>>>, payment_storage:
85 PaymentInfoStorage, node_privkey: SecretKey, event_notifier:
86 mpsc::Sender<()>, ldk_data_dir: String, logger: Arc<FilesystemLogger>,
87 runtime_handle: Handle) {
88 println!("LDK startup successful. To view available commands: \"help\".\nLDK logs are available in the `logs` folder of <your-supplied-ldk-data-dir-path>/.ldk/logs");
89 let stdin = io::stdin();
90 print!("> "); io::stdout().flush().unwrap(); // Without flushing, the `>` doesn't print
91 for line in stdin.lock().lines() {
92 let _ = event_notifier.try_send(());
93 let line = line.unwrap();
94 let mut words = line.split_whitespace();
95 if let Some(word) = words.next() {
99 let peer_pubkey_and_ip_addr = words.next();
100 let channel_value_sat = words.next();
101 if peer_pubkey_and_ip_addr.is_none() || channel_value_sat.is_none() {
102 println!("ERROR: openchannel takes 2 arguments: `openchannel pubkey@host:port channel_amt_satoshis`");
103 print!("> "); io::stdout().flush().unwrap(); continue;
105 let peer_pubkey_and_ip_addr = peer_pubkey_and_ip_addr.unwrap();
106 let (pubkey, peer_addr) = match parse_peer_info(peer_pubkey_and_ip_addr.to_string()) {
109 println!("{:?}", e.into_inner().unwrap());
110 print!("> "); io::stdout().flush().unwrap(); continue;
114 let chan_amt_sat: Result<u64, _> = channel_value_sat.unwrap().parse();
115 if chan_amt_sat.is_err() {
116 println!("ERROR: channel amount must be a number");
117 print!("> "); io::stdout().flush().unwrap(); continue;
120 if connect_peer_if_necessary(pubkey, peer_addr, peer_manager.clone(),
121 event_notifier.clone(),
122 runtime_handle.clone()).is_err() {
123 print!("> "); io::stdout().flush().unwrap(); continue;
126 if open_channel(pubkey, chan_amt_sat.unwrap(), channel_manager.clone()).is_ok() {
127 let peer_data_path = format!("{}/channel_peer_data", ldk_data_dir.clone());
128 let _ = disk::persist_channel_peer(Path::new(&peer_data_path), peer_pubkey_and_ip_addr);
132 let invoice_str = words.next();
133 if invoice_str.is_none() {
134 println!("ERROR: sendpayment requires an invoice: `sendpayment <invoice>`");
135 print!("> "); io::stdout().flush().unwrap(); continue;
138 let invoice_res = lightning_invoice::Invoice::from_str(invoice_str.unwrap());
139 if invoice_res.is_err() {
140 println!("ERROR: invalid invoice: {:?}", invoice_res.unwrap_err());
141 print!("> "); io::stdout().flush().unwrap(); continue;
143 let invoice = invoice_res.unwrap();
145 let amt_pico_btc = invoice.amount_pico_btc();
146 if amt_pico_btc.is_none () {
147 println!("ERROR: invalid invoice: must contain amount to pay");
148 print!("> "); io::stdout().flush().unwrap(); continue;
150 let amt_msat = amt_pico_btc.unwrap() / 10;
152 let payee_pubkey = invoice.recover_payee_pub_key();
153 let final_cltv = *invoice.min_final_cltv_expiry().unwrap_or(&9) as u32;
155 let mut payment_hash = PaymentHash([0; 32]);
156 payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
159 let payment_secret = match invoice.payment_secret() {
161 let mut payment_secret = PaymentSecret([0; 32]);
162 payment_secret.0.copy_from_slice(&secret.0);
168 let mut invoice_features = InvoiceFeatures::empty();
169 for field in &invoice.into_signed_raw().raw_invoice().data.tagged_fields {
171 lightning_invoice::RawTaggedField::UnknownSemantics(vec) => {
172 if vec[0] == bech32::u5::try_from_u8(5).unwrap() {
173 if vec.len() >= 6 && vec[5].to_u8() & 0b10000 != 0 {
174 invoice_features.set_supports_var_onion_optin();
176 if vec.len() >= 6 && vec[5].to_u8() & 0b01000 != 0 {
177 invoice_features.set_requires_var_onion_optin();
179 if vec.len() >= 4 && vec[3].to_u8() & 0b00001 != 0 {
180 invoice_features.set_supports_payment_secret();
182 if vec.len() >= 5 && vec[4].to_u8() & 0b10000 != 0 {
183 invoice_features.set_requires_payment_secret();
185 if vec.len() >= 4 && vec[3].to_u8() & 0b00100 != 0 {
186 invoice_features.set_supports_basic_mpp();
188 if vec.len() >= 4 && vec[3].to_u8() & 0b00010 != 0 {
189 invoice_features.set_requires_basic_mpp();
196 let invoice_features_opt = match invoice_features == InvoiceFeatures::empty() {
198 false => Some(invoice_features)
200 send_payment(payee_pubkey, amt_msat, final_cltv, payment_hash,
201 payment_secret, invoice_features_opt, router.clone(),
202 channel_manager.clone(), payment_storage.clone(),
206 let amt_str = words.next();
207 if amt_str.is_none() {
208 println!("ERROR: getinvoice requires an amount in satoshis");
209 print!("> "); io::stdout().flush().unwrap(); continue;
212 let amt_sat: Result<u64, _> = amt_str.unwrap().parse();
213 if amt_sat.is_err() {
214 println!("ERROR: getinvoice provided payment amount was not a number");
215 print!("> "); io::stdout().flush().unwrap(); continue;
217 get_invoice(amt_sat.unwrap(), payment_storage.clone(), node_privkey.clone(),
218 channel_manager.clone(), router.clone());
221 let peer_pubkey_and_ip_addr = words.next();
222 if peer_pubkey_and_ip_addr.is_none() {
223 println!("ERROR: connectpeer requires peer connection info: `connectpeer pubkey@host:port`");
224 print!("> "); io::stdout().flush().unwrap(); continue;
226 let (pubkey, peer_addr) = match parse_peer_info(peer_pubkey_and_ip_addr.unwrap().to_string()) {
229 println!("{:?}", e.into_inner().unwrap());
230 print!("> "); io::stdout().flush().unwrap(); continue;
233 if connect_peer_if_necessary(pubkey, peer_addr, peer_manager.clone(),
234 event_notifier.clone(), runtime_handle.clone()).is_ok() {
235 println!("SUCCESS: connected to peer {}", pubkey);
239 "listchannels" => list_channels(channel_manager.clone()),
240 "listpayments" => list_payments(payment_storage.clone()),
242 let channel_id_str = words.next();
243 if channel_id_str.is_none() {
244 println!("ERROR: closechannel requires a channel ID: `closechannel <channel_id>`");
245 print!("> "); io::stdout().flush().unwrap(); continue;
247 let channel_id_vec = hex_utils::to_vec(channel_id_str.unwrap());
248 if channel_id_vec.is_none() {
249 println!("ERROR: couldn't parse channel_id as hex");
250 print!("> "); io::stdout().flush().unwrap(); continue;
252 let mut channel_id = [0; 32];
253 channel_id.copy_from_slice(&channel_id_vec.unwrap());
254 close_channel(channel_id, channel_manager.clone());
256 "forceclosechannel" => {
257 let channel_id_str = words.next();
258 if channel_id_str.is_none() {
259 println!("ERROR: forceclosechannel requires a channel ID: `forceclosechannel <channel_id>`");
260 print!("> "); io::stdout().flush().unwrap(); continue;
262 let channel_id_vec = hex_utils::to_vec(channel_id_str.unwrap());
263 if channel_id_vec.is_none() {
264 println!("ERROR: couldn't parse channel_id as hex");
265 print!("> "); io::stdout().flush().unwrap(); continue;
267 let mut channel_id = [0; 32];
268 channel_id.copy_from_slice(&channel_id_vec.unwrap());
269 force_close_channel(channel_id, channel_manager.clone());
271 _ => println!("Unknown command. See `\"help\" for available commands.")
274 print!("> "); io::stdout().flush().unwrap();
280 println!("openchannel pubkey@host:port channel_amt_satoshis");
281 println!("sendpayment <invoice>");
282 println!("getinvoice <amt_in_satoshis>");
283 println!("connectpeer pubkey@host:port");
284 println!("listchannels");
285 println!("listpayments");
286 println!("closechannel <channel_id>");
287 println!("forceclosechannel <channel_id>");
290 fn list_channels(channel_manager: Arc<ChannelManager>) {
292 for chan_info in channel_manager.list_channels() {
295 println!("\t\tchannel_id: {},", hex_utils::hex_str(&chan_info.channel_id[..]));
296 println!("\t\tpeer_pubkey: {},", hex_utils::hex_str(&chan_info.remote_network_id.serialize()));
297 let mut pending_channel = false;
298 match chan_info.short_channel_id {
299 Some(id) => println!("\t\tshort_channel_id: {},", id),
301 pending_channel = true;
304 println!("\t\tpending_open: {},", pending_channel);
305 println!("\t\tchannel_value_satoshis: {},", chan_info.channel_value_satoshis);
306 println!("\t\tchannel_can_send_payments: {},", chan_info.is_live);
312 fn list_payments(payment_storage: PaymentInfoStorage) {
313 let payments = payment_storage.lock().unwrap();
315 for (payment_hash, payment_info) in payments.deref() {
318 println!("\t\tpayment_hash: {},", hex_utils::hex_str(&payment_hash.0));
319 println!("\t\thtlc_direction: {},", if payment_info.1 == HTLCDirection::Inbound { "inbound" } else { "outbound" });
320 println!("\t\thtlc_status: {},", match payment_info.2 {
321 HTLCStatus::Pending => "pending",
322 HTLCStatus::Succeeded => "succeeded",
323 HTLCStatus::Failed => "failed"
332 pub(crate) fn connect_peer_if_necessary(pubkey: PublicKey, peer_addr: SocketAddr, peer_manager:
333 Arc<PeerManager>, event_notifier: mpsc::Sender<()>, runtime: Handle) ->
335 for node_pubkey in peer_manager.get_peer_node_ids() {
336 if node_pubkey == pubkey {
340 match TcpStream::connect_timeout(&peer_addr, Duration::from_secs(10)) {
342 let peer_mgr = peer_manager.clone();
343 let event_ntfns = event_notifier.clone();
344 runtime.spawn(async move {
345 lightning_net_tokio::setup_outbound(peer_mgr, event_ntfns, pubkey, stream).await;
347 let mut peer_connected = false;
348 while !peer_connected {
349 for node_pubkey in peer_manager.get_peer_node_ids() {
350 if node_pubkey == pubkey { peer_connected = true; }
354 Err(e) => {println!("ERROR: failed to connect to peer: {:?}", e);
361 fn open_channel(peer_pubkey: PublicKey, channel_amt_sat: u64, channel_manager: Arc<ChannelManager>)
363 let mut config = UserConfig::default();
364 // lnd's max to_self_delay is 2016, so we want to be compatible.
365 config.peer_channel_config_limits.their_to_self_delay = 2016;
366 match channel_manager.create_channel(peer_pubkey, channel_amt_sat, 0, 0, None) {
368 println!("EVENT: initiated channel with peer {}. ", peer_pubkey);
372 println!("ERROR: failed to open channel: {:?}", e);
378 fn send_payment(payee: PublicKey, amt_msat: u64, final_cltv: u32, payment_hash: PaymentHash,
379 payment_secret: Option<PaymentSecret>, payee_features:
380 Option<InvoiceFeatures>, router: Arc<NetGraphMsgHandler<Arc<dyn
381 chain::Access>, Arc<FilesystemLogger>>>, channel_manager:
382 Arc<ChannelManager>, payment_storage: PaymentInfoStorage, logger:
383 Arc<FilesystemLogger>) {
384 let network_graph = router.network_graph.read().unwrap();
385 let first_hops = channel_manager.list_usable_channels();
386 let payer_pubkey = channel_manager.get_our_node_id();
388 let route = router::get_route(&payer_pubkey, &network_graph, &payee, payee_features,
389 Some(&first_hops.iter().collect::<Vec<_>>()), &vec![], amt_msat,
391 if let Err(e) = route {
392 println!("ERROR: failed to find route: {}", e.err);
395 let status = match channel_manager.send_payment(&route.unwrap(), payment_hash, &payment_secret) {
397 println!("EVENT: initiated sending {} msats to {}", amt_msat, payee);
401 println!("ERROR: failed to send payment: {:?}", e);
405 let mut payments = payment_storage.lock().unwrap();
406 payments.insert(payment_hash, (None, HTLCDirection::Outbound, status));
409 fn get_invoice(amt_sat: u64, payment_storage: PaymentInfoStorage, our_node_privkey: SecretKey,
410 channel_manager: Arc<ChannelManager>, router: Arc<NetGraphMsgHandler<Arc<dyn
411 chain::Access>, Arc<FilesystemLogger>>>) {
412 let mut payments = payment_storage.lock().unwrap();
413 let secp_ctx = Secp256k1::new();
415 let mut preimage = [0; 32];
416 rand::thread_rng().fill_bytes(&mut preimage);
417 let payment_hash = Sha256Hash::hash(&preimage);
420 let our_node_pubkey = channel_manager.get_our_node_id();
421 let invoice = lightning_invoice::InvoiceBuilder::new(match NETWORK {
422 Network::Bitcoin => lightning_invoice::Currency::Bitcoin,
423 Network::Testnet => lightning_invoice::Currency::BitcoinTestnet,
424 Network::Regtest => lightning_invoice::Currency::Regtest,
425 Network::Signet => panic!("Signet invoices not supported")
426 }).payment_hash(payment_hash).description("rust-lightning-bitcoinrpc invoice".to_string())
427 .amount_pico_btc(amt_sat * 10)
429 .payee_pub_key(our_node_pubkey);
431 // Add route hints to the invoice.
432 // let our_channels = channel_manager.list_usable_channels();
433 // let network_graph = router.network_graph.read().unwrap();
434 // let network_channels = network_graph.get_channels();
435 // for channel in our_channels {
436 // let short_channel_id_opt = channel.short_channel_id;
437 // if short_channel_id_opt.is_none() {
441 // let short_channel_id = short_channel_id_opt.unwrap();
442 // let channel_routing_info_opt = network_channels.get(&short_channel_id);
443 // if channel_routing_info_opt.is_none() {
447 // let channel_routing_info = channel_routing_info_opt.unwrap();
448 // let mut counterparty = channel_routing_info.node_two;
449 // let mut counterparty_chan_fees_opt = channel_routing_info.one_to_two.as_ref();
450 // if channel_routing_info.node_two != our_node_pubkey { // e.g. if our counterparty is node_one
451 // counterparty = channel_routing_info.node_one;
452 // counterparty_chan_fees_opt = channel_routing_info.two_to_one.as_ref();
454 // if counterparty_chan_fees_opt.is_none() {
458 // let counterparty_chan_fees = counterparty_chan_fees_opt.unwrap();
459 // invoice = invoice.route(vec![
460 // lightning_invoice::RouteHop {
461 // short_channel_id: short_channel_id.to_be_bytes(),
462 // cltv_expiry_delta: counterparty_chan_fees.cltv_expiry_delta,
463 // fee_base_msat: counterparty_chan_fees.fees.base_msat,
464 // fee_proportional_millionths: counterparty_chan_fees.fees.proportional_millionths,
465 // pubkey: counterparty,
471 let invoice = invoice.build_signed(|msg_hash| {
472 secp_ctx.sign_recoverable(msg_hash, &our_node_privkey)
476 Ok(invoice) => println!("SUCCESS: generated invoice: {}", invoice),
477 Err(e) => println!("ERROR: failed to create invoice: {:?}", e),
480 payments.insert(PaymentHash(payment_hash.into_inner()), (Some(PaymentPreimage(preimage)),
481 HTLCDirection::Inbound,
482 HTLCStatus::Pending));
485 fn close_channel(channel_id: [u8; 32], channel_manager: Arc<ChannelManager>) {
486 match channel_manager.close_channel(&channel_id) {
487 Ok(()) => println!("EVENT: initiating channel close"),
488 Err(e) => println!("ERROR: failed to close channel: {:?}", e)
492 fn force_close_channel(channel_id: [u8; 32], channel_manager: Arc<ChannelManager>) {
493 match channel_manager.force_close_channel(&channel_id) {
494 Ok(()) => println!("EVENT: initiating channel force-close"),
495 Err(e) => println!("ERROR: failed to force-close channel: {:?}", e)
499 pub(crate) fn parse_peer_info(peer_pubkey_and_ip_addr: String) -> Result<(PublicKey, SocketAddr), std::io::Error> {
500 let mut pubkey_and_addr = peer_pubkey_and_ip_addr.split("@");
501 let pubkey = pubkey_and_addr.next();
502 let peer_addr_str = pubkey_and_addr.next();
503 if peer_addr_str.is_none() || peer_addr_str.is_none() {
504 return Err(std::io::Error::new(std::io::ErrorKind::Other, "ERROR: incorrectly formatted peer
505 info. Should be formatted as: `pubkey@host:port`"));
508 let peer_addr: Result<SocketAddr, _> = peer_addr_str.unwrap().parse();
509 if peer_addr.is_err() {
510 return Err(std::io::Error::new(std::io::ErrorKind::Other, "ERROR: couldn't parse pubkey@host:port into a socket address"));
513 let pubkey = hex_utils::to_compressed_pubkey(pubkey.unwrap());
514 if pubkey.is_none() {
515 return Err(std::io::Error::new(std::io::ErrorKind::Other, "ERROR: unable to parse given pubkey for node"));
518 Ok((pubkey.unwrap(), peer_addr.unwrap()))