1212//!
1313//! Designed to be as simple as possible, the high-level usage is almost as simple as "hand over a
1414//! TcpStream and a reference to a PeerManager and the rest is handled", except for the
15- //! [Event](../lightning/util/events/enum.Event.html) handlng mechanism, see below.
15+ //! [Event](../lightning/util/events/enum.Event.html) handling mechanism; see example below.
1616//!
1717//! The PeerHandler, due to the fire-and-forget nature of this logic, must be an Arc, and must use
1818//! the SocketDescriptor provided here as the PeerHandler's SocketDescriptor.
1919//!
20- //! Three methods are exposed to register a new connection for handling in tokio::spawn calls, see
21- //! their individual docs for more. All three take a
22- //! [mpsc::Sender<()>](../tokio/sync/mpsc/struct.Sender.html) which is sent into every time
23- //! something occurs which may result in lightning [Events](../lightning/util/events/enum.Event.html).
24- //! The call site should, thus, look something like this:
20+ //! Three methods are exposed to register a new connection for handling in tokio::spawn calls; see
21+ //! their individual docs for details.
22+ //!
23+ //! # Example
2524//! ```
26- //! use tokio::sync::mpsc;
2725//! use std::net::TcpStream;
2826//! use bitcoin::secp256k1::key::PublicKey;
2927//! use lightning::util::events::{Event, EventHandler, EventsProvider};
4341//!
4442//! // Connect to node with pubkey their_node_id at addr:
4543//! async fn connect_to_node(peer_manager: PeerManager, chain_monitor: Arc<ChainMonitor>, channel_manager: ChannelManager, their_node_id: PublicKey, addr: SocketAddr) {
46- //! let (sender, mut receiver) = mpsc::channel(2);
47- //! lightning_net_tokio::connect_outbound(peer_manager, sender, their_node_id, addr).await;
48- //! loop {
49- //! receiver.recv().await;
50- //! channel_manager.process_pending_events(&|event| {
51- //! // Handle the event!
52- //! });
53- //! chain_monitor.process_pending_events(&|event| {
54- //! // Handle the event!
55- //! });
56- //! }
44+ //! lightning_net_tokio::connect_outbound(peer_manager, their_node_id, addr).await;
45+ //! loop {
46+ //! channel_manager.await_persistable_update();
47+ //! channel_manager.process_pending_events(&|event| {
48+ //! // Handle the event!
49+ //! });
50+ //! chain_monitor.process_pending_events(&|event| {
51+ //! // Handle the event!
52+ //! });
53+ //! }
5754//! }
5855//!
5956//! // Begin reading from a newly accepted socket and talk to the peer:
6057//! async fn accept_socket(peer_manager: PeerManager, chain_monitor: Arc<ChainMonitor>, channel_manager: ChannelManager, socket: TcpStream) {
61- //! let (sender, mut receiver) = mpsc::channel(2);
62- //! lightning_net_tokio::setup_inbound(peer_manager, sender, socket);
63- //! loop {
64- //! receiver.recv().await;
65- //! channel_manager.process_pending_events(&|event| {
66- //! // Handle the event!
67- //! });
68- //! chain_monitor.process_pending_events(&|event| {
69- //! // Handle the event!
70- //! });
71- //! }
58+ //! lightning_net_tokio::setup_inbound(peer_manager, socket);
59+ //! loop {
60+ //! channel_manager.await_persistable_update();
61+ //! channel_manager.process_pending_events(&|event| {
62+ //! // Handle the event!
63+ //! });
64+ //! chain_monitor.process_pending_events(&|event| {
65+ //! // Handle the event!
66+ //! });
67+ //! }
7268//! }
7369//! ```
7470
@@ -90,7 +86,7 @@ use lightning::util::logger::Logger;
9086use std:: { task, thread} ;
9187use std:: net:: SocketAddr ;
9288use std:: net:: TcpStream as StdTcpStream ;
93- use std:: sync:: { Arc , Mutex , MutexGuard } ;
89+ use std:: sync:: { Arc , Mutex } ;
9490use std:: sync:: atomic:: { AtomicU64 , Ordering } ;
9591use std:: time:: Duration ;
9692use std:: hash:: Hash ;
@@ -102,7 +98,6 @@ static ID_COUNTER: AtomicU64 = AtomicU64::new(0);
10298/// read future (which is returned by schedule_read).
10399struct Connection {
104100 writer : Option < io:: WriteHalf < TcpStream > > ,
105- event_notify : mpsc:: Sender < ( ) > ,
106101 // Because our PeerManager is templated by user-provided types, and we can't (as far as I can
107102 // tell) have a const RawWakerVTable built out of templated functions, we need some indirection
108103 // between being woken up with write-ready and calling PeerManager::write_buffer_space_avail.
@@ -129,16 +124,6 @@ struct Connection {
129124 id : u64 ,
130125}
131126impl Connection {
132- fn event_trigger ( us : & mut MutexGuard < Self > ) {
133- match us. event_notify . try_send ( ( ) ) {
134- Ok ( _) => { } ,
135- Err ( mpsc:: error:: TrySendError :: Full ( _) ) => {
136- // Ignore full errors as we just need the user to poll after this point, so if they
137- // haven't received the last send yet, it doesn't matter.
138- } ,
139- _ => panic ! ( )
140- }
141- }
142127 async fn schedule_read < CMH , RMH , L > ( peer_manager : Arc < peer_handler:: PeerManager < SocketDescriptor , Arc < CMH > , Arc < RMH > , Arc < L > > > , us : Arc < Mutex < Self > > , mut reader : io:: ReadHalf < TcpStream > , mut read_wake_receiver : mpsc:: Receiver < ( ) > , mut write_avail_receiver : mpsc:: Receiver < ( ) > ) where
143128 CMH : ChannelMessageHandler + ' static ,
144129 RMH : RoutingMessageHandler + ' static ,
@@ -201,7 +186,6 @@ impl Connection {
201186 if pause_read {
202187 us_lock. read_paused = true ;
203188 }
204- Self :: event_trigger( & mut us_lock) ;
205189 } ,
206190 Err ( e) => shutdown_socket!( e, Disconnect :: CloseConnection ) ,
207191 }
@@ -218,11 +202,10 @@ impl Connection {
218202 }
219203 if let Disconnect :: PeerDisconnected = disconnect_type {
220204 peer_manager_ref. socket_disconnected ( & our_descriptor) ;
221- Self :: event_trigger ( & mut us. lock ( ) . unwrap ( ) ) ;
222205 }
223206 }
224207
225- fn new ( event_notify : mpsc :: Sender < ( ) > , stream : StdTcpStream ) -> ( io:: ReadHalf < TcpStream > , mpsc:: Receiver < ( ) > , mpsc:: Receiver < ( ) > , Arc < Mutex < Self > > ) {
208+ fn new ( stream : StdTcpStream ) -> ( io:: ReadHalf < TcpStream > , mpsc:: Receiver < ( ) > , mpsc:: Receiver < ( ) > , Arc < Mutex < Self > > ) {
226209 // We only ever need a channel of depth 1 here: if we returned a non-full write to the
227210 // PeerManager, we will eventually get notified that there is room in the socket to write
228211 // new bytes, which will generate an event. That event will be popped off the queue before
@@ -238,7 +221,7 @@ impl Connection {
238221
239222 ( reader, write_receiver, read_receiver,
240223 Arc :: new ( Mutex :: new ( Self {
241- writer : Some ( writer) , event_notify , write_avail, read_waker, read_paused : false ,
224+ writer : Some ( writer) , write_avail, read_waker, read_paused : false ,
242225 block_disconnect_socket : false , rl_requested_disconnect : false ,
243226 id : ID_COUNTER . fetch_add ( 1 , Ordering :: AcqRel )
244227 } ) ) )
@@ -251,13 +234,11 @@ impl Connection {
251234/// The returned future will complete when the peer is disconnected and associated handling
252235/// futures are freed, though, because all processing futures are spawned with tokio::spawn, you do
253236/// not need to poll the provided future in order to make progress.
254- ///
255- /// See the module-level documentation for how to handle the event_notify mpsc::Sender.
256- pub fn setup_inbound < CMH , RMH , L > ( peer_manager : Arc < peer_handler:: PeerManager < SocketDescriptor , Arc < CMH > , Arc < RMH > , Arc < L > > > , event_notify : mpsc:: Sender < ( ) > , stream : StdTcpStream ) -> impl std:: future:: Future < Output =( ) > where
237+ pub fn setup_inbound < CMH , RMH , L > ( peer_manager : Arc < peer_handler:: PeerManager < SocketDescriptor , Arc < CMH > , Arc < RMH > , Arc < L > > > , stream : StdTcpStream ) -> impl std:: future:: Future < Output =( ) > where
257238 CMH : ChannelMessageHandler + ' static + Send + Sync ,
258239 RMH : RoutingMessageHandler + ' static + Send + Sync ,
259240 L : Logger + ' static + ?Sized + Send + Sync {
260- let ( reader, write_receiver, read_receiver, us) = Connection :: new ( event_notify , stream) ;
241+ let ( reader, write_receiver, read_receiver, us) = Connection :: new ( stream) ;
261242 #[ cfg( debug_assertions) ]
262243 let last_us = Arc :: clone ( & us) ;
263244
@@ -293,13 +274,11 @@ pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<So
293274/// The returned future will complete when the peer is disconnected and associated handling
294275/// futures are freed, though, because all processing futures are spawned with tokio::spawn, you do
295276/// not need to poll the provided future in order to make progress.
296- ///
297- /// See the module-level documentation for how to handle the event_notify mpsc::Sender.
298- pub fn setup_outbound < CMH , RMH , L > ( peer_manager : Arc < peer_handler:: PeerManager < SocketDescriptor , Arc < CMH > , Arc < RMH > , Arc < L > > > , event_notify : mpsc:: Sender < ( ) > , their_node_id : PublicKey , stream : StdTcpStream ) -> impl std:: future:: Future < Output =( ) > where
277+ pub fn setup_outbound < CMH , RMH , L > ( peer_manager : Arc < peer_handler:: PeerManager < SocketDescriptor , Arc < CMH > , Arc < RMH > , Arc < L > > > , their_node_id : PublicKey , stream : StdTcpStream ) -> impl std:: future:: Future < Output =( ) > where
299278 CMH : ChannelMessageHandler + ' static + Send + Sync ,
300279 RMH : RoutingMessageHandler + ' static + Send + Sync ,
301280 L : Logger + ' static + ?Sized + Send + Sync {
302- let ( reader, mut write_receiver, read_receiver, us) = Connection :: new ( event_notify , stream) ;
281+ let ( reader, mut write_receiver, read_receiver, us) = Connection :: new ( stream) ;
303282 #[ cfg( debug_assertions) ]
304283 let last_us = Arc :: clone ( & us) ;
305284
@@ -365,14 +344,12 @@ pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<S
365344/// disconnected and associated handling futures are freed, though, because all processing in said
366345/// futures are spawned with tokio::spawn, you do not need to poll the second future in order to
367346/// make progress.
368- ///
369- /// See the module-level documentation for how to handle the event_notify mpsc::Sender.
370- pub async fn connect_outbound < CMH , RMH , L > ( peer_manager : Arc < peer_handler:: PeerManager < SocketDescriptor , Arc < CMH > , Arc < RMH > , Arc < L > > > , event_notify : mpsc:: Sender < ( ) > , their_node_id : PublicKey , addr : SocketAddr ) -> Option < impl std:: future:: Future < Output =( ) > > where
347+ pub async fn connect_outbound < CMH , RMH , L > ( peer_manager : Arc < peer_handler:: PeerManager < SocketDescriptor , Arc < CMH > , Arc < RMH > , Arc < L > > > , their_node_id : PublicKey , addr : SocketAddr ) -> Option < impl std:: future:: Future < Output =( ) > > where
371348 CMH : ChannelMessageHandler + ' static + Send + Sync ,
372349 RMH : RoutingMessageHandler + ' static + Send + Sync ,
373350 L : Logger + ' static + ?Sized + Send + Sync {
374351 if let Ok ( Ok ( stream) ) = time:: timeout ( Duration :: from_secs ( 10 ) , async { TcpStream :: connect ( & addr) . await . map ( |s| s. into_std ( ) . unwrap ( ) ) } ) . await {
375- Some ( setup_outbound ( peer_manager, event_notify , their_node_id, stream) )
352+ Some ( setup_outbound ( peer_manager, their_node_id, stream) )
376353 } else { None }
377354}
378355
@@ -634,9 +611,8 @@ mod tests {
634611 ( std:: net:: TcpStream :: connect ( "127.0.0.1:46926" ) . unwrap ( ) , listener. accept ( ) . unwrap ( ) . 0 )
635612 } else { panic ! ( "Failed to bind to v4 localhost on common ports" ) ; } ;
636613
637- let ( sender, _receiver) = mpsc:: channel ( 2 ) ;
638- let fut_a = super :: setup_outbound ( Arc :: clone ( & a_manager) , sender. clone ( ) , b_pub, conn_a) ;
639- let fut_b = super :: setup_inbound ( b_manager, sender, conn_b) ;
614+ let fut_a = super :: setup_outbound ( Arc :: clone ( & a_manager) , b_pub, conn_a) ;
615+ let fut_b = super :: setup_inbound ( b_manager, conn_b) ;
640616
641617 tokio:: time:: timeout ( Duration :: from_secs ( 10 ) , a_connected. recv ( ) ) . await . unwrap ( ) ;
642618 tokio:: time:: timeout ( Duration :: from_secs ( 1 ) , b_connected. recv ( ) ) . await . unwrap ( ) ;
0 commit comments