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,
7 PaymentInfoStorage, PeerManager, SatoshiAmount};
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,
37 pub(crate) network: Network,
40 pub(crate) fn parse_startup_args() -> Result<LdkUserInfo, ()> {
41 if env::args().len() < 4 {
42 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]`");
45 let bitcoind_rpc_info = env::args().skip(1).next().unwrap();
46 let bitcoind_rpc_info_parts: Vec<&str> = bitcoind_rpc_info.split("@").collect();
47 if bitcoind_rpc_info_parts.len() != 2 {
48 println!("ERROR: bad bitcoind RPC URL provided");
51 let rpc_user_and_password: Vec<&str> = bitcoind_rpc_info_parts[0].split(":").collect();
52 if rpc_user_and_password.len() != 2 {
53 println!("ERROR: bad bitcoind RPC username/password combo provided");
56 let bitcoind_rpc_username = rpc_user_and_password[0].to_string();
57 let bitcoind_rpc_password = rpc_user_and_password[1].to_string();
58 let bitcoind_rpc_path: Vec<&str> = bitcoind_rpc_info_parts[1].split(":").collect();
59 if bitcoind_rpc_path.len() != 2 {
60 println!("ERROR: bad bitcoind RPC path provided");
63 let bitcoind_rpc_host = bitcoind_rpc_path[0].to_string();
64 let bitcoind_rpc_port = bitcoind_rpc_path[1].parse::<u16>().unwrap();
66 let ldk_storage_dir_path = env::args().skip(2).next().unwrap();
68 let mut ldk_peer_port_set = true;
69 let ldk_peer_listening_port: u16 = match env::args().skip(3).next().map(|p| p.parse()) {
71 Some(Err(e)) => panic!(e),
73 ldk_peer_port_set = false;
78 let arg_idx = match ldk_peer_port_set {
82 let network: Network = match env::args().skip(arg_idx).next().as_ref().map(String::as_str) {
83 Some("testnet") => Network::Testnet,
84 Some("regtest") => Network::Regtest,
85 Some(_) => panic!("Unsupported network provided. Options are: `regtest`, `testnet`"),
86 None => Network::Testnet
89 bitcoind_rpc_username,
90 bitcoind_rpc_password,
94 ldk_peer_listening_port,
99 pub(crate) fn poll_for_user_input(peer_manager: Arc<PeerManager>, channel_manager:
100 Arc<ChannelManager>, router: Arc<NetGraphMsgHandler<Arc<dyn
101 chain::Access>, Arc<FilesystemLogger>>>, payment_storage:
102 PaymentInfoStorage, node_privkey: SecretKey, event_notifier:
103 mpsc::Sender<()>, ldk_data_dir: String, logger: Arc<FilesystemLogger>,
104 runtime_handle: Handle, network: Network) {
105 println!("LDK startup successful. To view available commands: \"help\".\nLDK logs are available at <your-supplied-ldk-data-dir-path>/.ldk/logs");
106 let stdin = io::stdin();
107 print!("> "); io::stdout().flush().unwrap(); // Without flushing, the `>` doesn't print
108 for line in stdin.lock().lines() {
109 let _ = event_notifier.try_send(());
110 let line = line.unwrap();
111 let mut words = line.split_whitespace();
112 if let Some(word) = words.next() {
116 let peer_pubkey_and_ip_addr = words.next();
117 let channel_value_sat = words.next();
118 if peer_pubkey_and_ip_addr.is_none() || channel_value_sat.is_none() {
119 println!("ERROR: openchannel takes 2 arguments: `openchannel pubkey@host:port channel_amt_satoshis`");
120 print!("> "); io::stdout().flush().unwrap(); continue;
122 let peer_pubkey_and_ip_addr = peer_pubkey_and_ip_addr.unwrap();
123 let (pubkey, peer_addr) = match parse_peer_info(peer_pubkey_and_ip_addr.to_string()) {
126 println!("{:?}", e.into_inner().unwrap());
127 print!("> "); io::stdout().flush().unwrap(); continue;
131 let chan_amt_sat: Result<u64, _> = channel_value_sat.unwrap().parse();
132 if chan_amt_sat.is_err() {
133 println!("ERROR: channel amount must be a number");
134 print!("> "); io::stdout().flush().unwrap(); continue;
137 if connect_peer_if_necessary(pubkey, peer_addr, peer_manager.clone(),
138 event_notifier.clone(),
139 runtime_handle.clone()).is_err() {
140 print!("> "); io::stdout().flush().unwrap(); continue;
143 if open_channel(pubkey, chan_amt_sat.unwrap(), channel_manager.clone()).is_ok() {
144 let peer_data_path = format!("{}/channel_peer_data", ldk_data_dir.clone());
145 let _ = disk::persist_channel_peer(Path::new(&peer_data_path), peer_pubkey_and_ip_addr);
149 let invoice_str = words.next();
150 if invoice_str.is_none() {
151 println!("ERROR: sendpayment requires an invoice: `sendpayment <invoice>`");
152 print!("> "); io::stdout().flush().unwrap(); continue;
155 let invoice_res = lightning_invoice::Invoice::from_str(invoice_str.unwrap());
156 if invoice_res.is_err() {
157 println!("ERROR: invalid invoice: {:?}", invoice_res.unwrap_err());
158 print!("> "); io::stdout().flush().unwrap(); continue;
160 let invoice = invoice_res.unwrap();
162 let amt_pico_btc = invoice.amount_pico_btc();
163 if amt_pico_btc.is_none () {
164 println!("ERROR: invalid invoice: must contain amount to pay");
165 print!("> "); io::stdout().flush().unwrap(); continue;
167 let amt_msat = amt_pico_btc.unwrap() / 10;
169 let payee_pubkey = invoice.recover_payee_pub_key();
170 let final_cltv = *invoice.min_final_cltv_expiry().unwrap_or(&9) as u32;
172 let mut payment_hash = PaymentHash([0; 32]);
173 payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
176 let payment_secret = match invoice.payment_secret() {
178 let mut payment_secret = PaymentSecret([0; 32]);
179 payment_secret.0.copy_from_slice(&secret.0);
185 // rust-lightning-invoice doesn't currently support features, so we parse features
186 // manually from the invoice.
187 let mut invoice_features = InvoiceFeatures::empty();
188 for field in &invoice.into_signed_raw().raw_invoice().data.tagged_fields {
190 lightning_invoice::RawTaggedField::UnknownSemantics(vec) => {
191 if vec[0] == bech32::u5::try_from_u8(5).unwrap() {
192 if vec.len() >= 6 && vec[5].to_u8() & 0b10000 != 0 {
193 invoice_features = invoice_features.set_variable_length_onion_optional();
195 if vec.len() >= 6 && vec[5].to_u8() & 0b01000 != 0 {
196 invoice_features = invoice_features.set_variable_length_onion_required();
198 if vec.len() >= 4 && vec[3].to_u8() & 0b00001 != 0 {
199 invoice_features = invoice_features.set_payment_secret_optional();
201 if vec.len() >= 5 && vec[4].to_u8() & 0b10000 != 0 {
202 invoice_features = invoice_features.set_payment_secret_required();
204 if vec.len() >= 4 && vec[3].to_u8() & 0b00100 != 0 {
205 invoice_features = invoice_features.set_basic_mpp_optional();
207 if vec.len() >= 4 && vec[3].to_u8() & 0b00010 != 0 {
208 invoice_features = invoice_features.set_basic_mpp_required();
215 let invoice_features_opt = match invoice_features == InvoiceFeatures::empty() {
217 false => Some(invoice_features)
219 send_payment(payee_pubkey, amt_msat, final_cltv, payment_hash,
220 payment_secret, invoice_features_opt, router.clone(),
221 channel_manager.clone(), payment_storage.clone(),
225 let amt_str = words.next();
226 if amt_str.is_none() {
227 println!("ERROR: getinvoice requires an amount in satoshis");
228 print!("> "); io::stdout().flush().unwrap(); continue;
231 let amt_sat: Result<u64, _> = amt_str.unwrap().parse();
232 if amt_sat.is_err() {
233 println!("ERROR: getinvoice provided payment amount was not a number");
234 print!("> "); io::stdout().flush().unwrap(); continue;
236 get_invoice(amt_sat.unwrap(), payment_storage.clone(), node_privkey.clone(),
237 channel_manager.clone(), network);
240 let peer_pubkey_and_ip_addr = words.next();
241 if peer_pubkey_and_ip_addr.is_none() {
242 println!("ERROR: connectpeer requires peer connection info: `connectpeer pubkey@host:port`");
243 print!("> "); io::stdout().flush().unwrap(); continue;
245 let (pubkey, peer_addr) = match parse_peer_info(peer_pubkey_and_ip_addr.unwrap().to_string()) {
248 println!("{:?}", e.into_inner().unwrap());
249 print!("> "); io::stdout().flush().unwrap(); continue;
252 if connect_peer_if_necessary(pubkey, peer_addr, peer_manager.clone(),
253 event_notifier.clone(), runtime_handle.clone()).is_ok() {
254 println!("SUCCESS: connected to peer {}", pubkey);
258 "listchannels" => list_channels(channel_manager.clone()),
259 "listpayments" => list_payments(payment_storage.clone()),
261 let channel_id_str = words.next();
262 if channel_id_str.is_none() {
263 println!("ERROR: closechannel requires a channel ID: `closechannel <channel_id>`");
264 print!("> "); io::stdout().flush().unwrap(); continue;
266 let channel_id_vec = hex_utils::to_vec(channel_id_str.unwrap());
267 if channel_id_vec.is_none() {
268 println!("ERROR: couldn't parse channel_id as hex");
269 print!("> "); io::stdout().flush().unwrap(); continue;
271 let mut channel_id = [0; 32];
272 channel_id.copy_from_slice(&channel_id_vec.unwrap());
273 close_channel(channel_id, channel_manager.clone());
275 "forceclosechannel" => {
276 let channel_id_str = words.next();
277 if channel_id_str.is_none() {
278 println!("ERROR: forceclosechannel requires a channel ID: `forceclosechannel <channel_id>`");
279 print!("> "); io::stdout().flush().unwrap(); continue;
281 let channel_id_vec = hex_utils::to_vec(channel_id_str.unwrap());
282 if channel_id_vec.is_none() {
283 println!("ERROR: couldn't parse channel_id as hex");
284 print!("> "); io::stdout().flush().unwrap(); continue;
286 let mut channel_id = [0; 32];
287 channel_id.copy_from_slice(&channel_id_vec.unwrap());
288 force_close_channel(channel_id, channel_manager.clone());
290 _ => println!("Unknown command. See `\"help\" for available commands.")
293 print!("> "); io::stdout().flush().unwrap();
299 println!("openchannel pubkey@host:port <channel_amt_satoshis>");
300 println!("sendpayment <invoice>");
301 println!("getinvoice <amt_in_satoshis>");
302 println!("connectpeer pubkey@host:port");
303 println!("listchannels");
304 println!("listpayments");
305 println!("closechannel <channel_id>");
306 println!("forceclosechannel <channel_id>");
309 fn list_channels(channel_manager: Arc<ChannelManager>) {
311 for chan_info in channel_manager.list_channels() {
314 println!("\t\tchannel_id: {},", hex_utils::hex_str(&chan_info.channel_id[..]));
315 println!("\t\tpeer_pubkey: {},", hex_utils::hex_str(&chan_info.remote_network_id.serialize()));
316 let mut pending_channel = false;
317 match chan_info.short_channel_id {
318 Some(id) => println!("\t\tshort_channel_id: {},", id),
320 pending_channel = true;
323 println!("\t\tpending_open: {},", pending_channel);
324 println!("\t\tchannel_value_satoshis: {},", chan_info.channel_value_satoshis);
325 println!("\t\tchannel_can_send_payments: {},", chan_info.is_live);
331 fn list_payments(payment_storage: PaymentInfoStorage) {
332 let payments = payment_storage.lock().unwrap();
334 for (payment_hash, payment_info) in payments.deref() {
335 let direction_str = match payment_info.1 {
336 HTLCDirection::Inbound => "inbound",
337 HTLCDirection::Outbound => "outbound",
341 println!("\t\tamount_satoshis: {},", payment_info.3);
342 println!("\t\tpayment_hash: {},", hex_utils::hex_str(&payment_hash.0));
343 println!("\t\thtlc_direction: {},", direction_str);
344 println!("\t\thtlc_status: {},", match payment_info.2 {
345 HTLCStatus::Pending => "pending",
346 HTLCStatus::Succeeded => "succeeded",
347 HTLCStatus::Failed => "failed"
356 pub(crate) fn connect_peer_if_necessary(pubkey: PublicKey, peer_addr: SocketAddr, peer_manager:
357 Arc<PeerManager>, event_notifier: mpsc::Sender<()>, runtime: Handle) ->
359 for node_pubkey in peer_manager.get_peer_node_ids() {
360 if node_pubkey == pubkey {
364 match TcpStream::connect_timeout(&peer_addr, Duration::from_secs(10)) {
366 let peer_mgr = peer_manager.clone();
367 let event_ntfns = event_notifier.clone();
368 runtime.spawn(async move {
369 lightning_net_tokio::setup_outbound(peer_mgr, event_ntfns, pubkey, stream).await;
371 let mut peer_connected = false;
372 while !peer_connected {
373 for node_pubkey in peer_manager.get_peer_node_ids() {
374 if node_pubkey == pubkey { peer_connected = true; }
378 Err(e) => {println!("ERROR: failed to connect to peer: {:?}", e);
385 fn open_channel(peer_pubkey: PublicKey, channel_amt_sat: u64, channel_manager: Arc<ChannelManager>)
387 let mut config = UserConfig::default();
388 // lnd's max to_self_delay is 2016, so we want to be compatible.
389 config.peer_channel_config_limits.their_to_self_delay = 2016;
390 match channel_manager.create_channel(peer_pubkey, channel_amt_sat, 0, 0, None) {
392 println!("EVENT: initiated channel with peer {}. ", peer_pubkey);
396 println!("ERROR: failed to open channel: {:?}", e);
402 fn send_payment(payee: PublicKey, amt_msat: u64, final_cltv: u32, payment_hash: PaymentHash,
403 payment_secret: Option<PaymentSecret>, payee_features: Option<InvoiceFeatures>,
404 router: Arc<NetGraphMsgHandler<Arc<dyn chain::Access>, Arc<FilesystemLogger>>>,
405 channel_manager: Arc<ChannelManager>, payment_storage: PaymentInfoStorage, logger:
406 Arc<FilesystemLogger>) {
407 let network_graph = router.network_graph.read().unwrap();
408 let first_hops = channel_manager.list_usable_channels();
409 let payer_pubkey = channel_manager.get_our_node_id();
411 let route = router::get_route(&payer_pubkey, &network_graph, &payee, payee_features,
412 Some(&first_hops.iter().collect::<Vec<_>>()), &vec![], amt_msat,
414 if let Err(e) = route {
415 println!("ERROR: failed to find route: {}", e.err);
418 let status = match channel_manager.send_payment(&route.unwrap(), payment_hash, &payment_secret) {
420 println!("EVENT: initiated sending {} msats to {}", amt_msat, payee);
424 println!("ERROR: failed to send payment: {:?}", e);
428 let mut payments = payment_storage.lock().unwrap();
429 payments.insert(payment_hash, (None, HTLCDirection::Outbound, status,
430 SatoshiAmount(Some(amt_msat * 1000))));
433 fn get_invoice(amt_sat: u64, payment_storage: PaymentInfoStorage, our_node_privkey: SecretKey,
434 channel_manager: Arc<ChannelManager>, network: Network) {
435 let mut payments = payment_storage.lock().unwrap();
436 let secp_ctx = Secp256k1::new();
438 let mut preimage = [0; 32];
439 rand::thread_rng().fill_bytes(&mut preimage);
440 let payment_hash = Sha256Hash::hash(&preimage);
443 let our_node_pubkey = channel_manager.get_our_node_id();
444 let mut invoice = lightning_invoice::InvoiceBuilder::new(match network {
445 Network::Bitcoin => lightning_invoice::Currency::Bitcoin,
446 Network::Testnet => lightning_invoice::Currency::BitcoinTestnet,
447 Network::Regtest => lightning_invoice::Currency::Regtest,
448 Network::Signet => panic!("Signet invoices not supported")
450 .payment_hash(payment_hash).description("rust-lightning-bitcoinrpc invoice".to_string())
451 .amount_pico_btc(amt_sat * 10_000)
453 .payee_pub_key(our_node_pubkey);
455 // Add route hints to the invoice.
456 let our_channels = channel_manager.list_usable_channels();
457 for channel in our_channels {
458 let short_channel_id = match channel.short_channel_id {
459 Some(id) => id.to_be_bytes(),
462 let forwarding_info = match channel.counterparty_forwarding_info {
466 println!("VMW: adding routehop, info.fee base: {}", forwarding_info.fee_base_msat);
467 invoice = invoice.route(vec![
468 lightning_invoice::RouteHop {
469 pubkey: channel.remote_network_id,
471 fee_base_msat: forwarding_info.fee_base_msat,
472 fee_proportional_millionths: forwarding_info.fee_proportional_millionths,
473 cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
479 let invoice = invoice.build_signed(|msg_hash| {
480 secp_ctx.sign_recoverable(msg_hash, &our_node_privkey)
484 Ok(invoice) => println!("SUCCESS: generated invoice: {}", invoice),
485 Err(e) => println!("ERROR: failed to create invoice: {:?}", e),
488 payments.insert(PaymentHash(payment_hash.into_inner()), (Some(PaymentPreimage(preimage)),
489 HTLCDirection::Inbound,
491 SatoshiAmount(Some(amt_sat))));
494 fn close_channel(channel_id: [u8; 32], channel_manager: Arc<ChannelManager>) {
495 match channel_manager.close_channel(&channel_id) {
496 Ok(()) => println!("EVENT: initiating channel close"),
497 Err(e) => println!("ERROR: failed to close channel: {:?}", e)
501 fn force_close_channel(channel_id: [u8; 32], channel_manager: Arc<ChannelManager>) {
502 match channel_manager.force_close_channel(&channel_id) {
503 Ok(()) => println!("EVENT: initiating channel force-close"),
504 Err(e) => println!("ERROR: failed to force-close channel: {:?}", e)
508 pub(crate) fn parse_peer_info(peer_pubkey_and_ip_addr: String) -> Result<(PublicKey, SocketAddr), std::io::Error> {
509 let mut pubkey_and_addr = peer_pubkey_and_ip_addr.split("@");
510 let pubkey = pubkey_and_addr.next();
511 let peer_addr_str = pubkey_and_addr.next();
512 if peer_addr_str.is_none() || peer_addr_str.is_none() {
513 return Err(std::io::Error::new(std::io::ErrorKind::Other, "ERROR: incorrectly formatted peer
514 info. Should be formatted as: `pubkey@host:port`"));
517 let peer_addr: Result<SocketAddr, _> = peer_addr_str.unwrap().parse();
518 if peer_addr.is_err() {
519 return Err(std::io::Error::new(std::io::ErrorKind::Other, "ERROR: couldn't parse pubkey@host:port into a socket address"));
522 let pubkey = hex_utils::to_compressed_pubkey(pubkey.unwrap());
523 if pubkey.is_none() {
524 return Err(std::io::Error::new(std::io::ErrorKind::Other, "ERROR: unable to parse given pubkey for node"));
527 Ok((pubkey.unwrap(), peer_addr.unwrap()))