12
12
//!
13
13
//! Designed to be as simple as possible, the high-level usage is almost as simple as "hand over a
14
14
//! 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.
16
16
//!
17
17
//! The PeerHandler, due to the fire-and-forget nature of this logic, must be an Arc, and must use
18
18
//! the SocketDescriptor provided here as the PeerHandler's SocketDescriptor.
19
19
//!
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
25
24
//! ```
26
- //! use tokio::sync::mpsc;
27
25
//! use std::net::TcpStream;
28
26
//! use bitcoin::secp256k1::key::PublicKey;
29
27
//! use lightning::util::events::{Event, EventHandler, EventsProvider};
43
41
//!
44
42
//! // Connect to node with pubkey their_node_id at addr:
45
43
//! 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
+ //! }
57
54
//! }
58
55
//!
59
56
//! // Begin reading from a newly accepted socket and talk to the peer:
60
57
//! 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
+ //! }
72
68
//! }
73
69
//! ```
74
70
@@ -90,7 +86,7 @@ use lightning::util::logger::Logger;
90
86
use std:: { task, thread} ;
91
87
use std:: net:: SocketAddr ;
92
88
use std:: net:: TcpStream as StdTcpStream ;
93
- use std:: sync:: { Arc , Mutex , MutexGuard } ;
89
+ use std:: sync:: { Arc , Mutex } ;
94
90
use std:: sync:: atomic:: { AtomicU64 , Ordering } ;
95
91
use std:: time:: Duration ;
96
92
use std:: hash:: Hash ;
@@ -102,7 +98,6 @@ static ID_COUNTER: AtomicU64 = AtomicU64::new(0);
102
98
/// read future (which is returned by schedule_read).
103
99
struct Connection {
104
100
writer : Option < io:: WriteHalf < TcpStream > > ,
105
- event_notify : mpsc:: Sender < ( ) > ,
106
101
// Because our PeerManager is templated by user-provided types, and we can't (as far as I can
107
102
// tell) have a const RawWakerVTable built out of templated functions, we need some indirection
108
103
// between being woken up with write-ready and calling PeerManager::write_buffer_space_avail.
@@ -129,21 +124,10 @@ struct Connection {
129
124
id : u64 ,
130
125
}
131
126
impl 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
- }
142
127
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
143
128
CMH : ChannelMessageHandler + ' static ,
144
129
RMH : RoutingMessageHandler + ' static ,
145
130
L : Logger + ' static + ?Sized {
146
- let peer_manager_ref = peer_manager. clone ( ) ;
147
131
// 8KB is nice and big but also should never cause any issues with stack overflowing.
148
132
let mut buf = [ 0 ; 8192 ] ;
149
133
@@ -201,7 +185,6 @@ impl Connection {
201
185
if pause_read {
202
186
us_lock. read_paused = true ;
203
187
}
204
- Self :: event_trigger( & mut us_lock) ;
205
188
} ,
206
189
Err ( e) => shutdown_socket!( e, Disconnect :: CloseConnection ) ,
207
190
}
@@ -210,19 +193,20 @@ impl Connection {
210
193
Err ( e) => shutdown_socket!( e, Disconnect :: PeerDisconnected ) ,
211
194
} ,
212
195
}
196
+ peer_manager. process_events ( ) ;
213
197
} ;
214
198
let writer_option = us. lock ( ) . unwrap ( ) . writer . take ( ) ;
215
199
if let Some ( mut writer) = writer_option {
216
200
// If the socket is already closed, shutdown() will fail, so just ignore it.
217
201
let _ = writer. shutdown ( ) . await ;
218
202
}
219
203
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 ( ) ;
222
206
}
223
207
}
224
208
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 > > ) {
226
210
// We only ever need a channel of depth 1 here: if we returned a non-full write to the
227
211
// PeerManager, we will eventually get notified that there is room in the socket to write
228
212
// new bytes, which will generate an event. That event will be popped off the queue before
@@ -238,7 +222,7 @@ impl Connection {
238
222
239
223
( reader, write_receiver, read_receiver,
240
224
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 ,
242
226
block_disconnect_socket : false , rl_requested_disconnect : false ,
243
227
id : ID_COUNTER . fetch_add ( 1 , Ordering :: AcqRel )
244
228
} ) ) )
@@ -251,13 +235,11 @@ impl Connection {
251
235
/// The returned future will complete when the peer is disconnected and associated handling
252
236
/// futures are freed, though, because all processing futures are spawned with tokio::spawn, you do
253
237
/// 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
257
239
CMH : ChannelMessageHandler + ' static + Send + Sync ,
258
240
RMH : RoutingMessageHandler + ' static + Send + Sync ,
259
241
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) ;
261
243
#[ cfg( debug_assertions) ]
262
244
let last_us = Arc :: clone ( & us) ;
263
245
@@ -293,13 +275,11 @@ pub fn setup_inbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<So
293
275
/// The returned future will complete when the peer is disconnected and associated handling
294
276
/// futures are freed, though, because all processing futures are spawned with tokio::spawn, you do
295
277
/// 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
299
279
CMH : ChannelMessageHandler + ' static + Send + Sync ,
300
280
RMH : RoutingMessageHandler + ' static + Send + Sync ,
301
281
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) ;
303
283
#[ cfg( debug_assertions) ]
304
284
let last_us = Arc :: clone ( & us) ;
305
285
@@ -365,14 +345,12 @@ pub fn setup_outbound<CMH, RMH, L>(peer_manager: Arc<peer_handler::PeerManager<S
365
345
/// disconnected and associated handling futures are freed, though, because all processing in said
366
346
/// futures are spawned with tokio::spawn, you do not need to poll the second future in order to
367
347
/// 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
371
349
CMH : ChannelMessageHandler + ' static + Send + Sync ,
372
350
RMH : RoutingMessageHandler + ' static + Send + Sync ,
373
351
L : Logger + ' static + ?Sized + Send + Sync {
374
352
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) )
376
354
} else { None }
377
355
}
378
356
@@ -634,9 +612,8 @@ mod tests {
634
612
( std:: net:: TcpStream :: connect ( "127.0.0.1:46926" ) . unwrap ( ) , listener. accept ( ) . unwrap ( ) . 0 )
635
613
} else { panic ! ( "Failed to bind to v4 localhost on common ports" ) ; } ;
636
614
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) ;
640
617
641
618
tokio:: time:: timeout ( Duration :: from_secs ( 10 ) , a_connected. recv ( ) ) . await . unwrap ( ) ;
642
619
tokio:: time:: timeout ( Duration :: from_secs ( 1 ) , b_connected. recv ( ) ) . await . unwrap ( ) ;
0 commit comments