Skip to content

Commit f8450a7

Browse files
authored
Merge pull request #920 from jkczyz/2021-05-event-processing
Background processing of ChannelManager and ChannelMonitor events
2 parents 3a0356f + a1f95de commit f8450a7

File tree

13 files changed

+374
-188
lines changed

13 files changed

+374
-188
lines changed

fuzz/src/chanmon_consistency.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ use lightning::util::errors::APIError;
4444
use lightning::util::events;
4545
use lightning::util::logger::Logger;
4646
use lightning::util::config::UserConfig;
47-
use lightning::util::events::{EventsProvider, MessageSendEventsProvider};
47+
use lightning::util::events::MessageSendEventsProvider;
4848
use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer};
4949
use lightning::routing::router::{Route, RouteHop};
5050

fuzz/src/full_stack.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ use lightning::ln::msgs::DecodeError;
3939
use lightning::routing::router::get_route;
4040
use lightning::routing::network_graph::NetGraphMsgHandler;
4141
use lightning::util::config::UserConfig;
42-
use lightning::util::events::{EventsProvider,Event};
42+
use lightning::util::events::Event;
4343
use lightning::util::enforcing_trait_impls::EnforcingSigner;
4444
use lightning::util::logger::Logger;
4545
use lightning::util::ser::Readable;

lightning-background-processor/src/lib.rs

Lines changed: 139 additions & 43 deletions
Large diffs are not rendered by default.

lightning-net-tokio/src/lib.rs

Lines changed: 40 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -12,21 +12,19 @@
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;
29-
//! use lightning::util::events::EventsProvider;
27+
//! use lightning::util::events::{Event, EventHandler, EventsProvider};
3028
//! use std::net::SocketAddr;
3129
//! use std::sync::Arc;
3230
//!
@@ -43,32 +41,30 @@
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-
//! for _event in channel_manager.get_and_clear_pending_events().drain(..) {
51-
//! // Handle the event!
52-
//! }
53-
//! for _event in chain_monitor.get_and_clear_pending_events().drain(..) {
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-
//! for _event in channel_manager.get_and_clear_pending_events().drain(..) {
66-
//! // Handle the event!
67-
//! }
68-
//! for _event in chain_monitor.get_and_clear_pending_events().drain(..) {
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;
9086
use std::{task, thread};
9187
use std::net::SocketAddr;
9288
use std::net::TcpStream as StdTcpStream;
93-
use std::sync::{Arc, Mutex, MutexGuard};
89+
use std::sync::{Arc, Mutex};
9490
use std::sync::atomic::{AtomicU64, Ordering};
9591
use std::time::Duration;
9692
use std::hash::Hash;
@@ -102,7 +98,6 @@ static ID_COUNTER: AtomicU64 = AtomicU64::new(0);
10298
/// read future (which is returned by schedule_read).
10399
struct 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
}
131126
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-
}
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();

lightning/src/chain/chainmonitor.rs

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ use chain::transaction::{OutPoint, TransactionData};
3535
use chain::keysinterface::Sign;
3636
use util::logger::Logger;
3737
use util::events;
38-
use util::events::Event;
38+
use util::events::EventHandler;
3939

4040
use std::collections::{HashMap, hash_map};
4141
use std::sync::RwLock;
@@ -139,6 +139,15 @@ where C::Target: chain::Filter,
139139
persister,
140140
}
141141
}
142+
143+
#[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
144+
pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
145+
use util::events::EventsProvider;
146+
let events = std::cell::RefCell::new(Vec::new());
147+
let event_handler = |event| events.borrow_mut().push(event);
148+
self.process_pending_events(&event_handler);
149+
events.into_inner()
150+
}
142151
}
143152

144153
impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
@@ -306,12 +315,20 @@ impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> even
306315
L::Target: Logger,
307316
P::Target: channelmonitor::Persist<ChannelSigner>,
308317
{
309-
fn get_and_clear_pending_events(&self) -> Vec<Event> {
318+
/// Processes [`SpendableOutputs`] events produced from each [`ChannelMonitor`] upon maturity.
319+
///
320+
/// An [`EventHandler`] may safely call back to the provider, though this shouldn't be needed in
321+
/// order to handle these events.
322+
///
323+
/// [`SpendableOutputs`]: events::Event::SpendableOutputs
324+
fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
310325
let mut pending_events = Vec::new();
311326
for monitor in self.monitors.read().unwrap().values() {
312327
pending_events.append(&mut monitor.get_and_clear_pending_events());
313328
}
314-
pending_events
329+
for event in pending_events.drain(..) {
330+
handler.handle_event(event);
331+
}
315332
}
316333
}
317334

@@ -320,7 +337,6 @@ mod tests {
320337
use ::{check_added_monitors, get_local_commitment_txn};
321338
use ln::features::InitFeatures;
322339
use ln::functional_test_utils::*;
323-
use util::events::EventsProvider;
324340
use util::events::MessageSendEventsProvider;
325341
use util::test_utils::{OnRegisterOutput, TxOutReference};
326342

lightning/src/chain/channelmonitor.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -222,11 +222,11 @@ pub(crate) const CLTV_CLAIM_BUFFER: u32 = 18;
222222
pub(crate) const LATENCY_GRACE_PERIOD_BLOCKS: u32 = 3;
223223
/// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding inbound
224224
/// HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us losing money.
225-
/// We use also this delay to be sure we can remove our in-flight claim txn from bump candidates buffer.
226-
/// It may cause spurrious generation of bumped claim txn but that's allright given the outpoint is already
227-
/// solved by a previous claim tx. What we want to avoid is reorg evicting our claim tx and us not
228-
/// keeping bumping another claim tx to solve the outpoint.
229-
pub(crate) const ANTI_REORG_DELAY: u32 = 6;
225+
// We also use this delay to be sure we can remove our in-flight claim txn from bump candidates buffer.
226+
// It may cause spurious generation of bumped claim txn but that's alright given the outpoint is already
227+
// solved by a previous claim tx. What we want to avoid is reorg evicting our claim tx and us not
228+
// keep bumping another claim tx to solve the outpoint.
229+
pub const ANTI_REORG_DELAY: u32 = 6;
230230
/// Number of blocks before confirmation at which we fail back an un-relayed HTLC or at which we
231231
/// refuse to accept a new HTLC.
232232
///

lightning/src/ln/chanmon_update_fail_tests.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ use ln::msgs::{ChannelMessageHandler, ErrorAction, RoutingMessageHandler};
2727
use routing::router::get_route;
2828
use util::config::UserConfig;
2929
use util::enforcing_trait_impls::EnforcingSigner;
30-
use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
30+
use util::events::{Event, MessageSendEvent, MessageSendEventsProvider};
3131
use util::errors::APIError;
3232
use util::ser::{ReadableArgs, Writeable};
3333

0 commit comments

Comments
 (0)