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,21 +124,10 @@ 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 ,
145130 L : Logger + ' static + ?Sized {
146- let peer_manager_ref = peer_manager. clone ( ) ;
147131 // 8KB is nice and big but also should never cause any issues with stack overflowing.
148132 let mut buf = [ 0 ; 8192 ] ;
149133
@@ -201,7 +185,6 @@ impl Connection {
201185 if pause_read {
202186 us_lock. read_paused = true ;
203187 }
204- Self :: event_trigger( & mut us_lock) ;
205188 } ,
206189 Err ( e) => shutdown_socket!( e, Disconnect :: CloseConnection ) ,
207190 }
@@ -210,19 +193,20 @@ impl Connection {
210193 Err ( e) => shutdown_socket!( e, Disconnect :: PeerDisconnected ) ,
211194 } ,
212195 }
196+ peer_manager. process_events ( ) ;
213197 } ;
214198 let writer_option = us. lock ( ) . unwrap ( ) . writer . take ( ) ;
215199 if let Some ( mut writer) = writer_option {
216200 // If the socket is already closed, shutdown() will fail, so just ignore it.
217201 let _ = writer. shutdown ( ) . await ;
218202 }
219203 if let Disconnect :: PeerDisconnected = disconnect_type {
220- peer_manager_ref . socket_disconnected ( & our_descriptor) ;
221- Self :: event_trigger ( & mut us . lock ( ) . unwrap ( ) ) ;
204+ peer_manager . socket_disconnected ( & our_descriptor) ;
205+ peer_manager . process_events ( ) ;
222206 }
223207 }
224208
225- fn new ( event_notify : mpsc :: Sender < ( ) > , stream : StdTcpStream ) -> ( io:: ReadHalf < TcpStream > , mpsc:: Receiver < ( ) > , mpsc:: Receiver < ( ) > , Arc < Mutex < Self > > ) {
209+ fn new ( stream : StdTcpStream ) -> ( io:: ReadHalf < TcpStream > , mpsc:: Receiver < ( ) > , mpsc:: Receiver < ( ) > , Arc < Mutex < Self > > ) {
226210 // We only ever need a channel of depth 1 here: if we returned a non-full write to the
227211 // PeerManager, we will eventually get notified that there is room in the socket to write
228212 // new bytes, which will generate an event. That event will be popped off the queue before
@@ -238,7 +222,7 @@ impl Connection {
238222
239223 ( reader, write_receiver, read_receiver,
240224 Arc :: new ( Mutex :: new ( Self {
241- writer : Some ( writer) , event_notify , write_avail, read_waker, read_paused : false ,
225+ writer : Some ( writer) , write_avail, read_waker, read_paused : false ,
242226 block_disconnect_socket : false , rl_requested_disconnect : false ,
243227 id : ID_COUNTER . fetch_add ( 1 , Ordering :: AcqRel )
244228 } ) ) )
@@ -251,13 +235,11 @@ impl Connection {
251235/// The returned future will complete when the peer is disconnected and associated handling
252236/// futures are freed, though, because all processing futures are spawned with tokio::spawn, you do
253237/// 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
238+ 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
257239 CMH : ChannelMessageHandler + ' static + Send + Sync ,
258240 RMH : RoutingMessageHandler + ' static + Send + Sync ,
259241 L : Logger + ' static + ?Sized + Send + Sync {
260- let ( reader, write_receiver, read_receiver, us) = Connection :: new ( event_notify , stream) ;
242+ let ( reader, write_receiver, read_receiver, us) = Connection :: new ( stream) ;
261243 #[ cfg( debug_assertions) ]
262244 let last_us = Arc :: clone ( & us) ;
263245
@@ -293,13 +275,11 @@ pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<So
293275/// The returned future will complete when the peer is disconnected and associated handling
294276/// futures are freed, though, because all processing futures are spawned with tokio::spawn, you do
295277/// 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
278+ 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
299279 CMH : ChannelMessageHandler + ' static + Send + Sync ,
300280 RMH : RoutingMessageHandler + ' static + Send + Sync ,
301281 L : Logger + ' static + ?Sized + Send + Sync {
302- let ( reader, mut write_receiver, read_receiver, us) = Connection :: new ( event_notify , stream) ;
282+ let ( reader, mut write_receiver, read_receiver, us) = Connection :: new ( stream) ;
303283 #[ cfg( debug_assertions) ]
304284 let last_us = Arc :: clone ( & us) ;
305285
@@ -365,14 +345,12 @@ pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<S
365345/// disconnected and associated handling futures are freed, though, because all processing in said
366346/// futures are spawned with tokio::spawn, you do not need to poll the second future in order to
367347/// 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
348+ 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
371349 CMH : ChannelMessageHandler + ' static + Send + Sync ,
372350 RMH : RoutingMessageHandler + ' static + Send + Sync ,
373351 L : Logger + ' static + ?Sized + Send + Sync {
374352 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) )
353+ Some ( setup_outbound ( peer_manager, their_node_id, stream) )
376354 } else { None }
377355}
378356
@@ -634,9 +612,8 @@ mod tests {
634612 ( std:: net:: TcpStream :: connect ( "127.0.0.1:46926" ) . unwrap ( ) , listener. accept ( ) . unwrap ( ) . 0 )
635613 } else { panic ! ( "Failed to bind to v4 localhost on common ports" ) ; } ;
636614
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) ;
615+ let fut_a = super :: setup_outbound ( Arc :: clone ( & a_manager) , b_pub, conn_a) ;
616+ let fut_b = super :: setup_inbound ( b_manager, conn_b) ;
640617
641618 tokio:: time:: timeout ( Duration :: from_secs ( 10 ) , a_connected. recv ( ) ) . await . unwrap ( ) ;
642619 tokio:: time:: timeout ( Duration :: from_secs ( 1 ) , b_connected. recv ( ) ) . await . unwrap ( ) ;
0 commit comments