X-Git-Url: http://git.bitcoin.ninja/index.cgi?p=ldk-sample;a=blobdiff_plain;f=src%2Fmain.rs;h=b7d74aa0ffb57c0ed427ead353f162b3acd20dbd;hp=32981a4ac23845322d5a301c1edf62a7090daf4c;hb=5ff97eca45db6c8e3498c88a1f2cca99dec14208;hpb=9157f86d3f75c4b122c319e2639455b90f7fd1f9 diff --git a/src/main.rs b/src/main.rs index 32981a4..b7d74aa 100644 --- a/src/main.rs +++ b/src/main.rs @@ -23,13 +23,13 @@ use lightning::chain::Filter; use lightning::chain::Watch; use lightning::ln::channelmanager; use lightning::ln::channelmanager::{ - ChainParameters, ChannelManagerReadArgs, PaymentHash, PaymentPreimage, PaymentSecret, - SimpleArcChannelManager, + BestBlock, ChainParameters, ChannelManagerReadArgs, SimpleArcChannelManager, }; use lightning::ln::peer_handler::{MessageHandler, SimpleArcPeerManager}; +use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret}; use lightning::routing::network_graph::NetGraphMsgHandler; use lightning::util::config::UserConfig; -use lightning::util::events::{Event, EventsProvider}; +use lightning::util::events::Event; use lightning::util::ser::ReadableArgs; use lightning_background_processor::BackgroundProcessor; use lightning_block_sync::init; @@ -39,6 +39,7 @@ use lightning_block_sync::UnboundedCache; use lightning_net_tokio::SocketDescriptor; use lightning_persister::FilesystemPersister; use rand::{thread_rng, Rng}; +use std::collections::hash_map::Entry; use std::collections::HashMap; use std::fmt; use std::fs; @@ -49,7 +50,6 @@ use std::ops::Deref; use std::path::Path; use std::sync::{Arc, Mutex}; use std::time::{Duration, SystemTime}; -use tokio::sync::mpsc; pub(crate) enum HTLCStatus { Pending, @@ -79,7 +79,7 @@ pub(crate) type PaymentInfoStorage = Arc type ChainMonitor = chainmonitor::ChainMonitor< InMemorySigner, - Arc, + Arc, Arc, Arc, Arc, @@ -91,7 +91,7 @@ pub(crate) type PeerManager = SimpleArcPeerManager< ChainMonitor, BitcoindClient, BitcoindClient, - dyn chain::Access, + dyn chain::Access + Send + Sync, FilesystemLogger, >; @@ -99,154 +99,151 @@ pub(crate) type ChannelManager = SimpleArcChannelManager; async fn handle_ldk_events( - channel_manager: Arc, chain_monitor: Arc, - bitcoind_client: Arc, keys_manager: Arc, - payment_storage: PaymentInfoStorage, network: Network, + channel_manager: Arc, bitcoind_client: Arc, + keys_manager: Arc, inbound_payments: PaymentInfoStorage, + outbound_payments: PaymentInfoStorage, network: Network, event: Event, ) { - loop { - let loop_channel_manager = channel_manager.clone(); - let mut events = channel_manager.get_and_clear_pending_events(); - events.append(&mut chain_monitor.get_and_clear_pending_events()); - for event in events { - match event { - Event::FundingGenerationReady { - temporary_channel_id, - channel_value_satoshis, - output_script, - .. - } => { - // Construct the raw transaction with one output, that is paid the amount of the - // channel. - let addr = WitnessProgram::from_scriptpubkey( - &output_script[..], - match network { - Network::Bitcoin => bitcoin_bech32::constants::Network::Bitcoin, - Network::Testnet => bitcoin_bech32::constants::Network::Testnet, - Network::Regtest => bitcoin_bech32::constants::Network::Regtest, - Network::Signet => panic!("Signet unsupported"), - }, - ) - .expect("Lightning funding tx should always be to a SegWit output") - .to_address(); - let mut outputs = vec![HashMap::with_capacity(1)]; - outputs[0].insert(addr, channel_value_satoshis as f64 / 100_000_000.0); - let raw_tx = bitcoind_client.create_raw_transaction(outputs).await; - - // Have your wallet put the inputs into the transaction such that the output is - // satisfied. - let funded_tx = bitcoind_client.fund_raw_transaction(raw_tx).await; - let change_output_position = funded_tx.changepos; - assert!(change_output_position == 0 || change_output_position == 1); - - // Sign the final funding transaction and broadcast it. - let signed_tx = - bitcoind_client.sign_raw_transaction_with_wallet(funded_tx.hex).await; - assert_eq!(signed_tx.complete, true); - let final_tx: Transaction = - encode::deserialize(&hex_utils::to_vec(&signed_tx.hex).unwrap()).unwrap(); - // Give the funding transaction back to LDK for opening the channel. - loop_channel_manager - .funding_transaction_generated(&temporary_channel_id, final_tx) - .unwrap(); - } - Event::PaymentReceived { payment_hash, .. } => { - let mut payments = payment_storage.lock().unwrap(); - if let Some(payment) = payments.get_mut(&payment_hash) { - assert!(loop_channel_manager.claim_funds( - payment.preimage.unwrap().clone(), - &payment.secret, - payment.amt_msat.0.unwrap(), - )); - println!( - "\nEVENT: received payment from payment_hash {} of {} millisatoshis", - hex_utils::hex_str(&payment_hash.0), - payment.amt_msat - ); - print!("> "); - io::stdout().flush().unwrap(); - payment.status = HTLCStatus::Succeeded; - } else { - println!("\nERROR: we received a payment but didn't know the preimage"); - print!("> "); - io::stdout().flush().unwrap(); - loop_channel_manager.fail_htlc_backwards(&payment_hash, &None); - payments.insert( - payment_hash, - PaymentInfo { - preimage: None, - secret: None, - status: HTLCStatus::Failed, - amt_msat: MillisatAmount(None), - }, - ); - } - } - Event::PaymentSent { payment_preimage } => { - let hashed = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()); - let mut payments = payment_storage.lock().unwrap(); - for (payment_hash, payment) in payments.iter_mut() { - if *payment_hash == hashed { - payment.preimage = Some(payment_preimage); - payment.status = HTLCStatus::Succeeded; - println!( - "\nEVENT: successfully sent payment of {} millisatoshis from \ - payment hash {:?} with preimage {:?}", - payment.amt_msat, - hex_utils::hex_str(&payment_hash.0), - hex_utils::hex_str(&payment_preimage.0) - ); - print!("> "); - io::stdout().flush().unwrap(); - } - } - } - Event::PaymentFailed { payment_hash, rejected_by_dest } => { - print!( - "\nEVENT: Failed to send payment to payment hash {:?}: ", - hex_utils::hex_str(&payment_hash.0) + match event { + Event::FundingGenerationReady { + temporary_channel_id, + channel_value_satoshis, + output_script, + .. + } => { + // Construct the raw transaction with one output, that is paid the amount of the + // channel. + let addr = WitnessProgram::from_scriptpubkey( + &output_script[..], + match network { + Network::Bitcoin => bitcoin_bech32::constants::Network::Bitcoin, + Network::Testnet => bitcoin_bech32::constants::Network::Testnet, + Network::Regtest => bitcoin_bech32::constants::Network::Regtest, + Network::Signet => panic!("Signet unsupported"), + }, + ) + .expect("Lightning funding tx should always be to a SegWit output") + .to_address(); + let mut outputs = vec![HashMap::with_capacity(1)]; + outputs[0].insert(addr, channel_value_satoshis as f64 / 100_000_000.0); + let raw_tx = bitcoind_client.create_raw_transaction(outputs).await; + + // Have your wallet put the inputs into the transaction such that the output is + // satisfied. + let funded_tx = bitcoind_client.fund_raw_transaction(raw_tx).await; + let change_output_position = funded_tx.changepos; + assert!(change_output_position == 0 || change_output_position == 1); + + // Sign the final funding transaction and broadcast it. + let signed_tx = bitcoind_client.sign_raw_transaction_with_wallet(funded_tx.hex).await; + assert_eq!(signed_tx.complete, true); + let final_tx: Transaction = + encode::deserialize(&hex_utils::to_vec(&signed_tx.hex).unwrap()).unwrap(); + // Give the funding transaction back to LDK for opening the channel. + if channel_manager + .funding_transaction_generated(&temporary_channel_id, final_tx) + .is_err() + { + println!( + "\nERROR: Channel went away before we could fund it. The peer disconnected or refused the channel."); + print!("> "); + io::stdout().flush().unwrap(); + } + } + Event::PaymentReceived { payment_hash, payment_preimage, payment_secret, amt, .. } => { + let mut payments = inbound_payments.lock().unwrap(); + let status = match channel_manager.claim_funds(payment_preimage.unwrap()) { + true => { + println!( + "\nEVENT: received payment from payment hash {} of {} millisatoshis", + hex_utils::hex_str(&payment_hash.0), + amt ); - if rejected_by_dest { - println!("rejected by destination node"); - } else { - println!("route failed"); - } print!("> "); io::stdout().flush().unwrap(); - - let mut payments = payment_storage.lock().unwrap(); - if payments.contains_key(&payment_hash) { - let payment = payments.get_mut(&payment_hash).unwrap(); - payment.status = HTLCStatus::Failed; - } + HTLCStatus::Succeeded } - Event::PendingHTLCsForwardable { time_forwardable } => { - let forwarding_channel_manager = loop_channel_manager.clone(); - tokio::spawn(async move { - let min = time_forwardable.as_millis() as u64; - let millis_to_sleep = thread_rng().gen_range(min, min * 5) as u64; - tokio::time::sleep(Duration::from_millis(millis_to_sleep)).await; - forwarding_channel_manager.process_pending_htlc_forwards(); + _ => HTLCStatus::Failed, + }; + match payments.entry(payment_hash) { + Entry::Occupied(mut e) => { + let payment = e.get_mut(); + payment.status = status; + payment.preimage = Some(payment_preimage.unwrap()); + payment.secret = Some(payment_secret); + } + Entry::Vacant(e) => { + e.insert(PaymentInfo { + preimage: Some(payment_preimage.unwrap()), + secret: Some(payment_secret), + status, + amt_msat: MillisatAmount(Some(amt)), }); } - Event::SpendableOutputs { outputs } => { - let destination_address = bitcoind_client.get_new_address().await; - let output_descriptors = &outputs.iter().map(|a| a).collect::>(); - let tx_feerate = - bitcoind_client.get_est_sat_per_1000_weight(ConfirmationTarget::Normal); - let spending_tx = keys_manager - .spend_spendable_outputs( - output_descriptors, - Vec::new(), - destination_address.script_pubkey(), - tx_feerate, - &Secp256k1::new(), - ) - .unwrap(); - bitcoind_client.broadcast_transaction(&spending_tx); + } + } + Event::PaymentSent { payment_preimage } => { + let hashed = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()); + let mut payments = outbound_payments.lock().unwrap(); + for (payment_hash, payment) in payments.iter_mut() { + if *payment_hash == hashed { + payment.preimage = Some(payment_preimage); + payment.status = HTLCStatus::Succeeded; + println!( + "\nEVENT: successfully sent payment of {} millisatoshis from \ + payment hash {:?} with preimage {:?}", + payment.amt_msat, + hex_utils::hex_str(&payment_hash.0), + hex_utils::hex_str(&payment_preimage.0) + ); + print!("> "); + io::stdout().flush().unwrap(); } } } - tokio::time::sleep(Duration::from_secs(1)).await; + Event::PaymentFailed { payment_hash, rejected_by_dest } => { + print!( + "\nEVENT: Failed to send payment to payment hash {:?}: ", + hex_utils::hex_str(&payment_hash.0) + ); + if rejected_by_dest { + println!("re-attempting the payment will not succeed"); + } else { + println!("payment may be retried"); + } + print!("> "); + io::stdout().flush().unwrap(); + + let mut payments = outbound_payments.lock().unwrap(); + if payments.contains_key(&payment_hash) { + let payment = payments.get_mut(&payment_hash).unwrap(); + payment.status = HTLCStatus::Failed; + } + } + Event::PendingHTLCsForwardable { time_forwardable } => { + let forwarding_channel_manager = channel_manager.clone(); + tokio::spawn(async move { + let min = time_forwardable.as_millis() as u64; + let millis_to_sleep = thread_rng().gen_range(min, min * 5) as u64; + tokio::time::sleep(Duration::from_millis(millis_to_sleep)).await; + forwarding_channel_manager.process_pending_htlc_forwards(); + }); + } + Event::SpendableOutputs { outputs } => { + let destination_address = bitcoind_client.get_new_address().await; + let output_descriptors = &outputs.iter().map(|a| a).collect::>(); + let tx_feerate = + bitcoind_client.get_est_sat_per_1000_weight(ConfirmationTarget::Normal); + let spending_tx = keys_manager + .spend_spendable_outputs( + output_descriptors, + Vec::new(), + destination_address.script_pubkey(), + tx_feerate, + &Secp256k1::new(), + ) + .unwrap(); + bitcoind_client.broadcast_transaction(&spending_tx); + } } } @@ -276,6 +273,22 @@ async fn start_ldk() { } }; + // Check that the bitcoind we've connected to is running the network we expect + let bitcoind_chain = bitcoind_client.get_blockchain_info().await.chain; + if bitcoind_chain + != match args.network { + bitcoin::Network::Bitcoin => "main", + bitcoin::Network::Testnet => "test", + bitcoin::Network::Regtest => "regtest", + bitcoin::Network::Signet => "signet", + } { + println!( + "Chain argument ({}) didn't match bitcoind chain ({})", + args.network, bitcoind_chain + ); + return; + } + // ## Setup // Step 1: Initialize the FeeEstimator @@ -334,7 +347,7 @@ async fn start_ldk() { // Step 7: Read ChannelMonitor state from disk let mut channelmonitors = persister.read_channelmonitors(keys_manager.clone()).unwrap(); - // Step 9: Initialize the ChannelManager + // Step 8: Initialize the ChannelManager let user_config = UserConfig::default(); let mut restarting_node = true; let (channel_manager_blockhash, mut channel_manager) = { @@ -360,8 +373,10 @@ async fn start_ldk() { let chain_params = ChainParameters { network: args.network, - latest_hash: getinfo_resp.latest_blockhash, - latest_height: getinfo_resp.latest_height, + best_block: BestBlock::new( + getinfo_resp.latest_blockhash, + getinfo_resp.latest_height as u32, + ), }; let fresh_channel_manager = channelmanager::ChannelManager::new( fee_estimator.clone(), @@ -376,7 +391,7 @@ async fn start_ldk() { } }; - // Step 10: Sync ChannelMonitors and ChannelManager to chain tip + // Step 9: Sync ChannelMonitors and ChannelManager to chain tip let mut chain_listener_channel_monitors = Vec::new(); let mut cache = UnboundedCache::new(); let mut chain_tip: Option = None; @@ -411,20 +426,43 @@ async fn start_ldk() { ); } - // Step 11: Give ChannelMonitors to ChainMonitor + // Step 10: Give ChannelMonitors to ChainMonitor for item in chain_listener_channel_monitors.drain(..) { let channel_monitor = item.1 .0; let funding_outpoint = item.2; chain_monitor.watch_channel(funding_outpoint, channel_monitor).unwrap(); } - // Step 13: Optional: Initialize the NetGraphMsgHandler - // XXX persist routing data + // Step 11: Optional: Initialize the NetGraphMsgHandler let genesis = genesis_block(args.network).header.block_hash(); - let router = - Arc::new(NetGraphMsgHandler::new(genesis, None::>, logger.clone())); + let network_graph_path = format!("{}/network_graph", ldk_data_dir.clone()); + let network_graph = disk::read_network(Path::new(&network_graph_path), genesis); + let router = Arc::new(NetGraphMsgHandler::from_net_graph( + None::>, + logger.clone(), + network_graph, + )); + let router_persist = Arc::clone(&router); + tokio::spawn(async move { + let mut interval = tokio::time::interval(Duration::from_secs(600)); + loop { + interval.tick().await; + if disk::persist_network( + Path::new(&network_graph_path), + &*router_persist.network_graph.read().unwrap(), + ) + .is_err() + { + // Persistence errors here are non-fatal as we can just fetch the routing graph + // again later, but they may indicate a disk error which could be fatal elsewhere. + eprintln!( + "Warning: Failed to persist network graph, check your disk and permissions" + ); + } + } + }); - // Step 14: Initialize the PeerManager + // Step 12: Initialize the PeerManager let channel_manager: Arc = Arc::new(channel_manager); let mut ephemeral_bytes = [0; 32]; rand::thread_rng().fill_bytes(&mut ephemeral_bytes); @@ -438,28 +476,28 @@ async fn start_ldk() { )); // ## Running LDK - // Step 16: Initialize Peer Connection Handling + // Step 13: Initialize networking - // We poll for events in handle_ldk_events(..) rather than waiting for them over the - // mpsc::channel, so we can leave the event receiver as unused. - let (event_ntfn_sender, _event_ntfn_receiver) = mpsc::channel(2); let peer_manager_connection_handler = peer_manager.clone(); - let event_notifier = event_ntfn_sender.clone(); let listening_port = args.ldk_peer_listening_port; tokio::spawn(async move { - let listener = std::net::TcpListener::bind(format!("0.0.0.0:{}", listening_port)).unwrap(); + let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", listening_port)) + .await + .expect("Failed to bind to listen port - is something else already listening on it?"); loop { - let tcp_stream = listener.accept().unwrap().0; - lightning_net_tokio::setup_inbound( - peer_manager_connection_handler.clone(), - event_notifier.clone(), - tcp_stream, - ) - .await; + let peer_mgr = peer_manager_connection_handler.clone(); + let tcp_stream = listener.accept().await.unwrap().0; + tokio::spawn(async move { + lightning_net_tokio::setup_inbound( + peer_mgr.clone(), + tcp_stream.into_std().unwrap(), + ) + .await; + }); } }); - // Step 17: Connect and Disconnect Blocks + // Step 14: Connect and Disconnect Blocks if chain_tip.is_none() { chain_tip = Some(init::validate_best_block_header(&mut bitcoind_client.deref()).await.unwrap()); @@ -480,39 +518,42 @@ async fn start_ldk() { } }); - // Step 17 & 18: Initialize ChannelManager persistence & Once Per Minute: ChannelManager's - // timer_chan_freshness_every_min() and PeerManager's timer_tick_occurred + // Step 15: Handle LDK Events + let channel_manager_event_listener = channel_manager.clone(); + let keys_manager_listener = keys_manager.clone(); + // TODO: persist payment info to disk + let inbound_payments: PaymentInfoStorage = Arc::new(Mutex::new(HashMap::new())); + let outbound_payments: PaymentInfoStorage = Arc::new(Mutex::new(HashMap::new())); + let inbound_pmts_for_events = inbound_payments.clone(); + let outbound_pmts_for_events = outbound_payments.clone(); + let network = args.network; + let bitcoind_rpc = bitcoind_client.clone(); + let handle = tokio::runtime::Handle::current(); + let event_handler = move |event| { + handle.block_on(handle_ldk_events( + channel_manager_event_listener.clone(), + bitcoind_rpc.clone(), + keys_manager_listener.clone(), + inbound_pmts_for_events.clone(), + outbound_pmts_for_events.clone(), + network, + event, + )) + }; + // Step 16: Persist ChannelManager let data_dir = ldk_data_dir.clone(); let persist_channel_manager_callback = move |node: &ChannelManager| FilesystemPersister::persist_manager(data_dir.clone(), &*node); + // Step 17: Background Processing BackgroundProcessor::start( persist_channel_manager_callback, + event_handler, + chain_monitor.clone(), channel_manager.clone(), peer_manager.clone(), logger.clone(), ); - // Step 15: Initialize LDK Event Handling - let channel_manager_event_listener = channel_manager.clone(); - let chain_monitor_event_listener = chain_monitor.clone(); - let keys_manager_listener = keys_manager.clone(); - // TODO: persist payment info to disk - let payment_info: PaymentInfoStorage = Arc::new(Mutex::new(HashMap::new())); - let payment_info_for_events = payment_info.clone(); - let network = args.network; - let bitcoind_rpc = bitcoind_client.clone(); - tokio::spawn(async move { - handle_ldk_events( - channel_manager_event_listener, - chain_monitor_event_listener, - bitcoind_rpc, - keys_manager_listener, - payment_info_for_events, - network, - ) - .await; - }); - // Reconnect to channel peers if possible. let peer_data_path = format!("{}/channel_peer_data", ldk_data_dir.clone()); match disk::read_channel_peer_data(Path::new(&peer_data_path)) { @@ -520,12 +561,9 @@ async fn start_ldk() { for (pubkey, peer_addr) in info.drain() { for chan_info in channel_manager.list_channels() { if pubkey == chan_info.remote_network_id { - let _ = cli::connect_peer_if_necessary( - pubkey, - peer_addr, - peer_manager.clone(), - event_ntfn_sender.clone(), - ); + let _ = + cli::connect_peer_if_necessary(pubkey, peer_addr, peer_manager.clone()) + .await; } } } @@ -533,17 +571,37 @@ async fn start_ldk() { Err(e) => println!("ERROR: errored reading channel peer info from disk: {:?}", e), } + // Regularly broadcast our node_announcement. This is only required (or possible) if we have + // some public channels, and is only useful if we have public listen address(es) to announce. + // In a production environment, this should occur only after the announcement of new channels + // to avoid churn in the global network graph. + let chan_manager = Arc::clone(&channel_manager); + let network = args.network; + if !args.ldk_announced_listen_addr.is_empty() { + tokio::spawn(async move { + let mut interval = tokio::time::interval(Duration::from_secs(60)); + loop { + interval.tick().await; + chan_manager.broadcast_node_announcement( + [0; 3], + args.ldk_announced_node_name, + args.ldk_announced_listen_addr.clone(), + ); + } + }); + } + // Start the CLI. cli::poll_for_user_input( peer_manager.clone(), channel_manager.clone(), + keys_manager.clone(), router.clone(), - payment_info, - keys_manager.get_node_secret(), - event_ntfn_sender, + inbound_payments, + outbound_payments, ldk_data_dir.clone(), logger.clone(), - args.network, + network, ) .await; }