X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning-net-tokio%2Fsrc%2Flib.rs;h=645a7434e4536534138c5dd6150fe52bad55ff0c;hb=28c9b56113ff1ebb1b505a2c979c55c1626aa06b;hp=22df5c3e8bd4d4e8a88d863d751e95725dfdd211;hpb=132b07239784749dcadfc2959a9487107789df56;p=rust-lightning diff --git a/lightning-net-tokio/src/lib.rs b/lightning-net-tokio/src/lib.rs index 22df5c3e..645a7434 100644 --- a/lightning-net-tokio/src/lib.rs +++ b/lightning-net-tokio/src/lib.rs @@ -23,7 +23,7 @@ //! # Example //! ``` //! use std::net::TcpStream; -//! use bitcoin::secp256k1::key::PublicKey; +//! use bitcoin::secp256k1::PublicKey; //! use lightning::util::events::{Event, EventHandler, EventsProvider}; //! use std::net::SocketAddr; //! use std::sync::Arc; @@ -71,7 +71,7 @@ #![cfg_attr(docsrs, feature(doc_auto_cfg))] -use bitcoin::secp256k1::key::PublicKey; +use bitcoin::secp256k1::PublicKey; use tokio::net::TcpStream; use tokio::{io, time}; @@ -84,6 +84,7 @@ use lightning::ln::peer_handler::CustomMessageHandler; use lightning::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, NetAddress}; use lightning::util::logger::Logger; +use std::ops::Deref; use std::task; use std::net::SocketAddr; use std::net::TcpStream as StdTcpStream; @@ -120,11 +121,38 @@ struct Connection { id: u64, } impl Connection { - async fn schedule_read(peer_manager: Arc, Arc, Arc, Arc>>, us: Arc>, mut reader: io::ReadHalf, mut read_wake_receiver: mpsc::Receiver<()>, mut write_avail_receiver: mpsc::Receiver<()>) where - CMH: ChannelMessageHandler + 'static, - RMH: RoutingMessageHandler + 'static, - L: Logger + 'static + ?Sized, - UMH: CustomMessageHandler + 'static { + async fn poll_event_process(peer_manager: Arc>, mut event_receiver: mpsc::Receiver<()>) where + CMH: Deref + 'static + Send + Sync, + RMH: Deref + 'static + Send + Sync, + L: Deref + 'static + Send + Sync, + UMH: Deref + 'static + Send + Sync, + CMH::Target: ChannelMessageHandler + Send + Sync, + RMH::Target: RoutingMessageHandler + Send + Sync, + L::Target: Logger + Send + Sync, + UMH::Target: CustomMessageHandler + Send + Sync, + { + loop { + if event_receiver.recv().await.is_none() { + return; + } + peer_manager.process_events(); + } + } + + async fn schedule_read(peer_manager: Arc>, us: Arc>, mut reader: io::ReadHalf, mut read_wake_receiver: mpsc::Receiver<()>, mut write_avail_receiver: mpsc::Receiver<()>) where + CMH: Deref + 'static + Send + Sync, + RMH: Deref + 'static + Send + Sync, + L: Deref + 'static + Send + Sync, + UMH: Deref + 'static + Send + Sync, + CMH::Target: ChannelMessageHandler + 'static + Send + Sync, + RMH::Target: RoutingMessageHandler + 'static + Send + Sync, + L::Target: Logger + 'static + Send + Sync, + UMH::Target: CustomMessageHandler + 'static + Send + Sync, + { + // Create a waker to wake up poll_event_process, above + let (event_waker, event_receiver) = mpsc::channel(1); + tokio::spawn(Self::poll_event_process(Arc::clone(&peer_manager), event_receiver)); + // 8KB is nice and big but also should never cause any issues with stack overflowing. let mut buf = [0; 8192]; @@ -175,7 +203,14 @@ impl Connection { Err(_) => break Disconnect::PeerDisconnected, }, } - peer_manager.process_events(); + let _ = event_waker.try_send(()); + + // At this point we've processed a message or two, and reset the ping timer for this + // peer, at least in the "are we still receiving messages" context, if we don't give up + // our timeslice to another task we may just spin on this peer, starving other peers + // and eventually disconnecting them for ping timeouts. Instead, we explicitly yield + // here. + tokio::task::yield_now().await; }; let writer_option = us.lock().unwrap().writer.take(); if let Some(mut writer) = writer_option { @@ -231,11 +266,16 @@ fn get_addr_from_stream(stream: &StdTcpStream) -> Option { /// The returned future will complete when the peer is disconnected and associated handling /// futures are freed, though, because all processing futures are spawned with tokio::spawn, you do /// not need to poll the provided future in order to make progress. -pub fn setup_inbound(peer_manager: Arc, Arc, Arc, Arc>>, stream: StdTcpStream) -> impl std::future::Future where - CMH: ChannelMessageHandler + 'static + Send + Sync, - RMH: RoutingMessageHandler + 'static + Send + Sync, - L: Logger + 'static + ?Sized + Send + Sync, - UMH: CustomMessageHandler + 'static + Send + Sync { +pub fn setup_inbound(peer_manager: Arc>, stream: StdTcpStream) -> impl std::future::Future where + CMH: Deref + 'static + Send + Sync, + RMH: Deref + 'static + Send + Sync, + L: Deref + 'static + Send + Sync, + UMH: Deref + 'static + Send + Sync, + CMH::Target: ChannelMessageHandler + Send + Sync, + RMH::Target: RoutingMessageHandler + Send + Sync, + L::Target: Logger + Send + Sync, + UMH::Target: CustomMessageHandler + Send + Sync, +{ let remote_addr = get_addr_from_stream(&stream); let (reader, write_receiver, read_receiver, us) = Connection::new(stream); #[cfg(debug_assertions)] @@ -273,11 +313,16 @@ pub fn setup_inbound(peer_manager: Arc(peer_manager: Arc, Arc, Arc, Arc>>, their_node_id: PublicKey, stream: StdTcpStream) -> impl std::future::Future where - CMH: ChannelMessageHandler + 'static + Send + Sync, - RMH: RoutingMessageHandler + 'static + Send + Sync, - L: Logger + 'static + ?Sized + Send + Sync, - UMH: CustomMessageHandler + 'static + Send + Sync { +pub fn setup_outbound(peer_manager: Arc>, their_node_id: PublicKey, stream: StdTcpStream) -> impl std::future::Future where + CMH: Deref + 'static + Send + Sync, + RMH: Deref + 'static + Send + Sync, + L: Deref + 'static + Send + Sync, + UMH: Deref + 'static + Send + Sync, + CMH::Target: ChannelMessageHandler + Send + Sync, + RMH::Target: RoutingMessageHandler + Send + Sync, + L::Target: Logger + Send + Sync, + UMH::Target: CustomMessageHandler + Send + Sync, +{ let remote_addr = get_addr_from_stream(&stream); let (reader, mut write_receiver, read_receiver, us) = Connection::new(stream); #[cfg(debug_assertions)] @@ -344,11 +389,16 @@ pub fn setup_outbound(peer_manager: Arc(peer_manager: Arc, Arc, Arc, Arc>>, their_node_id: PublicKey, addr: SocketAddr) -> Option> where - CMH: ChannelMessageHandler + 'static + Send + Sync, - RMH: RoutingMessageHandler + 'static + Send + Sync, - L: Logger + 'static + ?Sized + Send + Sync, - UMH: CustomMessageHandler + 'static + Send + Sync { +pub async fn connect_outbound(peer_manager: Arc>, their_node_id: PublicKey, addr: SocketAddr) -> Option> where + CMH: Deref + 'static + Send + Sync, + RMH: Deref + 'static + Send + Sync, + L: Deref + 'static + Send + Sync, + UMH: Deref + 'static + Send + Sync, + CMH::Target: ChannelMessageHandler + Send + Sync, + RMH::Target: RoutingMessageHandler + Send + Sync, + L::Target: Logger + Send + Sync, + UMH::Target: CustomMessageHandler + Send + Sync, +{ if let Ok(Ok(stream)) = time::timeout(Duration::from_secs(10), async { TcpStream::connect(&addr).await.map(|s| s.into_std().unwrap()) }).await { Some(setup_outbound(peer_manager, their_node_id, stream)) } else { None } @@ -443,6 +493,9 @@ impl peer_handler::SocketDescriptor for SocketDescriptor { // pause read given we're now waiting on the remote end to ACK (and in // accordance with the send_data() docs). us.read_paused = true; + // Further, to avoid any current pending read causing a `read_event` call, wake + // up the read_waker and restart its loop. + let _ = us.read_waker.try_send(()); return written_len; }, } @@ -522,7 +575,7 @@ mod tests { fn handle_accept_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, _msg: &AcceptChannel) {} fn handle_funding_created(&self, _their_node_id: &PublicKey, _msg: &FundingCreated) {} fn handle_funding_signed(&self, _their_node_id: &PublicKey, _msg: &FundingSigned) {} - fn handle_funding_locked(&self, _their_node_id: &PublicKey, _msg: &FundingLocked) {} + fn handle_channel_ready(&self, _their_node_id: &PublicKey, _msg: &ChannelReady) {} fn handle_shutdown(&self, _their_node_id: &PublicKey, _their_features: &InitFeatures, _msg: &Shutdown) {} fn handle_closing_signed(&self, _their_node_id: &PublicKey, _msg: &ClosingSigned) {} fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, _msg: &UpdateAddHTLC) {}