X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=src%2Fmain.rs;h=f66d4ed393eabfb82aa82fb2cc190c2d249e4444;hb=ad1b9a4ef09fb4966462457dfa69504f20cc9da5;hp=57f0bb2ea7f9017c42feb5b6ef7b9b8818bbda7d;hpb=22fb5d92b9d3711f469cc4dd325981ba979340d5;p=ldk-sample diff --git a/src/main.rs b/src/main.rs index 57f0bb2..f66d4ed 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,8 +9,6 @@ use crate::disk::FilesystemLogger; use bitcoin::blockdata::constants::genesis_block; use bitcoin::blockdata::transaction::Transaction; use bitcoin::consensus::encode; -use bitcoin::hashes::sha256::Hash as Sha256; -use bitcoin::hashes::Hash; use bitcoin::network::constants::Network; use bitcoin::secp256k1::Secp256k1; use bitcoin::BlockHash; @@ -24,7 +22,7 @@ use lightning::ln::channelmanager; use lightning::ln::channelmanager::{ ChainParameters, ChannelManagerReadArgs, SimpleArcChannelManager, }; -use lightning::ln::peer_handler::{MessageHandler, SimpleArcPeerManager}; +use lightning::ln::peer_handler::{IgnoringMessageHandler, MessageHandler, SimpleArcPeerManager}; use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret}; use lightning::routing::network_graph::NetGraphMsgHandler; use lightning::util::config::UserConfig; @@ -100,7 +98,7 @@ pub(crate) type ChannelManager = async fn handle_ldk_events( channel_manager: Arc, bitcoind_client: Arc, keys_manager: Arc, inbound_payments: PaymentInfoStorage, - outbound_payments: PaymentInfoStorage, network: Network, event: Event, + outbound_payments: PaymentInfoStorage, network: Network, event: &Event, ) { match event { Event::FundingGenerationReady { @@ -123,14 +121,12 @@ async fn handle_ldk_events( .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); + 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; @@ -152,9 +148,9 @@ async fn handle_ldk_events( let mut payments = inbound_payments.lock().unwrap(); let (payment_preimage, payment_secret) = match purpose { PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => { - (payment_preimage, Some(payment_secret)) + (*payment_preimage, Some(*payment_secret)) } - PaymentPurpose::SpontaneousPayment(preimage) => (Some(preimage), None), + PaymentPurpose::SpontaneousPayment(preimage) => (Some(*preimage), None), }; let status = match channel_manager.claim_funds(payment_preimage.unwrap()) { true => { @@ -169,7 +165,7 @@ async fn handle_ldk_events( } _ => HTLCStatus::Failed, }; - match payments.entry(payment_hash) { + match payments.entry(*payment_hash) { Entry::Occupied(mut e) => { let payment = e.get_mut(); payment.status = status; @@ -181,17 +177,16 @@ async fn handle_ldk_events( preimage: payment_preimage, secret: payment_secret, status, - amt_msat: MillisatAmount(Some(amt)), + amt_msat: MillisatAmount(Some(*amt)), }); } } } - Event::PaymentSent { payment_preimage } => { - let hashed = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()); + Event::PaymentSent { payment_preimage, payment_hash } => { let mut payments = outbound_payments.lock().unwrap(); - for (payment_hash, payment) in payments.iter_mut() { - if *payment_hash == hashed { - payment.preimage = Some(payment_preimage); + for (hash, payment) in payments.iter_mut() { + if *hash == *payment_hash { + payment.preimage = Some(*payment_preimage); payment.status = HTLCStatus::Succeeded; println!( "\nEVENT: successfully sent payment of {} millisatoshis from \ @@ -205,15 +200,26 @@ async fn handle_ldk_events( } } } - Event::PaymentFailed { payment_hash, rejected_by_dest } => { + Event::PaymentPathFailed { + payment_hash, + rejected_by_dest, + network_update: _, + all_paths_failed, + path: _, + short_channel_id, + } => { print!( - "\nEVENT: Failed to send payment to payment hash {:?}: ", + "\nEVENT: Failed to send payment{} to payment hash {:?}", + if *all_paths_failed { "" } else { " along MPP path" }, hex_utils::hex_str(&payment_hash.0) ); - if rejected_by_dest { - println!("re-attempting the payment will not succeed"); + if let Some(scid) = short_channel_id { + print!(" because of failure at channel {}", scid); + } + if *rejected_by_dest { + println!(": re-attempting the payment will not succeed"); } else { - println!("payment may be retried"); + println!(": payment may be retried"); } print!("> "); io::stdout().flush().unwrap(); @@ -224,10 +230,27 @@ async fn handle_ldk_events( payment.status = HTLCStatus::Failed; } } + Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => { + let from_onchain_str = if *claim_from_onchain_tx { + "from onchain downstream claim" + } else { + "from HTLC fulfill message" + }; + if let Some(fee_earned) = fee_earned_msat { + println!( + "\nEVENT: Forwarded payment, earning {} msat {}", + fee_earned, from_onchain_str + ); + } else { + println!("\nEVENT: Forwarded payment, claiming onchain {}", from_onchain_str); + } + print!("> "); + io::stdout().flush().unwrap(); + } Event::PendingHTLCsForwardable { time_forwardable } => { let forwarding_channel_manager = channel_manager.clone(); + let min = time_forwardable.as_millis() as u64; 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(); @@ -249,6 +272,19 @@ async fn handle_ldk_events( .unwrap(); bitcoind_client.broadcast_transaction(&spending_tx); } + Event::ChannelClosed { channel_id, reason, user_channel_id: _ } => { + println!( + "\nEVENT: Channel {} closed due to: {:?}", + hex_utils::hex_str(channel_id), + reason + ); + print!("> "); + io::stdout().flush().unwrap(); + } + Event::DiscardFunding { .. } => { + // A "real" node should probably "lock" the UTXOs spent in funding transactions until + // the funding transaction either confirms, or this event is generated. + } } } @@ -268,6 +304,7 @@ async fn start_ldk() { args.bitcoind_rpc_port, args.bitcoind_rpc_username.clone(), args.bitcoind_rpc_password.clone(), + tokio::runtime::Handle::current(), ) .await { @@ -443,21 +480,18 @@ async fn start_ldk() { let genesis = genesis_block(args.network).header.block_hash(); 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( + let router = Arc::new(NetGraphMsgHandler::new( + network_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() + if disk::persist_network(Path::new(&network_graph_path), &router_persist.network_graph) + .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. @@ -479,6 +513,7 @@ async fn start_ldk() { keys_manager.get_node_secret(), &ephemeral_bytes, logger.clone(), + Arc::new(IgnoringMessageHandler {}), )); // ## Running LDK @@ -535,7 +570,7 @@ async fn start_ldk() { let network = args.network; let bitcoind_rpc = bitcoind_client.clone(); let handle = tokio::runtime::Handle::current(); - let event_handler = move |event| { + let event_handler = move |event: &Event| { handle.block_on(handle_ldk_events( channel_manager_event_listener.clone(), bitcoind_rpc.clone(), @@ -544,7 +579,7 @@ async fn start_ldk() { outbound_pmts_for_events.clone(), network, event, - )) + )); }; // Step 16: Persist ChannelManager let data_dir = ldk_data_dir.clone(); @@ -556,6 +591,7 @@ async fn start_ldk() { event_handler, chain_monitor.clone(), channel_manager.clone(), + Some(router.clone()), peer_manager.clone(), logger.clone(), );