1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Top level peer message handling and socket handling logic lives here.
12 //! Instead of actually servicing sockets ourselves we require that you implement the
13 //! SocketDescriptor interface and use that to receive actions which you should perform on the
14 //! socket, and call into PeerManager with bytes read from the socket. The PeerManager will then
15 //! call into the provided message handlers (probably a ChannelManager and NetGraphmsgHandler) with messages
16 //! they should handle, and encoding/sending response messages.
18 use bitcoin::secp256k1::key::{SecretKey,PublicKey};
20 use ln::features::InitFeatures;
22 use ln::msgs::{ChannelMessageHandler, LightningError, RoutingMessageHandler};
23 use ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager};
24 use util::ser::{VecWriter, Writeable, Writer};
25 use ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
28 use util::events::{MessageSendEvent, MessageSendEventsProvider};
29 use util::logger::Logger;
30 use routing::network_graph::NetGraphMsgHandler;
34 use alloc::collections::LinkedList;
35 use sync::{Arc, Mutex};
36 use core::sync::atomic::{AtomicUsize, Ordering};
37 use core::{cmp, hash, fmt, mem};
39 use core::convert::Infallible;
40 #[cfg(feature = "std")] use std::error;
42 use bitcoin::hashes::sha256::Hash as Sha256;
43 use bitcoin::hashes::sha256::HashEngine as Sha256Engine;
44 use bitcoin::hashes::{HashEngine, Hash};
46 /// Handler for BOLT1-compliant messages.
47 pub trait CustomMessageHandler: wire::CustomMessageReader {
48 /// Called with the message type that was received and the buffer to be read.
49 /// Can return a `MessageHandlingError` if the message could not be handled.
50 fn handle_custom_message(&self, msg: Self::CustomMessage, sender_node_id: &PublicKey) -> Result<(), LightningError>;
52 /// Gets the list of pending messages which were generated by the custom message
53 /// handler, clearing the list in the process. The first tuple element must
54 /// correspond to the intended recipients node ids. If no connection to one of the
55 /// specified node does not exist, the message is simply not sent to it.
56 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)>;
59 /// A dummy struct which implements `RoutingMessageHandler` without storing any routing information
60 /// or doing any processing. You can provide one of these as the route_handler in a MessageHandler.
61 pub struct IgnoringMessageHandler{}
62 impl MessageSendEventsProvider for IgnoringMessageHandler {
63 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> { Vec::new() }
65 impl RoutingMessageHandler for IgnoringMessageHandler {
66 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> { Ok(false) }
67 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> { Ok(false) }
68 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> { Ok(false) }
69 fn get_next_channel_announcements(&self, _starting_point: u64, _batch_amount: u8) ->
70 Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> { Vec::new() }
71 fn get_next_node_announcements(&self, _starting_point: Option<&PublicKey>, _batch_amount: u8) -> Vec<msgs::NodeAnnouncement> { Vec::new() }
72 fn sync_routing_table(&self, _their_node_id: &PublicKey, _init: &msgs::Init) {}
73 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), LightningError> { Ok(()) }
74 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), LightningError> { Ok(()) }
75 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), LightningError> { Ok(()) }
76 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), LightningError> { Ok(()) }
78 impl Deref for IgnoringMessageHandler {
79 type Target = IgnoringMessageHandler;
80 fn deref(&self) -> &Self { self }
83 // Implement Type for Infallible, note that it cannot be constructed, and thus you can never call a
84 // method that takes self for it.
85 impl wire::Type for Infallible {
86 fn type_id(&self) -> u16 {
90 impl Writeable for Infallible {
91 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
96 impl wire::CustomMessageReader for IgnoringMessageHandler {
97 type CustomMessage = Infallible;
98 fn read<R: io::Read>(&self, _message_type: u16, _buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
103 impl CustomMessageHandler for IgnoringMessageHandler {
104 fn handle_custom_message(&self, _msg: Infallible, _sender_node_id: &PublicKey) -> Result<(), LightningError> {
105 // Since we always return `None` in the read the handle method should never be called.
109 fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
112 /// A dummy struct which implements `ChannelMessageHandler` without having any channels.
113 /// You can provide one of these as the route_handler in a MessageHandler.
114 pub struct ErroringMessageHandler {
115 message_queue: Mutex<Vec<MessageSendEvent>>
117 impl ErroringMessageHandler {
118 /// Constructs a new ErroringMessageHandler
119 pub fn new() -> Self {
120 Self { message_queue: Mutex::new(Vec::new()) }
122 fn push_error(&self, node_id: &PublicKey, channel_id: [u8; 32]) {
123 self.message_queue.lock().unwrap().push(MessageSendEvent::HandleError {
124 action: msgs::ErrorAction::SendErrorMessage {
125 msg: msgs::ErrorMessage { channel_id, data: "We do not support channel messages, sorry.".to_owned() },
127 node_id: node_id.clone(),
131 impl MessageSendEventsProvider for ErroringMessageHandler {
132 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
133 let mut res = Vec::new();
134 mem::swap(&mut res, &mut self.message_queue.lock().unwrap());
138 impl ChannelMessageHandler for ErroringMessageHandler {
139 // Any messages which are related to a specific channel generate an error message to let the
140 // peer know we don't care about channels.
141 fn handle_open_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::OpenChannel) {
142 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
144 fn handle_accept_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::AcceptChannel) {
145 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
147 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
148 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
150 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
151 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
153 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) {
154 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
156 fn handle_shutdown(&self, their_node_id: &PublicKey, _their_features: &InitFeatures, msg: &msgs::Shutdown) {
157 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
159 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
160 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
162 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
163 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
165 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
166 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
168 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
169 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
171 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
172 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
174 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
175 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
177 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
178 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
180 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
181 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
183 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
184 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
186 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
187 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
189 // msgs::ChannelUpdate does not contain the channel_id field, so we just drop them.
190 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {}
191 fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
192 fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) {}
193 fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
195 impl Deref for ErroringMessageHandler {
196 type Target = ErroringMessageHandler;
197 fn deref(&self) -> &Self { self }
200 /// Provides references to trait impls which handle different types of messages.
201 pub struct MessageHandler<CM: Deref, RM: Deref> where
202 CM::Target: ChannelMessageHandler,
203 RM::Target: RoutingMessageHandler {
204 /// A message handler which handles messages specific to channels. Usually this is just a
205 /// [`ChannelManager`] object or an [`ErroringMessageHandler`].
207 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
208 pub chan_handler: CM,
209 /// A message handler which handles messages updating our knowledge of the network channel
210 /// graph. Usually this is just a [`NetGraphMsgHandler`] object or an
211 /// [`IgnoringMessageHandler`].
213 /// [`NetGraphMsgHandler`]: crate::routing::network_graph::NetGraphMsgHandler
214 pub route_handler: RM,
217 /// Provides an object which can be used to send data to and which uniquely identifies a connection
218 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
219 /// implement Hash to meet the PeerManager API.
221 /// For efficiency, Clone should be relatively cheap for this type.
223 /// Two descriptors may compare equal (by [`cmp::Eq`] and [`hash::Hash`]) as long as the original
224 /// has been disconnected, the [`PeerManager`] has been informed of the disconnection (either by it
225 /// having triggered the disconnection or a call to [`PeerManager::socket_disconnected`]), and no
226 /// further calls to the [`PeerManager`] related to the original socket occur. This allows you to
227 /// use a file descriptor for your SocketDescriptor directly, however for simplicity you may wish
228 /// to simply use another value which is guaranteed to be globally unique instead.
229 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
230 /// Attempts to send some data from the given slice to the peer.
232 /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
233 /// Note that in the disconnected case, [`PeerManager::socket_disconnected`] must still be
234 /// called and further write attempts may occur until that time.
236 /// If the returned size is smaller than `data.len()`, a
237 /// [`PeerManager::write_buffer_space_avail`] call must be made the next time more data can be
238 /// written. Additionally, until a `send_data` event completes fully, no further
239 /// [`PeerManager::read_event`] calls should be made for the same peer! Because this is to
240 /// prevent denial-of-service issues, you should not read or buffer any data from the socket
243 /// If a [`PeerManager::read_event`] call on this descriptor had previously returned true
244 /// (indicating that read events should be paused to prevent DoS in the send buffer),
245 /// `resume_read` may be set indicating that read events on this descriptor should resume. A
246 /// `resume_read` of false carries no meaning, and should not cause any action.
247 fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize;
248 /// Disconnect the socket pointed to by this SocketDescriptor.
250 /// You do *not* need to call [`PeerManager::socket_disconnected`] with this socket after this
251 /// call (doing so is a noop).
252 fn disconnect_socket(&mut self);
255 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
256 /// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the
259 pub struct PeerHandleError {
260 /// Used to indicate that we probably can't make any future connections to this peer, implying
261 /// we should go ahead and force-close any channels we have with it.
262 pub no_connection_possible: bool,
264 impl fmt::Debug for PeerHandleError {
265 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
266 formatter.write_str("Peer Sent Invalid Data")
269 impl fmt::Display for PeerHandleError {
270 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
271 formatter.write_str("Peer Sent Invalid Data")
275 #[cfg(feature = "std")]
276 impl error::Error for PeerHandleError {
277 fn description(&self) -> &str {
278 "Peer Sent Invalid Data"
282 enum InitSyncTracker{
284 ChannelsSyncing(u64),
285 NodesSyncing(PublicKey),
288 /// The ratio between buffer sizes at which we stop sending initial sync messages vs when we stop
289 /// forwarding gossip messages to peers altogether.
290 const FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO: usize = 2;
292 /// When the outbound buffer has this many messages, we'll stop reading bytes from the peer until
293 /// we have fewer than this many messages in the outbound buffer again.
294 /// We also use this as the target number of outbound gossip messages to keep in the write buffer,
295 /// refilled as we send bytes.
296 const OUTBOUND_BUFFER_LIMIT_READ_PAUSE: usize = 10;
297 /// When the outbound buffer has this many messages, we'll simply skip relaying gossip messages to
299 const OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP: usize = OUTBOUND_BUFFER_LIMIT_READ_PAUSE * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO;
301 /// If we've sent a ping, and are still awaiting a response, we may need to churn our way through
302 /// the socket receive buffer before receiving the ping.
304 /// On a fairly old Arm64 board, with Linux defaults, this can take as long as 20 seconds, not
305 /// including any network delays, outbound traffic, or the same for messages from other peers.
307 /// Thus, to avoid needlessly disconnecting a peer, we allow a peer to take this many timer ticks
308 /// per connected peer to respond to a ping, as long as they send us at least one message during
309 /// each tick, ensuring we aren't actually just disconnected.
310 /// With a timer tick interval of five seconds, this translates to about 30 seconds per connected
313 /// When we improve parallelism somewhat we should reduce this to e.g. this many timer ticks per
314 /// two connected peers, assuming most LDK-running systems have at least two cores.
315 const MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER: i8 = 6;
317 /// This is the minimum number of messages we expect a peer to be able to handle within one timer
318 /// tick. Once we have sent this many messages since the last ping, we send a ping right away to
319 /// ensures we don't just fill up our send buffer and leave the peer with too many messages to
320 /// process before the next ping.
321 const BUFFER_DRAIN_MSGS_PER_TICK: usize = 32;
324 channel_encryptor: PeerChannelEncryptor,
325 their_node_id: Option<PublicKey>,
326 their_features: Option<InitFeatures>,
328 pending_outbound_buffer: LinkedList<Vec<u8>>,
329 pending_outbound_buffer_first_msg_offset: usize,
330 awaiting_write_event: bool,
332 pending_read_buffer: Vec<u8>,
333 pending_read_buffer_pos: usize,
334 pending_read_is_header: bool,
336 sync_status: InitSyncTracker,
338 msgs_sent_since_pong: usize,
339 awaiting_pong_timer_tick_intervals: i8,
340 received_message_since_timer_tick: bool,
344 /// Returns true if the channel announcements/updates for the given channel should be
345 /// forwarded to this peer.
346 /// If we are sending our routing table to this peer and we have not yet sent channel
347 /// announcements/updates for the given channel_id then we will send it when we get to that
348 /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
349 /// sent the old versions, we should send the update, and so return true here.
350 fn should_forward_channel_announcement(&self, channel_id: u64)->bool{
351 match self.sync_status {
352 InitSyncTracker::NoSyncRequested => true,
353 InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
354 InitSyncTracker::NodesSyncing(_) => true,
358 /// Similar to the above, but for node announcements indexed by node_id.
359 fn should_forward_node_announcement(&self, node_id: PublicKey) -> bool {
360 match self.sync_status {
361 InitSyncTracker::NoSyncRequested => true,
362 InitSyncTracker::ChannelsSyncing(_) => false,
363 InitSyncTracker::NodesSyncing(pk) => pk < node_id,
368 struct PeerHolder<Descriptor: SocketDescriptor> {
369 peers: HashMap<Descriptor, Peer>,
370 /// Only add to this set when noise completes:
371 node_id_to_descriptor: HashMap<PublicKey, Descriptor>,
374 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
375 fn _check_usize_is_32_or_64() {
376 // See below, less than 32 bit pointers may be unsafe here!
377 unsafe { mem::transmute::<*const usize, [u8; 4]>(panic!()); }
380 /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
381 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
382 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
383 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
384 /// issues such as overly long function definitions.
385 pub type SimpleArcPeerManager<SD, M, T, F, C, L> = PeerManager<SD, Arc<SimpleArcChannelManager<M, T, F, L>>, Arc<NetGraphMsgHandler<Arc<C>, Arc<L>>>, Arc<L>, Arc<IgnoringMessageHandler>>;
387 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
388 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
389 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
390 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
391 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
392 /// helps with issues such as long function definitions.
393 pub type SimpleRefPeerManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, SD, M, T, F, C, L> = PeerManager<SD, SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L>, &'e NetGraphMsgHandler<&'g C, &'f L>, &'f L, IgnoringMessageHandler>;
395 /// A PeerManager manages a set of peers, described by their [`SocketDescriptor`] and marshalls
396 /// socket events into messages which it passes on to its [`MessageHandler`].
398 /// Locks are taken internally, so you must never assume that reentrancy from a
399 /// [`SocketDescriptor`] call back into [`PeerManager`] methods will not deadlock.
401 /// Calls to [`read_event`] will decode relevant messages and pass them to the
402 /// [`ChannelMessageHandler`], likely doing message processing in-line. Thus, the primary form of
403 /// parallelism in Rust-Lightning is in calls to [`read_event`]. Note, however, that calls to any
404 /// [`PeerManager`] functions related to the same connection must occur only in serial, making new
405 /// calls only after previous ones have returned.
407 /// Rather than using a plain PeerManager, it is preferable to use either a SimpleArcPeerManager
408 /// a SimpleRefPeerManager, for conciseness. See their documentation for more details, but
409 /// essentially you should default to using a SimpleRefPeerManager, and use a
410 /// SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when
411 /// you're using lightning-net-tokio.
413 /// [`read_event`]: PeerManager::read_event
414 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> where
415 CM::Target: ChannelMessageHandler,
416 RM::Target: RoutingMessageHandler,
418 CMH::Target: CustomMessageHandler {
419 message_handler: MessageHandler<CM, RM>,
420 peers: Mutex<PeerHolder<Descriptor>>,
421 our_node_secret: SecretKey,
422 ephemeral_key_midstate: Sha256Engine,
423 custom_message_handler: CMH,
425 // Usize needs to be at least 32 bits to avoid overflowing both low and high. If usize is 64
426 // bits we will never realistically count into high:
427 peer_counter_low: AtomicUsize,
428 peer_counter_high: AtomicUsize,
433 enum MessageHandlingError {
434 PeerHandleError(PeerHandleError),
435 LightningError(LightningError),
438 impl From<PeerHandleError> for MessageHandlingError {
439 fn from(error: PeerHandleError) -> Self {
440 MessageHandlingError::PeerHandleError(error)
444 impl From<LightningError> for MessageHandlingError {
445 fn from(error: LightningError) -> Self {
446 MessageHandlingError::LightningError(error)
450 macro_rules! encode_msg {
452 let mut buffer = VecWriter(Vec::new());
453 wire::write($msg, &mut buffer).unwrap();
458 impl<Descriptor: SocketDescriptor, CM: Deref, L: Deref> PeerManager<Descriptor, CM, IgnoringMessageHandler, L, IgnoringMessageHandler> where
459 CM::Target: ChannelMessageHandler,
461 /// Constructs a new PeerManager with the given ChannelMessageHandler. No routing message
462 /// handler is used and network graph messages are ignored.
464 /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
465 /// cryptographically secure random bytes.
467 /// (C-not exported) as we can't export a PeerManager with a dummy route handler
468 pub fn new_channel_only(channel_message_handler: CM, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
469 Self::new(MessageHandler {
470 chan_handler: channel_message_handler,
471 route_handler: IgnoringMessageHandler{},
472 }, our_node_secret, ephemeral_random_data, logger, IgnoringMessageHandler{})
476 impl<Descriptor: SocketDescriptor, RM: Deref, L: Deref> PeerManager<Descriptor, ErroringMessageHandler, RM, L, IgnoringMessageHandler> where
477 RM::Target: RoutingMessageHandler,
479 /// Constructs a new PeerManager with the given RoutingMessageHandler. No channel message
480 /// handler is used and messages related to channels will be ignored (or generate error
481 /// messages). Note that some other lightning implementations time-out connections after some
482 /// time if no channel is built with the peer.
484 /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
485 /// cryptographically secure random bytes.
487 /// (C-not exported) as we can't export a PeerManager with a dummy channel handler
488 pub fn new_routing_only(routing_message_handler: RM, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
489 Self::new(MessageHandler {
490 chan_handler: ErroringMessageHandler::new(),
491 route_handler: routing_message_handler,
492 }, our_node_secret, ephemeral_random_data, logger, IgnoringMessageHandler{})
496 /// A simple wrapper that optionally prints " from <pubkey>" for an optional pubkey.
497 /// This works around `format!()` taking a reference to each argument, preventing
498 /// `if let Some(node_id) = peer.their_node_id { format!(.., node_id) } else { .. }` from compiling
499 /// due to lifetime errors.
500 struct OptionalFromDebugger<'a>(&'a Option<PublicKey>);
501 impl core::fmt::Display for OptionalFromDebugger<'_> {
502 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
503 if let Some(node_id) = self.0 { write!(f, " from {}", log_pubkey!(node_id)) } else { Ok(()) }
507 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> PeerManager<Descriptor, CM, RM, L, CMH> where
508 CM::Target: ChannelMessageHandler,
509 RM::Target: RoutingMessageHandler,
511 CMH::Target: CustomMessageHandler {
512 /// Constructs a new PeerManager with the given message handlers and node_id secret key
513 /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
514 /// cryptographically secure random bytes.
515 pub fn new(message_handler: MessageHandler<CM, RM>, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L, custom_message_handler: CMH) -> Self {
516 let mut ephemeral_key_midstate = Sha256::engine();
517 ephemeral_key_midstate.input(ephemeral_random_data);
521 peers: Mutex::new(PeerHolder {
522 peers: HashMap::new(),
523 node_id_to_descriptor: HashMap::new()
526 ephemeral_key_midstate,
527 peer_counter_low: AtomicUsize::new(0),
528 peer_counter_high: AtomicUsize::new(0),
530 custom_message_handler,
534 /// Get the list of node ids for peers which have completed the initial handshake.
536 /// For outbound connections, this will be the same as the their_node_id parameter passed in to
537 /// new_outbound_connection, however entries will only appear once the initial handshake has
538 /// completed and we are sure the remote peer has the private key for the given node_id.
539 pub fn get_peer_node_ids(&self) -> Vec<PublicKey> {
540 let peers = self.peers.lock().unwrap();
541 peers.peers.values().filter_map(|p| {
542 if !p.channel_encryptor.is_ready_for_encryption() || p.their_features.is_none() {
549 fn get_ephemeral_key(&self) -> SecretKey {
550 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
551 let low = self.peer_counter_low.fetch_add(1, Ordering::AcqRel);
552 let high = if low == 0 {
553 self.peer_counter_high.fetch_add(1, Ordering::AcqRel)
555 self.peer_counter_high.load(Ordering::Acquire)
557 ephemeral_hash.input(&byte_utils::le64_to_array(low as u64));
558 ephemeral_hash.input(&byte_utils::le64_to_array(high as u64));
559 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!")
562 /// Indicates a new outbound connection has been established to a node with the given node_id.
563 /// Note that if an Err is returned here you MUST NOT call socket_disconnected for the new
564 /// descriptor but must disconnect the connection immediately.
566 /// Returns a small number of bytes to send to the remote node (currently always 50).
568 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
569 /// [`socket_disconnected()`].
571 /// [`socket_disconnected()`]: PeerManager::socket_disconnected
572 pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor) -> Result<Vec<u8>, PeerHandleError> {
573 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
574 let res = peer_encryptor.get_act_one().to_vec();
575 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
577 let mut peers = self.peers.lock().unwrap();
578 if peers.peers.insert(descriptor, Peer {
579 channel_encryptor: peer_encryptor,
581 their_features: None,
583 pending_outbound_buffer: LinkedList::new(),
584 pending_outbound_buffer_first_msg_offset: 0,
585 awaiting_write_event: false,
588 pending_read_buffer_pos: 0,
589 pending_read_is_header: false,
591 sync_status: InitSyncTracker::NoSyncRequested,
593 msgs_sent_since_pong: 0,
594 awaiting_pong_timer_tick_intervals: 0,
595 received_message_since_timer_tick: false,
597 panic!("PeerManager driver duplicated descriptors!");
602 /// Indicates a new inbound connection has been established.
604 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
605 /// (outbound connector always speaks first). Note that if an Err is returned here you MUST NOT
606 /// call socket_disconnected for the new descriptor but must disconnect the connection
609 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
610 /// [`socket_disconnected()`].
612 /// [`socket_disconnected()`]: PeerManager::socket_disconnected
613 pub fn new_inbound_connection(&self, descriptor: Descriptor) -> Result<(), PeerHandleError> {
614 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret);
615 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
617 let mut peers = self.peers.lock().unwrap();
618 if peers.peers.insert(descriptor, Peer {
619 channel_encryptor: peer_encryptor,
621 their_features: None,
623 pending_outbound_buffer: LinkedList::new(),
624 pending_outbound_buffer_first_msg_offset: 0,
625 awaiting_write_event: false,
628 pending_read_buffer_pos: 0,
629 pending_read_is_header: false,
631 sync_status: InitSyncTracker::NoSyncRequested,
633 msgs_sent_since_pong: 0,
634 awaiting_pong_timer_tick_intervals: 0,
635 received_message_since_timer_tick: false,
637 panic!("PeerManager driver duplicated descriptors!");
642 fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer) {
643 while !peer.awaiting_write_event {
644 if peer.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE && peer.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK {
645 match peer.sync_status {
646 InitSyncTracker::NoSyncRequested => {},
647 InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
648 let steps = ((OUTBOUND_BUFFER_LIMIT_READ_PAUSE - peer.pending_outbound_buffer.len() + 2) / 3) as u8;
649 let all_messages = self.message_handler.route_handler.get_next_channel_announcements(c, steps);
650 for &(ref announce, ref update_a_option, ref update_b_option) in all_messages.iter() {
651 self.enqueue_message(peer, announce);
652 if let &Some(ref update_a) = update_a_option {
653 self.enqueue_message(peer, update_a);
655 if let &Some(ref update_b) = update_b_option {
656 self.enqueue_message(peer, update_b);
658 peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
660 if all_messages.is_empty() || all_messages.len() != steps as usize {
661 peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
664 InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
665 let steps = (OUTBOUND_BUFFER_LIMIT_READ_PAUSE - peer.pending_outbound_buffer.len()) as u8;
666 let all_messages = self.message_handler.route_handler.get_next_node_announcements(None, steps);
667 for msg in all_messages.iter() {
668 self.enqueue_message(peer, msg);
669 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
671 if all_messages.is_empty() || all_messages.len() != steps as usize {
672 peer.sync_status = InitSyncTracker::NoSyncRequested;
675 InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
676 InitSyncTracker::NodesSyncing(key) => {
677 let steps = (OUTBOUND_BUFFER_LIMIT_READ_PAUSE - peer.pending_outbound_buffer.len()) as u8;
678 let all_messages = self.message_handler.route_handler.get_next_node_announcements(Some(&key), steps);
679 for msg in all_messages.iter() {
680 self.enqueue_message(peer, msg);
681 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
683 if all_messages.is_empty() || all_messages.len() != steps as usize {
684 peer.sync_status = InitSyncTracker::NoSyncRequested;
689 if peer.msgs_sent_since_pong >= BUFFER_DRAIN_MSGS_PER_TICK {
690 self.maybe_send_extra_ping(peer);
694 let next_buff = match peer.pending_outbound_buffer.front() {
699 let should_be_reading = peer.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE;
700 let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
701 let data_sent = descriptor.send_data(pending, should_be_reading);
702 peer.pending_outbound_buffer_first_msg_offset += data_sent;
703 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() { true } else { false }
705 peer.pending_outbound_buffer_first_msg_offset = 0;
706 peer.pending_outbound_buffer.pop_front();
708 peer.awaiting_write_event = true;
713 /// Indicates that there is room to write data to the given socket descriptor.
715 /// May return an Err to indicate that the connection should be closed.
717 /// May call [`send_data`] on the descriptor passed in (or an equal descriptor) before
718 /// returning. Thus, be very careful with reentrancy issues! The invariants around calling
719 /// [`write_buffer_space_avail`] in case a write did not fully complete must still hold - be
720 /// ready to call `[write_buffer_space_avail`] again if a write call generated here isn't
723 /// [`send_data`]: SocketDescriptor::send_data
724 /// [`write_buffer_space_avail`]: PeerManager::write_buffer_space_avail
725 pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
726 let mut peers = self.peers.lock().unwrap();
727 match peers.peers.get_mut(descriptor) {
729 // This is most likely a simple race condition where the user found that the socket
730 // was writeable, then we told the user to `disconnect_socket()`, then they called
731 // this method. Return an error to make sure we get disconnected.
732 return Err(PeerHandleError { no_connection_possible: false });
735 peer.awaiting_write_event = false;
736 self.do_attempt_write_data(descriptor, peer);
742 /// Indicates that data was read from the given socket descriptor.
744 /// May return an Err to indicate that the connection should be closed.
746 /// Will *not* call back into [`send_data`] on any descriptors to avoid reentrancy complexity.
747 /// Thus, however, you should call [`process_events`] after any `read_event` to generate
748 /// [`send_data`] calls to handle responses.
750 /// If `Ok(true)` is returned, further read_events should not be triggered until a
751 /// [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the
754 /// [`send_data`]: SocketDescriptor::send_data
755 /// [`process_events`]: PeerManager::process_events
756 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
757 match self.do_read_event(peer_descriptor, data) {
760 log_trace!(self.logger, "Peer sent invalid data or we decided to disconnect due to a protocol error");
761 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
767 /// Append a message to a peer's pending outbound/write buffer
768 fn enqueue_encoded_message(&self, peer: &mut Peer, encoded_message: &Vec<u8>) {
769 peer.msgs_sent_since_pong += 1;
770 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_message[..]));
773 /// Append a message to a peer's pending outbound/write buffer
774 fn enqueue_message<M: wire::Type>(&self, peer: &mut Peer, message: &M) {
775 let mut buffer = VecWriter(Vec::with_capacity(2048));
776 wire::write(message, &mut buffer).unwrap(); // crash if the write failed
777 log_trace!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap()));
778 self.enqueue_encoded_message(peer, &buffer.0);
781 fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
783 let mut peers_lock = self.peers.lock().unwrap();
784 let peers = &mut *peers_lock;
785 let mut msgs_to_forward = Vec::new();
786 let mut peer_node_id = None;
787 let pause_read = match peers.peers.get_mut(peer_descriptor) {
789 // This is most likely a simple race condition where the user read some bytes
790 // from the socket, then we told the user to `disconnect_socket()`, then they
791 // called this method. Return an error to make sure we get disconnected.
792 return Err(PeerHandleError { no_connection_possible: false });
795 assert!(peer.pending_read_buffer.len() > 0);
796 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
798 let mut read_pos = 0;
799 while read_pos < data.len() {
801 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
802 peer.pending_read_buffer[peer.pending_read_buffer_pos..peer.pending_read_buffer_pos + data_to_copy].copy_from_slice(&data[read_pos..read_pos + data_to_copy]);
803 read_pos += data_to_copy;
804 peer.pending_read_buffer_pos += data_to_copy;
807 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
808 peer.pending_read_buffer_pos = 0;
810 macro_rules! try_potential_handleerror {
816 msgs::ErrorAction::DisconnectPeer { msg: _ } => {
817 //TODO: Try to push msg
818 log_debug!(self.logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer.their_node_id), e.err);
819 return Err(PeerHandleError{ no_connection_possible: false });
821 msgs::ErrorAction::IgnoreAndLog(level) => {
822 log_given_level!(self.logger, level, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer.their_node_id), e.err);
825 msgs::ErrorAction::IgnoreError => {
826 log_debug!(self.logger, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer.their_node_id), e.err);
829 msgs::ErrorAction::SendErrorMessage { msg } => {
830 log_debug!(self.logger, "Error handling message{}; sending error message with: {}", OptionalFromDebugger(&peer.their_node_id), e.err);
831 self.enqueue_message(peer, &msg);
840 macro_rules! insert_node_id {
842 match peers.node_id_to_descriptor.entry(peer.their_node_id.unwrap()) {
843 hash_map::Entry::Occupied(_) => {
844 log_trace!(self.logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap()));
845 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
846 return Err(PeerHandleError{ no_connection_possible: false })
848 hash_map::Entry::Vacant(entry) => {
849 log_debug!(self.logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap()));
850 entry.insert(peer_descriptor.clone())
856 let next_step = peer.channel_encryptor.get_noise_step();
858 NextNoiseStep::ActOne => {
859 let act_two = try_potential_handleerror!(peer.channel_encryptor.process_act_one_with_keys(&peer.pending_read_buffer[..], &self.our_node_secret, self.get_ephemeral_key())).to_vec();
860 peer.pending_outbound_buffer.push_back(act_two);
861 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
863 NextNoiseStep::ActTwo => {
864 let (act_three, their_node_id) = try_potential_handleerror!(peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], &self.our_node_secret));
865 peer.pending_outbound_buffer.push_back(act_three.to_vec());
866 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
867 peer.pending_read_is_header = true;
869 peer.their_node_id = Some(their_node_id);
871 let features = InitFeatures::known();
872 let resp = msgs::Init { features };
873 self.enqueue_message(peer, &resp);
874 peer.awaiting_pong_timer_tick_intervals = 0;
876 NextNoiseStep::ActThree => {
877 let their_node_id = try_potential_handleerror!(peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
878 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
879 peer.pending_read_is_header = true;
880 peer.their_node_id = Some(their_node_id);
882 let features = InitFeatures::known();
883 let resp = msgs::Init { features };
884 self.enqueue_message(peer, &resp);
885 peer.awaiting_pong_timer_tick_intervals = 0;
887 NextNoiseStep::NoiseComplete => {
888 if peer.pending_read_is_header {
889 let msg_len = try_potential_handleerror!(peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
890 peer.pending_read_buffer = Vec::with_capacity(msg_len as usize + 16);
891 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
892 if msg_len < 2 { // Need at least the message type tag
893 return Err(PeerHandleError{ no_connection_possible: false });
895 peer.pending_read_is_header = false;
897 let msg_data = try_potential_handleerror!(peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
898 assert!(msg_data.len() >= 2);
901 peer.pending_read_buffer = [0; 18].to_vec();
902 peer.pending_read_is_header = true;
904 let mut reader = io::Cursor::new(&msg_data[..]);
905 let message_result = wire::read(&mut reader, &*self.custom_message_handler);
906 let message = match message_result {
910 msgs::DecodeError::UnknownVersion => return Err(PeerHandleError { no_connection_possible: false }),
911 msgs::DecodeError::UnknownRequiredFeature => {
912 log_trace!(self.logger, "Got a channel/node announcement with an known required feature flag, you may want to update!");
915 msgs::DecodeError::InvalidValue => {
916 log_debug!(self.logger, "Got an invalid value while deserializing message");
917 return Err(PeerHandleError { no_connection_possible: false });
919 msgs::DecodeError::ShortRead => {
920 log_debug!(self.logger, "Deserialization failed due to shortness of message");
921 return Err(PeerHandleError { no_connection_possible: false });
923 msgs::DecodeError::BadLengthDescriptor => return Err(PeerHandleError { no_connection_possible: false }),
924 msgs::DecodeError::Io(_) => return Err(PeerHandleError { no_connection_possible: false }),
925 msgs::DecodeError::UnsupportedCompression => {
926 log_trace!(self.logger, "We don't support zlib-compressed message fields, ignoring message");
933 match self.handle_message(peer, message) {
934 Err(handling_error) => match handling_error {
935 MessageHandlingError::PeerHandleError(e) => { return Err(e) },
936 MessageHandlingError::LightningError(e) => {
937 try_potential_handleerror!(Err(e));
941 peer_node_id = Some(peer.their_node_id.expect("After noise is complete, their_node_id is always set"));
942 msgs_to_forward.push(msg);
952 peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_READ_PAUSE // pause_read
956 for msg in msgs_to_forward.drain(..) {
957 self.forward_broadcast_msg(peers, &msg, peer_node_id.as_ref());
966 /// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer
967 /// Returns the message back if it needs to be broadcasted to all other peers.
971 message: wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>
972 ) -> Result<Option<wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError> {
973 log_trace!(self.logger, "Received message {:?} from {}", message, log_pubkey!(peer.their_node_id.unwrap()));
974 peer.received_message_since_timer_tick = true;
976 // Need an Init as first message
977 if let wire::Message::Init(_) = message {
978 } else if peer.their_features.is_none() {
979 log_debug!(self.logger, "Peer {} sent non-Init first message", log_pubkey!(peer.their_node_id.unwrap()));
980 return Err(PeerHandleError{ no_connection_possible: false }.into());
983 let mut should_forward = None;
986 // Setup and Control messages:
987 wire::Message::Init(msg) => {
988 if msg.features.requires_unknown_bits() {
989 log_debug!(self.logger, "Peer features required unknown version bits");
990 return Err(PeerHandleError{ no_connection_possible: true }.into());
992 if peer.their_features.is_some() {
993 return Err(PeerHandleError{ no_connection_possible: false }.into());
996 log_info!(self.logger, "Received peer Init message from {}: {}", log_pubkey!(peer.their_node_id.unwrap()), msg.features);
998 if msg.features.initial_routing_sync() {
999 peer.sync_status = InitSyncTracker::ChannelsSyncing(0);
1001 if !msg.features.supports_static_remote_key() {
1002 log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting with no_connection_possible", log_pubkey!(peer.their_node_id.unwrap()));
1003 return Err(PeerHandleError{ no_connection_possible: true }.into());
1006 self.message_handler.route_handler.sync_routing_table(&peer.their_node_id.unwrap(), &msg);
1008 self.message_handler.chan_handler.peer_connected(&peer.their_node_id.unwrap(), &msg);
1009 peer.their_features = Some(msg.features);
1011 wire::Message::Error(msg) => {
1012 let mut data_is_printable = true;
1013 for b in msg.data.bytes() {
1014 if b < 32 || b > 126 {
1015 data_is_printable = false;
1020 if data_is_printable {
1021 log_debug!(self.logger, "Got Err message from {}: {}", log_pubkey!(peer.their_node_id.unwrap()), msg.data);
1023 log_debug!(self.logger, "Got Err message from {} with non-ASCII error message", log_pubkey!(peer.their_node_id.unwrap()));
1025 self.message_handler.chan_handler.handle_error(&peer.their_node_id.unwrap(), &msg);
1026 if msg.channel_id == [0; 32] {
1027 return Err(PeerHandleError{ no_connection_possible: true }.into());
1031 wire::Message::Ping(msg) => {
1032 if msg.ponglen < 65532 {
1033 let resp = msgs::Pong { byteslen: msg.ponglen };
1034 self.enqueue_message(peer, &resp);
1037 wire::Message::Pong(_msg) => {
1038 peer.awaiting_pong_timer_tick_intervals = 0;
1039 peer.msgs_sent_since_pong = 0;
1042 // Channel messages:
1043 wire::Message::OpenChannel(msg) => {
1044 self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg);
1046 wire::Message::AcceptChannel(msg) => {
1047 self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg);
1050 wire::Message::FundingCreated(msg) => {
1051 self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg);
1053 wire::Message::FundingSigned(msg) => {
1054 self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg);
1056 wire::Message::FundingLocked(msg) => {
1057 self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg);
1060 wire::Message::Shutdown(msg) => {
1061 self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), peer.their_features.as_ref().unwrap(), &msg);
1063 wire::Message::ClosingSigned(msg) => {
1064 self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg);
1067 // Commitment messages:
1068 wire::Message::UpdateAddHTLC(msg) => {
1069 self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg);
1071 wire::Message::UpdateFulfillHTLC(msg) => {
1072 self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg);
1074 wire::Message::UpdateFailHTLC(msg) => {
1075 self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg);
1077 wire::Message::UpdateFailMalformedHTLC(msg) => {
1078 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg);
1081 wire::Message::CommitmentSigned(msg) => {
1082 self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg);
1084 wire::Message::RevokeAndACK(msg) => {
1085 self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg);
1087 wire::Message::UpdateFee(msg) => {
1088 self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg);
1090 wire::Message::ChannelReestablish(msg) => {
1091 self.message_handler.chan_handler.handle_channel_reestablish(&peer.their_node_id.unwrap(), &msg);
1094 // Routing messages:
1095 wire::Message::AnnouncementSignatures(msg) => {
1096 self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg);
1098 wire::Message::ChannelAnnouncement(msg) => {
1099 if self.message_handler.route_handler.handle_channel_announcement(&msg)
1100 .map_err(|e| -> MessageHandlingError { e.into() })? {
1101 should_forward = Some(wire::Message::ChannelAnnouncement(msg));
1104 wire::Message::NodeAnnouncement(msg) => {
1105 if self.message_handler.route_handler.handle_node_announcement(&msg)
1106 .map_err(|e| -> MessageHandlingError { e.into() })? {
1107 should_forward = Some(wire::Message::NodeAnnouncement(msg));
1110 wire::Message::ChannelUpdate(msg) => {
1111 self.message_handler.chan_handler.handle_channel_update(&peer.their_node_id.unwrap(), &msg);
1112 if self.message_handler.route_handler.handle_channel_update(&msg)
1113 .map_err(|e| -> MessageHandlingError { e.into() })? {
1114 should_forward = Some(wire::Message::ChannelUpdate(msg));
1117 wire::Message::QueryShortChannelIds(msg) => {
1118 self.message_handler.route_handler.handle_query_short_channel_ids(&peer.their_node_id.unwrap(), msg)?;
1120 wire::Message::ReplyShortChannelIdsEnd(msg) => {
1121 self.message_handler.route_handler.handle_reply_short_channel_ids_end(&peer.their_node_id.unwrap(), msg)?;
1123 wire::Message::QueryChannelRange(msg) => {
1124 self.message_handler.route_handler.handle_query_channel_range(&peer.their_node_id.unwrap(), msg)?;
1126 wire::Message::ReplyChannelRange(msg) => {
1127 self.message_handler.route_handler.handle_reply_channel_range(&peer.their_node_id.unwrap(), msg)?;
1129 wire::Message::GossipTimestampFilter(_msg) => {
1130 // TODO: handle message
1133 // Unknown messages:
1134 wire::Message::Unknown(type_id) if message.is_even() => {
1135 log_debug!(self.logger, "Received unknown even message of type {}, disconnecting peer!", type_id);
1136 // Fail the channel if message is an even, unknown type as per BOLT #1.
1137 return Err(PeerHandleError{ no_connection_possible: true }.into());
1139 wire::Message::Unknown(type_id) => {
1140 log_trace!(self.logger, "Received unknown odd message of type {}, ignoring", type_id);
1142 wire::Message::Custom(custom) => {
1143 self.custom_message_handler.handle_custom_message(custom, &peer.their_node_id.unwrap())?;
1149 fn forward_broadcast_msg(&self, peers: &mut PeerHolder<Descriptor>, msg: &wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>, except_node: Option<&PublicKey>) {
1151 wire::Message::ChannelAnnouncement(ref msg) => {
1152 log_trace!(self.logger, "Sending message to all peers except {:?} or the announced channel's counterparties: {:?}", except_node, msg);
1153 let encoded_msg = encode_msg!(msg);
1155 for (_, peer) in peers.peers.iter_mut() {
1156 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1157 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1160 if peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP
1161 || peer.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_SIZE_LIMIT
1163 log_trace!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1166 if peer.their_node_id.as_ref() == Some(&msg.contents.node_id_1) ||
1167 peer.their_node_id.as_ref() == Some(&msg.contents.node_id_2) {
1170 if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1173 self.enqueue_encoded_message(peer, &encoded_msg);
1176 wire::Message::NodeAnnouncement(ref msg) => {
1177 log_trace!(self.logger, "Sending message to all peers except {:?} or the announced node: {:?}", except_node, msg);
1178 let encoded_msg = encode_msg!(msg);
1180 for (_, peer) in peers.peers.iter_mut() {
1181 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1182 !peer.should_forward_node_announcement(msg.contents.node_id) {
1185 if peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP
1186 || peer.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_SIZE_LIMIT
1188 log_trace!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1191 if peer.their_node_id.as_ref() == Some(&msg.contents.node_id) {
1194 if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1197 self.enqueue_encoded_message(peer, &encoded_msg);
1200 wire::Message::ChannelUpdate(ref msg) => {
1201 log_trace!(self.logger, "Sending message to all peers except {:?}: {:?}", except_node, msg);
1202 let encoded_msg = encode_msg!(msg);
1204 for (_, peer) in peers.peers.iter_mut() {
1205 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1206 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1209 if peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP
1210 || peer.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_SIZE_LIMIT
1212 log_trace!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1215 if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1218 self.enqueue_encoded_message(peer, &encoded_msg);
1221 _ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),
1225 /// Checks for any events generated by our handlers and processes them. Includes sending most
1226 /// response messages as well as messages generated by calls to handler functions directly (eg
1227 /// functions like [`ChannelManager::process_pending_htlc_forwards`] or [`send_payment`]).
1229 /// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1232 /// You don't have to call this function explicitly if you are using [`lightning-net-tokio`]
1233 /// or one of the other clients provided in our language bindings.
1235 /// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1236 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
1237 /// [`send_data`]: SocketDescriptor::send_data
1238 pub fn process_events(&self) {
1240 // TODO: There are some DoS attacks here where you can flood someone's outbound send
1241 // buffer by doing things like announcing channels on another node. We should be willing to
1242 // drop optional-ish messages when send buffers get full!
1244 let mut peers_lock = self.peers.lock().unwrap();
1245 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
1246 events_generated.append(&mut self.message_handler.route_handler.get_and_clear_pending_msg_events());
1247 let peers = &mut *peers_lock;
1248 macro_rules! get_peer_for_forwarding {
1249 ($node_id: expr) => {
1251 match peers.node_id_to_descriptor.get($node_id) {
1252 Some(descriptor) => match peers.peers.get_mut(&descriptor) {
1254 if peer.their_features.is_none() {
1259 None => panic!("Inconsistent peers set state!"),
1268 for event in events_generated.drain(..) {
1270 MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
1271 log_debug!(self.logger, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
1272 log_pubkey!(node_id),
1273 log_bytes!(msg.temporary_channel_id));
1274 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1276 MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
1277 log_debug!(self.logger, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
1278 log_pubkey!(node_id),
1279 log_bytes!(msg.temporary_channel_id));
1280 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1282 MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
1283 log_debug!(self.logger, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
1284 log_pubkey!(node_id),
1285 log_bytes!(msg.temporary_channel_id),
1286 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
1287 // TODO: If the peer is gone we should generate a DiscardFunding event
1288 // indicating to the wallet that they should just throw away this funding transaction
1289 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1291 MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
1292 log_debug!(self.logger, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
1293 log_pubkey!(node_id),
1294 log_bytes!(msg.channel_id));
1295 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1297 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
1298 log_debug!(self.logger, "Handling SendFundingLocked event in peer_handler for node {} for channel {}",
1299 log_pubkey!(node_id),
1300 log_bytes!(msg.channel_id));
1301 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1303 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
1304 log_debug!(self.logger, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
1305 log_pubkey!(node_id),
1306 log_bytes!(msg.channel_id));
1307 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1309 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
1310 log_debug!(self.logger, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
1311 log_pubkey!(node_id),
1312 update_add_htlcs.len(),
1313 update_fulfill_htlcs.len(),
1314 update_fail_htlcs.len(),
1315 log_bytes!(commitment_signed.channel_id));
1316 let peer = get_peer_for_forwarding!(node_id);
1317 for msg in update_add_htlcs {
1318 self.enqueue_message(peer, msg);
1320 for msg in update_fulfill_htlcs {
1321 self.enqueue_message(peer, msg);
1323 for msg in update_fail_htlcs {
1324 self.enqueue_message(peer, msg);
1326 for msg in update_fail_malformed_htlcs {
1327 self.enqueue_message(peer, msg);
1329 if let &Some(ref msg) = update_fee {
1330 self.enqueue_message(peer, msg);
1332 self.enqueue_message(peer, commitment_signed);
1334 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1335 log_debug!(self.logger, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
1336 log_pubkey!(node_id),
1337 log_bytes!(msg.channel_id));
1338 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1340 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1341 log_debug!(self.logger, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
1342 log_pubkey!(node_id),
1343 log_bytes!(msg.channel_id));
1344 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1346 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
1347 log_debug!(self.logger, "Handling Shutdown event in peer_handler for node {} for channel {}",
1348 log_pubkey!(node_id),
1349 log_bytes!(msg.channel_id));
1350 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1352 MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
1353 log_debug!(self.logger, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
1354 log_pubkey!(node_id),
1355 log_bytes!(msg.channel_id));
1356 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1358 MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
1359 log_debug!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1360 if self.message_handler.route_handler.handle_channel_announcement(&msg).is_ok() && self.message_handler.route_handler.handle_channel_update(&update_msg).is_ok() {
1361 self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None);
1362 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(update_msg), None);
1365 MessageSendEvent::BroadcastNodeAnnouncement { msg } => {
1366 log_debug!(self.logger, "Handling BroadcastNodeAnnouncement event in peer_handler");
1367 if self.message_handler.route_handler.handle_node_announcement(&msg).is_ok() {
1368 self.forward_broadcast_msg(peers, &wire::Message::NodeAnnouncement(msg), None);
1371 MessageSendEvent::BroadcastChannelUpdate { msg } => {
1372 log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1373 if self.message_handler.route_handler.handle_channel_update(&msg).is_ok() {
1374 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None);
1377 MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
1378 log_trace!(self.logger, "Handling SendChannelUpdate event in peer_handler for node {} for channel {}",
1379 log_pubkey!(node_id), msg.contents.short_channel_id);
1380 let peer = get_peer_for_forwarding!(node_id);
1381 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1383 MessageSendEvent::HandleError { ref node_id, ref action } => {
1385 msgs::ErrorAction::DisconnectPeer { ref msg } => {
1386 if let Some(mut descriptor) = peers.node_id_to_descriptor.remove(node_id) {
1387 if let Some(mut peer) = peers.peers.remove(&descriptor) {
1388 if let Some(ref msg) = *msg {
1389 log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
1390 log_pubkey!(node_id),
1392 self.enqueue_message(&mut peer, msg);
1393 // This isn't guaranteed to work, but if there is enough free
1394 // room in the send buffer, put the error message there...
1395 self.do_attempt_write_data(&mut descriptor, &mut peer);
1397 log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with no message", log_pubkey!(node_id));
1400 descriptor.disconnect_socket();
1401 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1404 msgs::ErrorAction::IgnoreAndLog(level) => {
1405 log_given_level!(self.logger, level, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
1407 msgs::ErrorAction::IgnoreError => {
1408 log_debug!(self.logger, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
1410 msgs::ErrorAction::SendErrorMessage { ref msg } => {
1411 log_trace!(self.logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
1412 log_pubkey!(node_id),
1414 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1418 MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
1419 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1421 MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
1422 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1424 MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
1425 log_trace!(self.logger, "Handling SendReplyChannelRange event in peer_handler for node {} with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}",
1426 log_pubkey!(node_id),
1427 msg.short_channel_ids.len(),
1429 msg.number_of_blocks,
1431 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1436 for (node_id, msg) in self.custom_message_handler.get_and_clear_pending_msg() {
1437 self.enqueue_message(get_peer_for_forwarding!(&node_id), &msg);
1440 for (descriptor, peer) in peers.peers.iter_mut() {
1441 self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
1446 /// Indicates that the given socket descriptor's connection is now closed.
1447 pub fn socket_disconnected(&self, descriptor: &Descriptor) {
1448 self.disconnect_event_internal(descriptor, false);
1451 fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
1452 let mut peers = self.peers.lock().unwrap();
1453 let peer_option = peers.peers.remove(descriptor);
1456 // This is most likely a simple race condition where the user found that the socket
1457 // was disconnected, then we told the user to `disconnect_socket()`, then they
1458 // called this method. Either way we're disconnected, return.
1461 match peer.their_node_id {
1463 log_trace!(self.logger,
1464 "Handling disconnection of peer {}, with {}future connection to the peer possible.",
1465 log_pubkey!(node_id), if no_connection_possible { "no " } else { "" });
1466 peers.node_id_to_descriptor.remove(&node_id);
1467 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1475 /// Disconnect a peer given its node id.
1477 /// Set `no_connection_possible` to true to prevent any further connection with this peer,
1478 /// force-closing any channels we have with it.
1480 /// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the
1481 /// peer. Thus, be very careful about reentrancy issues.
1483 /// [`disconnect_socket`]: SocketDescriptor::disconnect_socket
1484 pub fn disconnect_by_node_id(&self, node_id: PublicKey, no_connection_possible: bool) {
1485 let mut peers_lock = self.peers.lock().unwrap();
1486 if let Some(mut descriptor) = peers_lock.node_id_to_descriptor.remove(&node_id) {
1487 log_trace!(self.logger, "Disconnecting peer with id {} due to client request", node_id);
1488 peers_lock.peers.remove(&descriptor);
1489 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1490 descriptor.disconnect_socket();
1494 /// Disconnects all currently-connected peers. This is useful on platforms where there may be
1495 /// an indication that TCP sockets have stalled even if we weren't around to time them out
1496 /// using regular ping/pongs.
1497 pub fn disconnect_all_peers(&self) {
1498 let mut peers_lock = self.peers.lock().unwrap();
1499 let peers = &mut *peers_lock;
1500 for (mut descriptor, peer) in peers.peers.drain() {
1501 if let Some(node_id) = peer.their_node_id {
1502 log_trace!(self.logger, "Disconnecting peer with id {} due to client request to disconnect all peers", node_id);
1503 peers.node_id_to_descriptor.remove(&node_id);
1504 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1506 descriptor.disconnect_socket();
1508 debug_assert!(peers.node_id_to_descriptor.is_empty());
1511 /// This is called when we're blocked on sending additional gossip messages until we receive a
1512 /// pong. If we aren't waiting on a pong, we take this opportunity to send a ping (setting
1513 /// `awaiting_pong_timer_tick_intervals` to a special flag value to indicate this).
1514 fn maybe_send_extra_ping(&self, peer: &mut Peer) {
1515 if peer.awaiting_pong_timer_tick_intervals == 0 {
1516 peer.awaiting_pong_timer_tick_intervals = -1;
1517 let ping = msgs::Ping {
1521 self.enqueue_message(peer, &ping);
1525 /// Send pings to each peer and disconnect those which did not respond to the last round of
1528 /// This may be called on any timescale you want, however, roughly once every five to ten
1529 /// seconds is preferred. The call rate determines both how often we send a ping to our peers
1530 /// and how much time they have to respond before we disconnect them.
1532 /// May call [`send_data`] on all [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1535 /// [`send_data`]: SocketDescriptor::send_data
1536 pub fn timer_tick_occurred(&self) {
1537 let mut peers_lock = self.peers.lock().unwrap();
1539 let peers = &mut *peers_lock;
1540 let node_id_to_descriptor = &mut peers.node_id_to_descriptor;
1541 let peers = &mut peers.peers;
1542 let mut descriptors_needing_disconnect = Vec::new();
1543 let peer_count = peers.len();
1545 peers.retain(|descriptor, peer| {
1546 let mut do_disconnect_peer = false;
1547 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_node_id.is_none() {
1548 // The peer needs to complete its handshake before we can exchange messages. We
1549 // give peers one timer tick to complete handshake, reusing
1550 // `awaiting_pong_timer_tick_intervals` to track number of timer ticks taken
1551 // for handshake completion.
1552 if peer.awaiting_pong_timer_tick_intervals != 0 {
1553 do_disconnect_peer = true;
1555 peer.awaiting_pong_timer_tick_intervals = 1;
1560 if peer.awaiting_pong_timer_tick_intervals == -1 {
1561 // Magic value set in `maybe_send_extra_ping`.
1562 peer.awaiting_pong_timer_tick_intervals = 1;
1563 peer.received_message_since_timer_tick = false;
1567 if do_disconnect_peer
1568 || (peer.awaiting_pong_timer_tick_intervals > 0 && !peer.received_message_since_timer_tick)
1569 || peer.awaiting_pong_timer_tick_intervals as u64 >
1570 MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER as u64 * peer_count as u64
1572 descriptors_needing_disconnect.push(descriptor.clone());
1573 match peer.their_node_id {
1575 log_trace!(self.logger, "Disconnecting peer with id {} due to ping timeout", node_id);
1576 node_id_to_descriptor.remove(&node_id);
1577 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1583 peer.received_message_since_timer_tick = false;
1585 if peer.awaiting_pong_timer_tick_intervals > 0 {
1586 peer.awaiting_pong_timer_tick_intervals += 1;
1590 peer.awaiting_pong_timer_tick_intervals = 1;
1591 let ping = msgs::Ping {
1595 self.enqueue_message(peer, &ping);
1596 self.do_attempt_write_data(&mut (descriptor.clone()), &mut *peer);
1601 for mut descriptor in descriptors_needing_disconnect.drain(..) {
1602 descriptor.disconnect_socket();
1610 use ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler};
1613 use util::test_utils;
1615 use bitcoin::secp256k1::Secp256k1;
1616 use bitcoin::secp256k1::key::{SecretKey, PublicKey};
1619 use sync::{Arc, Mutex};
1620 use core::sync::atomic::Ordering;
1623 struct FileDescriptor {
1625 outbound_data: Arc<Mutex<Vec<u8>>>,
1627 impl PartialEq for FileDescriptor {
1628 fn eq(&self, other: &Self) -> bool {
1632 impl Eq for FileDescriptor { }
1633 impl core::hash::Hash for FileDescriptor {
1634 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
1635 self.fd.hash(hasher)
1639 impl SocketDescriptor for FileDescriptor {
1640 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
1641 self.outbound_data.lock().unwrap().extend_from_slice(data);
1645 fn disconnect_socket(&mut self) {}
1648 struct PeerManagerCfg {
1649 chan_handler: test_utils::TestChannelMessageHandler,
1650 routing_handler: test_utils::TestRoutingMessageHandler,
1651 logger: test_utils::TestLogger,
1654 fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
1655 let mut cfgs = Vec::new();
1656 for _ in 0..peer_count {
1659 chan_handler: test_utils::TestChannelMessageHandler::new(),
1660 logger: test_utils::TestLogger::new(),
1661 routing_handler: test_utils::TestRoutingMessageHandler::new(),
1669 fn create_network<'a>(peer_count: usize, cfgs: &'a Vec<PeerManagerCfg>) -> Vec<PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, &'a test_utils::TestLogger, IgnoringMessageHandler>> {
1670 let mut peers = Vec::new();
1671 for i in 0..peer_count {
1672 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
1673 let ephemeral_bytes = [i as u8; 32];
1674 let msg_handler = MessageHandler { chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler };
1675 let peer = PeerManager::new(msg_handler, node_secret, &ephemeral_bytes, &cfgs[i].logger, IgnoringMessageHandler {});
1682 fn establish_connection<'a>(peer_a: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, &'a test_utils::TestLogger, IgnoringMessageHandler>, peer_b: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, &'a test_utils::TestLogger, IgnoringMessageHandler>) -> (FileDescriptor, FileDescriptor) {
1683 let secp_ctx = Secp256k1::new();
1684 let a_id = PublicKey::from_secret_key(&secp_ctx, &peer_a.our_node_secret);
1685 let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1686 let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1687 let initial_data = peer_b.new_outbound_connection(a_id, fd_b.clone()).unwrap();
1688 peer_a.new_inbound_connection(fd_a.clone()).unwrap();
1689 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
1690 peer_a.process_events();
1691 assert_eq!(peer_b.read_event(&mut fd_b, &fd_a.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
1692 peer_b.process_events();
1693 assert_eq!(peer_a.read_event(&mut fd_a, &fd_b.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
1694 (fd_a.clone(), fd_b.clone())
1698 fn test_disconnect_peer() {
1699 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
1700 // push a DisconnectPeer event to remove the node flagged by id
1701 let cfgs = create_peermgr_cfgs(2);
1702 let chan_handler = test_utils::TestChannelMessageHandler::new();
1703 let mut peers = create_network(2, &cfgs);
1704 establish_connection(&peers[0], &peers[1]);
1705 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1707 let secp_ctx = Secp256k1::new();
1708 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
1710 chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
1712 action: msgs::ErrorAction::DisconnectPeer { msg: None },
1714 assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1);
1715 peers[0].message_handler.chan_handler = &chan_handler;
1717 peers[0].process_events();
1718 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);
1722 fn test_timer_tick_occurred() {
1723 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
1724 let cfgs = create_peermgr_cfgs(2);
1725 let peers = create_network(2, &cfgs);
1726 establish_connection(&peers[0], &peers[1]);
1727 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1729 // peers[0] awaiting_pong is set to true, but the Peer is still connected
1730 peers[0].timer_tick_occurred();
1731 peers[0].process_events();
1732 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1734 // Since timer_tick_occurred() is called again when awaiting_pong is true, all Peers are disconnected
1735 peers[0].timer_tick_occurred();
1736 peers[0].process_events();
1737 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);
1741 fn test_do_attempt_write_data() {
1742 // Create 2 peers with custom TestRoutingMessageHandlers and connect them.
1743 let cfgs = create_peermgr_cfgs(2);
1744 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
1745 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
1746 let peers = create_network(2, &cfgs);
1748 // By calling establish_connect, we trigger do_attempt_write_data between
1749 // the peers. Previously this function would mistakenly enter an infinite loop
1750 // when there were more channel messages available than could fit into a peer's
1751 // buffer. This issue would now be detected by this test (because we use custom
1752 // RoutingMessageHandlers that intentionally return more channel messages
1753 // than can fit into a peer's buffer).
1754 let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
1756 // Make each peer to read the messages that the other peer just wrote to them. Note that
1757 // due to the max-messagse-before-ping limits this may take a few iterations to complete.
1758 for _ in 0..150/super::BUFFER_DRAIN_MSGS_PER_TICK + 1 {
1759 peers[0].process_events();
1760 let b_read_data = fd_a.outbound_data.lock().unwrap().split_off(0);
1761 assert!(!b_read_data.is_empty());
1763 peers[1].read_event(&mut fd_b, &b_read_data).unwrap();
1764 peers[1].process_events();
1766 let a_read_data = fd_b.outbound_data.lock().unwrap().split_off(0);
1767 assert!(!a_read_data.is_empty());
1768 peers[0].read_event(&mut fd_a, &a_read_data).unwrap();
1770 peers[1].process_events();
1771 assert_eq!(fd_b.outbound_data.lock().unwrap().len(), 0, "Until B receives data, it shouldn't send more messages");
1774 // Check that each peer has received the expected number of channel updates and channel
1776 assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 100);
1777 assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 50);
1778 assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 100);
1779 assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 50);
1783 fn test_handshake_timeout() {
1784 // Tests that we time out a peer still waiting on handshake completion after a full timer
1786 let cfgs = create_peermgr_cfgs(2);
1787 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
1788 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
1789 let peers = create_network(2, &cfgs);
1791 let secp_ctx = Secp256k1::new();
1792 let a_id = PublicKey::from_secret_key(&secp_ctx, &peers[0].our_node_secret);
1793 let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1794 let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1795 let initial_data = peers[1].new_outbound_connection(a_id, fd_b.clone()).unwrap();
1796 peers[0].new_inbound_connection(fd_a.clone()).unwrap();
1798 // If we get a single timer tick before completion, that's fine
1799 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1800 peers[0].timer_tick_occurred();
1801 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1803 assert_eq!(peers[0].read_event(&mut fd_a, &initial_data).unwrap(), false);
1804 peers[0].process_events();
1805 assert_eq!(peers[1].read_event(&mut fd_b, &fd_a.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
1806 peers[1].process_events();
1808 // ...but if we get a second timer tick, we should disconnect the peer
1809 peers[0].timer_tick_occurred();
1810 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);
1812 assert!(peers[0].read_event(&mut fd_a, &fd_b.outbound_data.lock().unwrap().split_off(0)).is_err());