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, NetAddress, 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::atomic_counter::AtomicCounter;
29 use util::events::{MessageSendEvent, MessageSendEventsProvider};
30 use util::logger::Logger;
31 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
35 use alloc::collections::LinkedList;
36 use sync::{Arc, Mutex, RwLock};
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 peer_connected(&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 ten seconds, this translates to about 40 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 = 4;
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>,
327 their_net_address: Option<NetAddress>,
329 pending_outbound_buffer: LinkedList<Vec<u8>>,
330 pending_outbound_buffer_first_msg_offset: usize,
331 awaiting_write_event: bool,
333 pending_read_buffer: Vec<u8>,
334 pending_read_buffer_pos: usize,
335 pending_read_is_header: bool,
337 sync_status: InitSyncTracker,
339 msgs_sent_since_pong: usize,
340 awaiting_pong_timer_tick_intervals: i8,
341 received_message_since_timer_tick: bool,
342 sent_gossip_timestamp_filter: bool,
346 /// Returns true if the channel announcements/updates for the given channel should be
347 /// forwarded to this peer.
348 /// If we are sending our routing table to this peer and we have not yet sent channel
349 /// announcements/updates for the given channel_id then we will send it when we get to that
350 /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
351 /// sent the old versions, we should send the update, and so return true here.
352 fn should_forward_channel_announcement(&self, channel_id: u64) -> bool {
353 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
354 !self.sent_gossip_timestamp_filter {
357 match self.sync_status {
358 InitSyncTracker::NoSyncRequested => true,
359 InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
360 InitSyncTracker::NodesSyncing(_) => true,
364 /// Similar to the above, but for node announcements indexed by node_id.
365 fn should_forward_node_announcement(&self, node_id: PublicKey) -> bool {
366 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
367 !self.sent_gossip_timestamp_filter {
370 match self.sync_status {
371 InitSyncTracker::NoSyncRequested => true,
372 InitSyncTracker::ChannelsSyncing(_) => false,
373 InitSyncTracker::NodesSyncing(pk) => pk < node_id,
378 struct PeerHolder<Descriptor: SocketDescriptor> {
379 peers: HashMap<Descriptor, Mutex<Peer>>,
382 /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
383 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
384 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
385 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
386 /// issues such as overly long function definitions.
388 /// (C-not exported) as Arcs don't make sense in bindings
389 pub type SimpleArcPeerManager<SD, M, T, F, C, L> = PeerManager<SD, Arc<SimpleArcChannelManager<M, T, F, L>>, Arc<NetGraphMsgHandler<Arc<NetworkGraph>, Arc<C>, Arc<L>>>, Arc<L>, Arc<IgnoringMessageHandler>>;
391 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
392 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
393 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
394 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
395 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
396 /// helps with issues such as long function definitions.
398 /// (C-not exported) as Arcs don't make sense in bindings
399 pub type SimpleRefPeerManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, SD, M, T, F, C, L> = PeerManager<SD, SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L>, &'e NetGraphMsgHandler<&'g NetworkGraph, &'h C, &'f L>, &'f L, IgnoringMessageHandler>;
401 /// A PeerManager manages a set of peers, described by their [`SocketDescriptor`] and marshalls
402 /// socket events into messages which it passes on to its [`MessageHandler`].
404 /// Locks are taken internally, so you must never assume that reentrancy from a
405 /// [`SocketDescriptor`] call back into [`PeerManager`] methods will not deadlock.
407 /// Calls to [`read_event`] will decode relevant messages and pass them to the
408 /// [`ChannelMessageHandler`], likely doing message processing in-line. Thus, the primary form of
409 /// parallelism in Rust-Lightning is in calls to [`read_event`]. Note, however, that calls to any
410 /// [`PeerManager`] functions related to the same connection must occur only in serial, making new
411 /// calls only after previous ones have returned.
413 /// Rather than using a plain PeerManager, it is preferable to use either a SimpleArcPeerManager
414 /// a SimpleRefPeerManager, for conciseness. See their documentation for more details, but
415 /// essentially you should default to using a SimpleRefPeerManager, and use a
416 /// SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when
417 /// you're using lightning-net-tokio.
419 /// [`read_event`]: PeerManager::read_event
420 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> where
421 CM::Target: ChannelMessageHandler,
422 RM::Target: RoutingMessageHandler,
424 CMH::Target: CustomMessageHandler {
425 message_handler: MessageHandler<CM, RM>,
426 peers: RwLock<PeerHolder<Descriptor>>,
427 /// Only add to this set when noise completes.
428 /// Locked *after* peers. When an item is removed, it must be removed with the `peers` write
429 /// lock held. Entries may be added with only the `peers` read lock held (though the
430 /// `Descriptor` value must already exist in `peers`).
431 node_id_to_descriptor: Mutex<HashMap<PublicKey, Descriptor>>,
432 our_node_secret: SecretKey,
433 ephemeral_key_midstate: Sha256Engine,
434 custom_message_handler: CMH,
436 peer_counter: AtomicCounter,
441 enum MessageHandlingError {
442 PeerHandleError(PeerHandleError),
443 LightningError(LightningError),
446 impl From<PeerHandleError> for MessageHandlingError {
447 fn from(error: PeerHandleError) -> Self {
448 MessageHandlingError::PeerHandleError(error)
452 impl From<LightningError> for MessageHandlingError {
453 fn from(error: LightningError) -> Self {
454 MessageHandlingError::LightningError(error)
458 macro_rules! encode_msg {
460 let mut buffer = VecWriter(Vec::new());
461 wire::write($msg, &mut buffer).unwrap();
466 impl<Descriptor: SocketDescriptor, CM: Deref, L: Deref> PeerManager<Descriptor, CM, IgnoringMessageHandler, L, IgnoringMessageHandler> where
467 CM::Target: ChannelMessageHandler,
469 /// Constructs a new PeerManager with the given ChannelMessageHandler. No routing message
470 /// handler is used and network graph messages are ignored.
472 /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
473 /// cryptographically secure random bytes.
475 /// (C-not exported) as we can't export a PeerManager with a dummy route handler
476 pub fn new_channel_only(channel_message_handler: CM, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
477 Self::new(MessageHandler {
478 chan_handler: channel_message_handler,
479 route_handler: IgnoringMessageHandler{},
480 }, our_node_secret, ephemeral_random_data, logger, IgnoringMessageHandler{})
484 impl<Descriptor: SocketDescriptor, RM: Deref, L: Deref> PeerManager<Descriptor, ErroringMessageHandler, RM, L, IgnoringMessageHandler> where
485 RM::Target: RoutingMessageHandler,
487 /// Constructs a new PeerManager with the given RoutingMessageHandler. No channel message
488 /// handler is used and messages related to channels will be ignored (or generate error
489 /// messages). Note that some other lightning implementations time-out connections after some
490 /// time if no channel is built with the peer.
492 /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
493 /// cryptographically secure random bytes.
495 /// (C-not exported) as we can't export a PeerManager with a dummy channel handler
496 pub fn new_routing_only(routing_message_handler: RM, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
497 Self::new(MessageHandler {
498 chan_handler: ErroringMessageHandler::new(),
499 route_handler: routing_message_handler,
500 }, our_node_secret, ephemeral_random_data, logger, IgnoringMessageHandler{})
504 /// A simple wrapper that optionally prints " from <pubkey>" for an optional pubkey.
505 /// This works around `format!()` taking a reference to each argument, preventing
506 /// `if let Some(node_id) = peer.their_node_id { format!(.., node_id) } else { .. }` from compiling
507 /// due to lifetime errors.
508 struct OptionalFromDebugger<'a>(&'a Option<PublicKey>);
509 impl core::fmt::Display for OptionalFromDebugger<'_> {
510 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
511 if let Some(node_id) = self.0 { write!(f, " from {}", log_pubkey!(node_id)) } else { Ok(()) }
515 /// A function used to filter out local or private addresses
516 /// https://www.iana.org./assignments/ipv4-address-space/ipv4-address-space.xhtml
517 /// https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml
518 fn filter_addresses(ip_address: Option<NetAddress>) -> Option<NetAddress> {
520 // For IPv4 range 10.0.0.0 - 10.255.255.255 (10/8)
521 Some(NetAddress::IPv4{addr: [10, _, _, _], port: _}) => None,
522 // For IPv4 range 0.0.0.0 - 0.255.255.255 (0/8)
523 Some(NetAddress::IPv4{addr: [0, _, _, _], port: _}) => None,
524 // For IPv4 range 100.64.0.0 - 100.127.255.255 (100.64/10)
525 Some(NetAddress::IPv4{addr: [100, 64..=127, _, _], port: _}) => None,
526 // For IPv4 range 127.0.0.0 - 127.255.255.255 (127/8)
527 Some(NetAddress::IPv4{addr: [127, _, _, _], port: _}) => None,
528 // For IPv4 range 169.254.0.0 - 169.254.255.255 (169.254/16)
529 Some(NetAddress::IPv4{addr: [169, 254, _, _], port: _}) => None,
530 // For IPv4 range 172.16.0.0 - 172.31.255.255 (172.16/12)
531 Some(NetAddress::IPv4{addr: [172, 16..=31, _, _], port: _}) => None,
532 // For IPv4 range 192.168.0.0 - 192.168.255.255 (192.168/16)
533 Some(NetAddress::IPv4{addr: [192, 168, _, _], port: _}) => None,
534 // For IPv4 range 192.88.99.0 - 192.88.99.255 (192.88.99/24)
535 Some(NetAddress::IPv4{addr: [192, 88, 99, _], port: _}) => None,
536 // For IPv6 range 2000:0000:0000:0000:0000:0000:0000:0000 - 3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff (2000::/3)
537 Some(NetAddress::IPv6{addr: [0x20..=0x3F, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _], port: _}) => ip_address,
538 // For remaining addresses
539 Some(NetAddress::IPv6{addr: _, port: _}) => None,
540 Some(..) => ip_address,
545 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref, CMH: Deref> PeerManager<Descriptor, CM, RM, L, CMH> where
546 CM::Target: ChannelMessageHandler,
547 RM::Target: RoutingMessageHandler,
549 CMH::Target: CustomMessageHandler {
550 /// Constructs a new PeerManager with the given message handlers and node_id secret key
551 /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
552 /// cryptographically secure random bytes.
553 pub fn new(message_handler: MessageHandler<CM, RM>, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L, custom_message_handler: CMH) -> Self {
554 let mut ephemeral_key_midstate = Sha256::engine();
555 ephemeral_key_midstate.input(ephemeral_random_data);
559 peers: RwLock::new(PeerHolder {
560 peers: HashMap::new(),
562 node_id_to_descriptor: Mutex::new(HashMap::new()),
564 ephemeral_key_midstate,
565 peer_counter: AtomicCounter::new(),
567 custom_message_handler,
571 /// Get the list of node ids for peers which have completed the initial handshake.
573 /// For outbound connections, this will be the same as the their_node_id parameter passed in to
574 /// new_outbound_connection, however entries will only appear once the initial handshake has
575 /// completed and we are sure the remote peer has the private key for the given node_id.
576 pub fn get_peer_node_ids(&self) -> Vec<PublicKey> {
577 let peers = self.peers.read().unwrap();
578 peers.peers.values().filter_map(|peer_mutex| {
579 let p = peer_mutex.lock().unwrap();
580 if !p.channel_encryptor.is_ready_for_encryption() || p.their_features.is_none() {
587 fn get_ephemeral_key(&self) -> SecretKey {
588 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
589 let counter = self.peer_counter.get_increment();
590 ephemeral_hash.input(&counter.to_le_bytes());
591 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!")
594 /// Indicates a new outbound connection has been established to a node with the given node_id
595 /// and an optional remote network address.
597 /// The remote network address adds the option to report a remote IP address back to a connecting
598 /// peer using the init message.
599 /// The user should pass the remote network address of the host they are connected to.
601 /// Note that if an Err is returned here you MUST NOT call socket_disconnected for the new
602 /// descriptor but must disconnect the connection immediately.
604 /// Returns a small number of bytes to send to the remote node (currently always 50).
606 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
607 /// [`socket_disconnected()`].
609 /// [`socket_disconnected()`]: PeerManager::socket_disconnected
610 pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor, remote_network_address: Option<NetAddress>) -> Result<Vec<u8>, PeerHandleError> {
611 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
612 let res = peer_encryptor.get_act_one().to_vec();
613 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
615 let mut peers = self.peers.write().unwrap();
616 if peers.peers.insert(descriptor, Mutex::new(Peer {
617 channel_encryptor: peer_encryptor,
619 their_features: None,
620 their_net_address: remote_network_address,
622 pending_outbound_buffer: LinkedList::new(),
623 pending_outbound_buffer_first_msg_offset: 0,
624 awaiting_write_event: false,
627 pending_read_buffer_pos: 0,
628 pending_read_is_header: false,
630 sync_status: InitSyncTracker::NoSyncRequested,
632 msgs_sent_since_pong: 0,
633 awaiting_pong_timer_tick_intervals: 0,
634 received_message_since_timer_tick: false,
635 sent_gossip_timestamp_filter: false,
637 panic!("PeerManager driver duplicated descriptors!");
642 /// Indicates a new inbound connection has been established to a node with an optional remote
645 /// The remote network address adds the option to report a remote IP address back to a connecting
646 /// peer using the init message.
647 /// The user should pass the remote network address of the host they are connected to.
649 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
650 /// (outbound connector always speaks first). Note that if an Err is returned here you MUST NOT
651 /// call socket_disconnected for the new descriptor but must disconnect the connection
654 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
655 /// [`socket_disconnected()`].
657 /// [`socket_disconnected()`]: PeerManager::socket_disconnected
658 pub fn new_inbound_connection(&self, descriptor: Descriptor, remote_network_address: Option<NetAddress>) -> Result<(), PeerHandleError> {
659 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret);
660 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
662 let mut peers = self.peers.write().unwrap();
663 if peers.peers.insert(descriptor, Mutex::new(Peer {
664 channel_encryptor: peer_encryptor,
666 their_features: None,
667 their_net_address: remote_network_address,
669 pending_outbound_buffer: LinkedList::new(),
670 pending_outbound_buffer_first_msg_offset: 0,
671 awaiting_write_event: false,
674 pending_read_buffer_pos: 0,
675 pending_read_is_header: false,
677 sync_status: InitSyncTracker::NoSyncRequested,
679 msgs_sent_since_pong: 0,
680 awaiting_pong_timer_tick_intervals: 0,
681 received_message_since_timer_tick: false,
682 sent_gossip_timestamp_filter: false,
684 panic!("PeerManager driver duplicated descriptors!");
689 fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer) {
690 while !peer.awaiting_write_event {
691 if peer.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE && peer.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK {
692 match peer.sync_status {
693 InitSyncTracker::NoSyncRequested => {},
694 InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
695 let steps = ((OUTBOUND_BUFFER_LIMIT_READ_PAUSE - peer.pending_outbound_buffer.len() + 2) / 3) as u8;
696 let all_messages = self.message_handler.route_handler.get_next_channel_announcements(c, steps);
697 for &(ref announce, ref update_a_option, ref update_b_option) in all_messages.iter() {
698 self.enqueue_message(peer, announce);
699 if let &Some(ref update_a) = update_a_option {
700 self.enqueue_message(peer, update_a);
702 if let &Some(ref update_b) = update_b_option {
703 self.enqueue_message(peer, update_b);
705 peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
707 if all_messages.is_empty() || all_messages.len() != steps as usize {
708 peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
711 InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
712 let steps = (OUTBOUND_BUFFER_LIMIT_READ_PAUSE - peer.pending_outbound_buffer.len()) as u8;
713 let all_messages = self.message_handler.route_handler.get_next_node_announcements(None, steps);
714 for msg in all_messages.iter() {
715 self.enqueue_message(peer, msg);
716 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
718 if all_messages.is_empty() || all_messages.len() != steps as usize {
719 peer.sync_status = InitSyncTracker::NoSyncRequested;
722 InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
723 InitSyncTracker::NodesSyncing(key) => {
724 let steps = (OUTBOUND_BUFFER_LIMIT_READ_PAUSE - peer.pending_outbound_buffer.len()) as u8;
725 let all_messages = self.message_handler.route_handler.get_next_node_announcements(Some(&key), steps);
726 for msg in all_messages.iter() {
727 self.enqueue_message(peer, msg);
728 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
730 if all_messages.is_empty() || all_messages.len() != steps as usize {
731 peer.sync_status = InitSyncTracker::NoSyncRequested;
736 if peer.msgs_sent_since_pong >= BUFFER_DRAIN_MSGS_PER_TICK {
737 self.maybe_send_extra_ping(peer);
741 let next_buff = match peer.pending_outbound_buffer.front() {
746 let should_be_reading = peer.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE;
747 let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
748 let data_sent = descriptor.send_data(pending, should_be_reading);
749 peer.pending_outbound_buffer_first_msg_offset += data_sent;
750 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() { true } else { false }
752 peer.pending_outbound_buffer_first_msg_offset = 0;
753 peer.pending_outbound_buffer.pop_front();
755 peer.awaiting_write_event = true;
760 /// Indicates that there is room to write data to the given socket descriptor.
762 /// May return an Err to indicate that the connection should be closed.
764 /// May call [`send_data`] on the descriptor passed in (or an equal descriptor) before
765 /// returning. Thus, be very careful with reentrancy issues! The invariants around calling
766 /// [`write_buffer_space_avail`] in case a write did not fully complete must still hold - be
767 /// ready to call `[write_buffer_space_avail`] again if a write call generated here isn't
770 /// [`send_data`]: SocketDescriptor::send_data
771 /// [`write_buffer_space_avail`]: PeerManager::write_buffer_space_avail
772 pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
773 let peers = self.peers.read().unwrap();
774 match peers.peers.get(descriptor) {
776 // This is most likely a simple race condition where the user found that the socket
777 // was writeable, then we told the user to `disconnect_socket()`, then they called
778 // this method. Return an error to make sure we get disconnected.
779 return Err(PeerHandleError { no_connection_possible: false });
781 Some(peer_mutex) => {
782 let mut peer = peer_mutex.lock().unwrap();
783 peer.awaiting_write_event = false;
784 self.do_attempt_write_data(descriptor, &mut peer);
790 /// Indicates that data was read from the given socket descriptor.
792 /// May return an Err to indicate that the connection should be closed.
794 /// Will *not* call back into [`send_data`] on any descriptors to avoid reentrancy complexity.
795 /// Thus, however, you should call [`process_events`] after any `read_event` to generate
796 /// [`send_data`] calls to handle responses.
798 /// If `Ok(true)` is returned, further read_events should not be triggered until a
799 /// [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the
802 /// [`send_data`]: SocketDescriptor::send_data
803 /// [`process_events`]: PeerManager::process_events
804 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
805 match self.do_read_event(peer_descriptor, data) {
808 log_trace!(self.logger, "Peer sent invalid data or we decided to disconnect due to a protocol error");
809 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
815 /// Append a message to a peer's pending outbound/write buffer
816 fn enqueue_encoded_message(&self, peer: &mut Peer, encoded_message: &Vec<u8>) {
817 peer.msgs_sent_since_pong += 1;
818 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_message[..]));
821 /// Append a message to a peer's pending outbound/write buffer
822 fn enqueue_message<M: wire::Type>(&self, peer: &mut Peer, message: &M) {
823 let mut buffer = VecWriter(Vec::with_capacity(2048));
824 wire::write(message, &mut buffer).unwrap(); // crash if the write failed
826 if is_gossip_msg(message.type_id()) {
827 log_gossip!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap()));
829 log_trace!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap()))
831 self.enqueue_encoded_message(peer, &buffer.0);
834 fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
836 let peers = self.peers.read().unwrap();
837 let mut msgs_to_forward = Vec::new();
838 let mut peer_node_id = None;
839 let pause_read = match peers.peers.get(peer_descriptor) {
841 // This is most likely a simple race condition where the user read some bytes
842 // from the socket, then we told the user to `disconnect_socket()`, then they
843 // called this method. Return an error to make sure we get disconnected.
844 return Err(PeerHandleError { no_connection_possible: false });
846 Some(peer_mutex) => {
847 let mut peer_lock = peer_mutex.lock().unwrap();
848 let peer = &mut *peer_lock;
850 assert!(peer.pending_read_buffer.len() > 0);
851 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
853 let mut read_pos = 0;
854 while read_pos < data.len() {
856 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
857 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]);
858 read_pos += data_to_copy;
859 peer.pending_read_buffer_pos += data_to_copy;
862 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
863 peer.pending_read_buffer_pos = 0;
865 macro_rules! try_potential_handleerror {
871 msgs::ErrorAction::DisconnectPeer { msg: _ } => {
872 //TODO: Try to push msg
873 log_debug!(self.logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer.their_node_id), e.err);
874 return Err(PeerHandleError{ no_connection_possible: false });
876 msgs::ErrorAction::IgnoreAndLog(level) => {
877 log_given_level!(self.logger, level, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer.their_node_id), e.err);
880 msgs::ErrorAction::IgnoreDuplicateGossip => continue, // Don't even bother logging these
881 msgs::ErrorAction::IgnoreError => {
882 log_debug!(self.logger, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer.their_node_id), e.err);
885 msgs::ErrorAction::SendErrorMessage { msg } => {
886 log_debug!(self.logger, "Error handling message{}; sending error message with: {}", OptionalFromDebugger(&peer.their_node_id), e.err);
887 self.enqueue_message(peer, &msg);
890 msgs::ErrorAction::SendWarningMessage { msg, log_level } => {
891 log_given_level!(self.logger, log_level, "Error handling message{}; sending warning message with: {}", OptionalFromDebugger(&peer.their_node_id), e.err);
892 self.enqueue_message(peer, &msg);
901 macro_rules! insert_node_id {
903 match self.node_id_to_descriptor.lock().unwrap().entry(peer.their_node_id.unwrap()) {
904 hash_map::Entry::Occupied(_) => {
905 log_trace!(self.logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap()));
906 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
907 return Err(PeerHandleError{ no_connection_possible: false })
909 hash_map::Entry::Vacant(entry) => {
910 log_debug!(self.logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap()));
911 entry.insert(peer_descriptor.clone())
917 let next_step = peer.channel_encryptor.get_noise_step();
919 NextNoiseStep::ActOne => {
920 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();
921 peer.pending_outbound_buffer.push_back(act_two);
922 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
924 NextNoiseStep::ActTwo => {
925 let (act_three, their_node_id) = try_potential_handleerror!(peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], &self.our_node_secret));
926 peer.pending_outbound_buffer.push_back(act_three.to_vec());
927 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
928 peer.pending_read_is_header = true;
930 peer.their_node_id = Some(their_node_id);
932 let features = InitFeatures::known();
933 let resp = msgs::Init { features, remote_network_address: filter_addresses(peer.their_net_address.clone())};
934 self.enqueue_message(peer, &resp);
935 peer.awaiting_pong_timer_tick_intervals = 0;
937 NextNoiseStep::ActThree => {
938 let their_node_id = try_potential_handleerror!(peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
939 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
940 peer.pending_read_is_header = true;
941 peer.their_node_id = Some(their_node_id);
943 let features = InitFeatures::known();
944 let resp = msgs::Init { features, remote_network_address: filter_addresses(peer.their_net_address.clone())};
945 self.enqueue_message(peer, &resp);
946 peer.awaiting_pong_timer_tick_intervals = 0;
948 NextNoiseStep::NoiseComplete => {
949 if peer.pending_read_is_header {
950 let msg_len = try_potential_handleerror!(peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
951 peer.pending_read_buffer = Vec::with_capacity(msg_len as usize + 16);
952 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
953 if msg_len < 2 { // Need at least the message type tag
954 return Err(PeerHandleError{ no_connection_possible: false });
956 peer.pending_read_is_header = false;
958 let msg_data = try_potential_handleerror!(peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
959 assert!(msg_data.len() >= 2);
962 peer.pending_read_buffer = [0; 18].to_vec();
963 peer.pending_read_is_header = true;
965 let mut reader = io::Cursor::new(&msg_data[..]);
966 let message_result = wire::read(&mut reader, &*self.custom_message_handler);
967 let message = match message_result {
971 // Note that to avoid recursion we never call
972 // `do_attempt_write_data` from here, causing
973 // the messages enqueued here to not actually
974 // be sent before the peer is disconnected.
975 (msgs::DecodeError::UnknownRequiredFeature, Some(ty)) if is_gossip_msg(ty) => {
976 log_gossip!(self.logger, "Got a channel/node announcement with an unknown required feature flag, you may want to update!");
979 (msgs::DecodeError::UnsupportedCompression, _) => {
980 log_gossip!(self.logger, "We don't support zlib-compressed message fields, sending a warning and ignoring message");
981 self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: "Unsupported message compression: zlib".to_owned() });
984 (_, Some(ty)) if is_gossip_msg(ty) => {
985 log_gossip!(self.logger, "Got an invalid value while deserializing a gossip message");
986 self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: "Unreadable/bogus gossip message".to_owned() });
989 (msgs::DecodeError::UnknownRequiredFeature, ty) => {
990 log_gossip!(self.logger, "Received a message with an unknown required feature flag or TLV, you may want to update!");
991 self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: format!("Received an unknown required feature/TLV in message type {:?}", ty) });
992 return Err(PeerHandleError { no_connection_possible: false });
994 (msgs::DecodeError::UnknownVersion, _) => return Err(PeerHandleError { no_connection_possible: false }),
995 (msgs::DecodeError::InvalidValue, _) => {
996 log_debug!(self.logger, "Got an invalid value while deserializing message");
997 return Err(PeerHandleError { no_connection_possible: false });
999 (msgs::DecodeError::ShortRead, _) => {
1000 log_debug!(self.logger, "Deserialization failed due to shortness of message");
1001 return Err(PeerHandleError { no_connection_possible: false });
1003 (msgs::DecodeError::BadLengthDescriptor, _) => return Err(PeerHandleError { no_connection_possible: false }),
1004 (msgs::DecodeError::Io(_), _) => return Err(PeerHandleError { no_connection_possible: false }),
1009 match self.handle_message(peer, message) {
1010 Err(handling_error) => match handling_error {
1011 MessageHandlingError::PeerHandleError(e) => { return Err(e) },
1012 MessageHandlingError::LightningError(e) => {
1013 try_potential_handleerror!(Err(e));
1017 peer_node_id = Some(peer.their_node_id.expect("After noise is complete, their_node_id is always set"));
1018 msgs_to_forward.push(msg);
1028 peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_READ_PAUSE // pause_read
1032 for msg in msgs_to_forward.drain(..) {
1033 self.forward_broadcast_msg(&*peers, &msg, peer_node_id.as_ref());
1042 /// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer
1043 /// Returns the message back if it needs to be broadcasted to all other peers.
1047 message: wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>
1048 ) -> Result<Option<wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError> {
1049 if is_gossip_msg(message.type_id()) {
1050 log_gossip!(self.logger, "Received message {:?} from {}", message, log_pubkey!(peer.their_node_id.unwrap()));
1052 log_trace!(self.logger, "Received message {:?} from {}", message, log_pubkey!(peer.their_node_id.unwrap()));
1055 peer.received_message_since_timer_tick = true;
1057 // Need an Init as first message
1058 if let wire::Message::Init(_) = message {
1059 } else if peer.their_features.is_none() {
1060 log_debug!(self.logger, "Peer {} sent non-Init first message", log_pubkey!(peer.their_node_id.unwrap()));
1061 return Err(PeerHandleError{ no_connection_possible: false }.into());
1064 let mut should_forward = None;
1067 // Setup and Control messages:
1068 wire::Message::Init(msg) => {
1069 if msg.features.requires_unknown_bits() {
1070 log_debug!(self.logger, "Peer features required unknown version bits");
1071 return Err(PeerHandleError{ no_connection_possible: true }.into());
1073 if peer.their_features.is_some() {
1074 return Err(PeerHandleError{ no_connection_possible: false }.into());
1077 log_info!(self.logger, "Received peer Init message from {}: {}", log_pubkey!(peer.their_node_id.unwrap()), msg.features);
1079 // For peers not supporting gossip queries start sync now, otherwise wait until we receive a filter.
1080 if msg.features.initial_routing_sync() && !msg.features.supports_gossip_queries() {
1081 peer.sync_status = InitSyncTracker::ChannelsSyncing(0);
1083 if !msg.features.supports_static_remote_key() {
1084 log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting with no_connection_possible", log_pubkey!(peer.their_node_id.unwrap()));
1085 return Err(PeerHandleError{ no_connection_possible: true }.into());
1088 self.message_handler.route_handler.peer_connected(&peer.their_node_id.unwrap(), &msg);
1090 self.message_handler.chan_handler.peer_connected(&peer.their_node_id.unwrap(), &msg);
1091 peer.their_features = Some(msg.features);
1093 wire::Message::Error(msg) => {
1094 let mut data_is_printable = true;
1095 for b in msg.data.bytes() {
1096 if b < 32 || b > 126 {
1097 data_is_printable = false;
1102 if data_is_printable {
1103 log_debug!(self.logger, "Got Err message from {}: {}", log_pubkey!(peer.their_node_id.unwrap()), msg.data);
1105 log_debug!(self.logger, "Got Err message from {} with non-ASCII error message", log_pubkey!(peer.their_node_id.unwrap()));
1107 self.message_handler.chan_handler.handle_error(&peer.their_node_id.unwrap(), &msg);
1108 if msg.channel_id == [0; 32] {
1109 return Err(PeerHandleError{ no_connection_possible: true }.into());
1112 wire::Message::Warning(msg) => {
1113 let mut data_is_printable = true;
1114 for b in msg.data.bytes() {
1115 if b < 32 || b > 126 {
1116 data_is_printable = false;
1121 if data_is_printable {
1122 log_debug!(self.logger, "Got warning message from {}: {}", log_pubkey!(peer.their_node_id.unwrap()), msg.data);
1124 log_debug!(self.logger, "Got warning message from {} with non-ASCII error message", log_pubkey!(peer.their_node_id.unwrap()));
1128 wire::Message::Ping(msg) => {
1129 if msg.ponglen < 65532 {
1130 let resp = msgs::Pong { byteslen: msg.ponglen };
1131 self.enqueue_message(peer, &resp);
1134 wire::Message::Pong(_msg) => {
1135 peer.awaiting_pong_timer_tick_intervals = 0;
1136 peer.msgs_sent_since_pong = 0;
1139 // Channel messages:
1140 wire::Message::OpenChannel(msg) => {
1141 self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg);
1143 wire::Message::AcceptChannel(msg) => {
1144 self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg);
1147 wire::Message::FundingCreated(msg) => {
1148 self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg);
1150 wire::Message::FundingSigned(msg) => {
1151 self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg);
1153 wire::Message::FundingLocked(msg) => {
1154 self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg);
1157 wire::Message::Shutdown(msg) => {
1158 self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), peer.their_features.as_ref().unwrap(), &msg);
1160 wire::Message::ClosingSigned(msg) => {
1161 self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg);
1164 // Commitment messages:
1165 wire::Message::UpdateAddHTLC(msg) => {
1166 self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg);
1168 wire::Message::UpdateFulfillHTLC(msg) => {
1169 self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg);
1171 wire::Message::UpdateFailHTLC(msg) => {
1172 self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg);
1174 wire::Message::UpdateFailMalformedHTLC(msg) => {
1175 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg);
1178 wire::Message::CommitmentSigned(msg) => {
1179 self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg);
1181 wire::Message::RevokeAndACK(msg) => {
1182 self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg);
1184 wire::Message::UpdateFee(msg) => {
1185 self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg);
1187 wire::Message::ChannelReestablish(msg) => {
1188 self.message_handler.chan_handler.handle_channel_reestablish(&peer.their_node_id.unwrap(), &msg);
1191 // Routing messages:
1192 wire::Message::AnnouncementSignatures(msg) => {
1193 self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg);
1195 wire::Message::ChannelAnnouncement(msg) => {
1196 if self.message_handler.route_handler.handle_channel_announcement(&msg)
1197 .map_err(|e| -> MessageHandlingError { e.into() })? {
1198 should_forward = Some(wire::Message::ChannelAnnouncement(msg));
1201 wire::Message::NodeAnnouncement(msg) => {
1202 if self.message_handler.route_handler.handle_node_announcement(&msg)
1203 .map_err(|e| -> MessageHandlingError { e.into() })? {
1204 should_forward = Some(wire::Message::NodeAnnouncement(msg));
1207 wire::Message::ChannelUpdate(msg) => {
1208 self.message_handler.chan_handler.handle_channel_update(&peer.their_node_id.unwrap(), &msg);
1209 if self.message_handler.route_handler.handle_channel_update(&msg)
1210 .map_err(|e| -> MessageHandlingError { e.into() })? {
1211 should_forward = Some(wire::Message::ChannelUpdate(msg));
1214 wire::Message::QueryShortChannelIds(msg) => {
1215 self.message_handler.route_handler.handle_query_short_channel_ids(&peer.their_node_id.unwrap(), msg)?;
1217 wire::Message::ReplyShortChannelIdsEnd(msg) => {
1218 self.message_handler.route_handler.handle_reply_short_channel_ids_end(&peer.their_node_id.unwrap(), msg)?;
1220 wire::Message::QueryChannelRange(msg) => {
1221 self.message_handler.route_handler.handle_query_channel_range(&peer.their_node_id.unwrap(), msg)?;
1223 wire::Message::ReplyChannelRange(msg) => {
1224 self.message_handler.route_handler.handle_reply_channel_range(&peer.their_node_id.unwrap(), msg)?;
1226 wire::Message::GossipTimestampFilter(_msg) => {
1227 // When supporting gossip messages, start inital gossip sync only after we receive
1228 // a GossipTimestampFilter
1229 if peer.their_features.as_ref().unwrap().supports_gossip_queries() &&
1230 !peer.sent_gossip_timestamp_filter {
1231 peer.sent_gossip_timestamp_filter = true;
1232 peer.sync_status = InitSyncTracker::ChannelsSyncing(0);
1236 // Unknown messages:
1237 wire::Message::Unknown(type_id) if message.is_even() => {
1238 log_debug!(self.logger, "Received unknown even message of type {}, disconnecting peer!", type_id);
1239 // Fail the channel if message is an even, unknown type as per BOLT #1.
1240 return Err(PeerHandleError{ no_connection_possible: true }.into());
1242 wire::Message::Unknown(type_id) => {
1243 log_trace!(self.logger, "Received unknown odd message of type {}, ignoring", type_id);
1245 wire::Message::Custom(custom) => {
1246 self.custom_message_handler.handle_custom_message(custom, &peer.their_node_id.unwrap())?;
1252 fn forward_broadcast_msg(&self, peers: &PeerHolder<Descriptor>, msg: &wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>, except_node: Option<&PublicKey>) {
1254 wire::Message::ChannelAnnouncement(ref msg) => {
1255 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced channel's counterparties: {:?}", except_node, msg);
1256 let encoded_msg = encode_msg!(msg);
1258 for (_, peer_mutex) in peers.peers.iter() {
1259 let mut peer = peer_mutex.lock().unwrap();
1260 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1261 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1264 if peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP
1265 || peer.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO
1267 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1270 if peer.their_node_id.as_ref() == Some(&msg.contents.node_id_1) ||
1271 peer.their_node_id.as_ref() == Some(&msg.contents.node_id_2) {
1274 if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1277 self.enqueue_encoded_message(&mut *peer, &encoded_msg);
1280 wire::Message::NodeAnnouncement(ref msg) => {
1281 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced node: {:?}", except_node, msg);
1282 let encoded_msg = encode_msg!(msg);
1284 for (_, peer_mutex) in peers.peers.iter() {
1285 let mut peer = peer_mutex.lock().unwrap();
1286 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1287 !peer.should_forward_node_announcement(msg.contents.node_id) {
1290 if peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP
1291 || peer.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO
1293 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1296 if peer.their_node_id.as_ref() == Some(&msg.contents.node_id) {
1299 if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1302 self.enqueue_encoded_message(&mut *peer, &encoded_msg);
1305 wire::Message::ChannelUpdate(ref msg) => {
1306 log_gossip!(self.logger, "Sending message to all peers except {:?}: {:?}", except_node, msg);
1307 let encoded_msg = encode_msg!(msg);
1309 for (_, peer_mutex) in peers.peers.iter() {
1310 let mut peer = peer_mutex.lock().unwrap();
1311 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1312 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1315 if peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP
1316 || peer.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO
1318 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1321 if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1324 self.enqueue_encoded_message(&mut *peer, &encoded_msg);
1327 _ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),
1331 /// Checks for any events generated by our handlers and processes them. Includes sending most
1332 /// response messages as well as messages generated by calls to handler functions directly (eg
1333 /// functions like [`ChannelManager::process_pending_htlc_forwards`] or [`send_payment`]).
1335 /// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1338 /// You don't have to call this function explicitly if you are using [`lightning-net-tokio`]
1339 /// or one of the other clients provided in our language bindings.
1341 /// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1342 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
1343 /// [`send_data`]: SocketDescriptor::send_data
1344 pub fn process_events(&self) {
1346 // TODO: There are some DoS attacks here where you can flood someone's outbound send
1347 // buffer by doing things like announcing channels on another node. We should be willing to
1348 // drop optional-ish messages when send buffers get full!
1350 let mut peers_lock = self.peers.write().unwrap();
1351 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
1352 events_generated.append(&mut self.message_handler.route_handler.get_and_clear_pending_msg_events());
1353 let peers = &mut *peers_lock;
1354 macro_rules! get_peer_for_forwarding {
1355 ($node_id: expr) => {
1357 match self.node_id_to_descriptor.lock().unwrap().get($node_id) {
1358 Some(descriptor) => match peers.peers.get_mut(&descriptor) {
1359 Some(peer_mutex) => {
1360 let peer_lock = peer_mutex.lock().unwrap();
1361 if peer_lock.their_features.is_none() {
1366 None => panic!("Inconsistent peers set state!"),
1375 for event in events_generated.drain(..) {
1377 MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
1378 log_debug!(self.logger, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
1379 log_pubkey!(node_id),
1380 log_bytes!(msg.temporary_channel_id));
1381 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1383 MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
1384 log_debug!(self.logger, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
1385 log_pubkey!(node_id),
1386 log_bytes!(msg.temporary_channel_id));
1387 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1389 MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
1390 log_debug!(self.logger, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
1391 log_pubkey!(node_id),
1392 log_bytes!(msg.temporary_channel_id),
1393 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
1394 // TODO: If the peer is gone we should generate a DiscardFunding event
1395 // indicating to the wallet that they should just throw away this funding transaction
1396 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1398 MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
1399 log_debug!(self.logger, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
1400 log_pubkey!(node_id),
1401 log_bytes!(msg.channel_id));
1402 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1404 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
1405 log_debug!(self.logger, "Handling SendFundingLocked event in peer_handler for node {} for channel {}",
1406 log_pubkey!(node_id),
1407 log_bytes!(msg.channel_id));
1408 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1410 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
1411 log_debug!(self.logger, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
1412 log_pubkey!(node_id),
1413 log_bytes!(msg.channel_id));
1414 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1416 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 } } => {
1417 log_debug!(self.logger, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
1418 log_pubkey!(node_id),
1419 update_add_htlcs.len(),
1420 update_fulfill_htlcs.len(),
1421 update_fail_htlcs.len(),
1422 log_bytes!(commitment_signed.channel_id));
1423 let mut peer = get_peer_for_forwarding!(node_id);
1424 for msg in update_add_htlcs {
1425 self.enqueue_message(&mut *peer, msg);
1427 for msg in update_fulfill_htlcs {
1428 self.enqueue_message(&mut *peer, msg);
1430 for msg in update_fail_htlcs {
1431 self.enqueue_message(&mut *peer, msg);
1433 for msg in update_fail_malformed_htlcs {
1434 self.enqueue_message(&mut *peer, msg);
1436 if let &Some(ref msg) = update_fee {
1437 self.enqueue_message(&mut *peer, msg);
1439 self.enqueue_message(&mut *peer, commitment_signed);
1441 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1442 log_debug!(self.logger, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
1443 log_pubkey!(node_id),
1444 log_bytes!(msg.channel_id));
1445 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1447 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1448 log_debug!(self.logger, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
1449 log_pubkey!(node_id),
1450 log_bytes!(msg.channel_id));
1451 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1453 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
1454 log_debug!(self.logger, "Handling Shutdown event in peer_handler for node {} for channel {}",
1455 log_pubkey!(node_id),
1456 log_bytes!(msg.channel_id));
1457 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1459 MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
1460 log_debug!(self.logger, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
1461 log_pubkey!(node_id),
1462 log_bytes!(msg.channel_id));
1463 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1465 MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
1466 log_debug!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1467 match self.message_handler.route_handler.handle_channel_announcement(&msg) {
1468 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1469 self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None),
1472 match self.message_handler.route_handler.handle_channel_update(&update_msg) {
1473 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1474 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(update_msg), None),
1478 MessageSendEvent::BroadcastNodeAnnouncement { msg } => {
1479 log_debug!(self.logger, "Handling BroadcastNodeAnnouncement event in peer_handler");
1480 match self.message_handler.route_handler.handle_node_announcement(&msg) {
1481 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1482 self.forward_broadcast_msg(peers, &wire::Message::NodeAnnouncement(msg), None),
1486 MessageSendEvent::BroadcastChannelUpdate { msg } => {
1487 log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1488 match self.message_handler.route_handler.handle_channel_update(&msg) {
1489 Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1490 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
1494 MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
1495 log_trace!(self.logger, "Handling SendChannelUpdate event in peer_handler for node {} for channel {}",
1496 log_pubkey!(node_id), msg.contents.short_channel_id);
1497 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1499 MessageSendEvent::HandleError { ref node_id, ref action } => {
1501 msgs::ErrorAction::DisconnectPeer { ref msg } => {
1502 // Note that since we are holding the peers *write* lock we can
1503 // remove from node_id_to_descriptor immediately (as no other
1504 // thread can be holding the peer lock if we have the global write
1506 if let Some(mut descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(node_id) {
1507 if let Some(peer_mutex) = peers.peers.remove(&descriptor) {
1508 if let Some(ref msg) = *msg {
1509 log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
1510 log_pubkey!(node_id),
1512 let mut peer = peer_mutex.lock().unwrap();
1513 self.enqueue_message(&mut *peer, msg);
1514 // This isn't guaranteed to work, but if there is enough free
1515 // room in the send buffer, put the error message there...
1516 self.do_attempt_write_data(&mut descriptor, &mut *peer);
1518 log_gossip!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with no message", log_pubkey!(node_id));
1521 descriptor.disconnect_socket();
1522 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1525 msgs::ErrorAction::IgnoreAndLog(level) => {
1526 log_given_level!(self.logger, level, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
1528 msgs::ErrorAction::IgnoreDuplicateGossip => {},
1529 msgs::ErrorAction::IgnoreError => {
1530 log_debug!(self.logger, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
1532 msgs::ErrorAction::SendErrorMessage { ref msg } => {
1533 log_trace!(self.logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
1534 log_pubkey!(node_id),
1536 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1538 msgs::ErrorAction::SendWarningMessage { ref msg, ref log_level } => {
1539 log_given_level!(self.logger, *log_level, "Handling SendWarningMessage HandleError event in peer_handler for node {} with message {}",
1540 log_pubkey!(node_id),
1542 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1546 MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
1547 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1549 MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
1550 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1552 MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
1553 log_gossip!(self.logger, "Handling SendReplyChannelRange event in peer_handler for node {} with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}",
1554 log_pubkey!(node_id),
1555 msg.short_channel_ids.len(),
1557 msg.number_of_blocks,
1559 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1561 MessageSendEvent::SendGossipTimestampFilter { ref node_id, ref msg } => {
1562 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1567 for (node_id, msg) in self.custom_message_handler.get_and_clear_pending_msg() {
1568 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), &msg);
1571 for (descriptor, peer_mutex) in peers.peers.iter_mut() {
1572 self.do_attempt_write_data(&mut (*descriptor).clone(), &mut *peer_mutex.lock().unwrap());
1577 /// Indicates that the given socket descriptor's connection is now closed.
1578 pub fn socket_disconnected(&self, descriptor: &Descriptor) {
1579 self.disconnect_event_internal(descriptor, false);
1582 fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
1583 let mut peers = self.peers.write().unwrap();
1584 let peer_option = peers.peers.remove(descriptor);
1587 // This is most likely a simple race condition where the user found that the socket
1588 // was disconnected, then we told the user to `disconnect_socket()`, then they
1589 // called this method. Either way we're disconnected, return.
1591 Some(peer_lock) => {
1592 let peer = peer_lock.lock().unwrap();
1593 match peer.their_node_id {
1595 log_trace!(self.logger,
1596 "Handling disconnection of peer {}, with {}future connection to the peer possible.",
1597 log_pubkey!(node_id), if no_connection_possible { "no " } else { "" });
1598 self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
1599 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1607 /// Disconnect a peer given its node id.
1609 /// Set `no_connection_possible` to true to prevent any further connection with this peer,
1610 /// force-closing any channels we have with it.
1612 /// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the
1613 /// peer. Thus, be very careful about reentrancy issues.
1615 /// [`disconnect_socket`]: SocketDescriptor::disconnect_socket
1616 pub fn disconnect_by_node_id(&self, node_id: PublicKey, no_connection_possible: bool) {
1617 let mut peers_lock = self.peers.write().unwrap();
1618 if let Some(mut descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
1619 log_trace!(self.logger, "Disconnecting peer with id {} due to client request", node_id);
1620 peers_lock.peers.remove(&descriptor);
1621 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1622 descriptor.disconnect_socket();
1626 /// Disconnects all currently-connected peers. This is useful on platforms where there may be
1627 /// an indication that TCP sockets have stalled even if we weren't around to time them out
1628 /// using regular ping/pongs.
1629 pub fn disconnect_all_peers(&self) {
1630 let mut peers_lock = self.peers.write().unwrap();
1631 self.node_id_to_descriptor.lock().unwrap().clear();
1632 let peers = &mut *peers_lock;
1633 for (mut descriptor, peer) in peers.peers.drain() {
1634 if let Some(node_id) = peer.lock().unwrap().their_node_id {
1635 log_trace!(self.logger, "Disconnecting peer with id {} due to client request to disconnect all peers", node_id);
1636 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1638 descriptor.disconnect_socket();
1642 /// This is called when we're blocked on sending additional gossip messages until we receive a
1643 /// pong. If we aren't waiting on a pong, we take this opportunity to send a ping (setting
1644 /// `awaiting_pong_timer_tick_intervals` to a special flag value to indicate this).
1645 fn maybe_send_extra_ping(&self, peer: &mut Peer) {
1646 if peer.awaiting_pong_timer_tick_intervals == 0 {
1647 peer.awaiting_pong_timer_tick_intervals = -1;
1648 let ping = msgs::Ping {
1652 self.enqueue_message(peer, &ping);
1656 /// Send pings to each peer and disconnect those which did not respond to the last round of
1659 /// This may be called on any timescale you want, however, roughly once every ten seconds is
1660 /// preferred. The call rate determines both how often we send a ping to our peers and how much
1661 /// time they have to respond before we disconnect them.
1663 /// May call [`send_data`] on all [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1666 /// [`send_data`]: SocketDescriptor::send_data
1667 pub fn timer_tick_occurred(&self) {
1668 let mut peers_lock = self.peers.write().unwrap();
1670 let mut descriptors_needing_disconnect = Vec::new();
1671 let peer_count = peers_lock.peers.len();
1673 peers_lock.peers.retain(|descriptor, peer_mutex| {
1674 let mut peer = peer_mutex.lock().unwrap();
1675 let mut do_disconnect_peer = false;
1676 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_node_id.is_none() {
1677 // The peer needs to complete its handshake before we can exchange messages. We
1678 // give peers one timer tick to complete handshake, reusing
1679 // `awaiting_pong_timer_tick_intervals` to track number of timer ticks taken
1680 // for handshake completion.
1681 if peer.awaiting_pong_timer_tick_intervals != 0 {
1682 do_disconnect_peer = true;
1684 peer.awaiting_pong_timer_tick_intervals = 1;
1689 if peer.awaiting_pong_timer_tick_intervals == -1 {
1690 // Magic value set in `maybe_send_extra_ping`.
1691 peer.awaiting_pong_timer_tick_intervals = 1;
1692 peer.received_message_since_timer_tick = false;
1696 if do_disconnect_peer
1697 || (peer.awaiting_pong_timer_tick_intervals > 0 && !peer.received_message_since_timer_tick)
1698 || peer.awaiting_pong_timer_tick_intervals as u64 >
1699 MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER as u64 * peer_count as u64
1701 descriptors_needing_disconnect.push(descriptor.clone());
1702 match peer.their_node_id {
1704 log_trace!(self.logger, "Disconnecting peer with id {} due to ping timeout", node_id);
1705 self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
1706 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1712 peer.received_message_since_timer_tick = false;
1714 if peer.awaiting_pong_timer_tick_intervals > 0 {
1715 peer.awaiting_pong_timer_tick_intervals += 1;
1719 peer.awaiting_pong_timer_tick_intervals = 1;
1720 let ping = msgs::Ping {
1724 self.enqueue_message(&mut *peer, &ping);
1725 self.do_attempt_write_data(&mut (descriptor.clone()), &mut *peer);
1730 for mut descriptor in descriptors_needing_disconnect.drain(..) {
1731 descriptor.disconnect_socket();
1737 fn is_gossip_msg(type_id: u16) -> bool {
1739 msgs::ChannelAnnouncement::TYPE |
1740 msgs::ChannelUpdate::TYPE |
1741 msgs::NodeAnnouncement::TYPE |
1742 msgs::QueryChannelRange::TYPE |
1743 msgs::ReplyChannelRange::TYPE |
1744 msgs::QueryShortChannelIds::TYPE |
1745 msgs::ReplyShortChannelIdsEnd::TYPE => true,
1752 use ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler, filter_addresses};
1754 use ln::msgs::NetAddress;
1756 use util::test_utils;
1758 use bitcoin::secp256k1::Secp256k1;
1759 use bitcoin::secp256k1::key::{SecretKey, PublicKey};
1762 use sync::{Arc, Mutex};
1763 use core::sync::atomic::Ordering;
1766 struct FileDescriptor {
1768 outbound_data: Arc<Mutex<Vec<u8>>>,
1770 impl PartialEq for FileDescriptor {
1771 fn eq(&self, other: &Self) -> bool {
1775 impl Eq for FileDescriptor { }
1776 impl core::hash::Hash for FileDescriptor {
1777 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
1778 self.fd.hash(hasher)
1782 impl SocketDescriptor for FileDescriptor {
1783 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
1784 self.outbound_data.lock().unwrap().extend_from_slice(data);
1788 fn disconnect_socket(&mut self) {}
1791 struct PeerManagerCfg {
1792 chan_handler: test_utils::TestChannelMessageHandler,
1793 routing_handler: test_utils::TestRoutingMessageHandler,
1794 logger: test_utils::TestLogger,
1797 fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
1798 let mut cfgs = Vec::new();
1799 for _ in 0..peer_count {
1802 chan_handler: test_utils::TestChannelMessageHandler::new(),
1803 logger: test_utils::TestLogger::new(),
1804 routing_handler: test_utils::TestRoutingMessageHandler::new(),
1812 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>> {
1813 let mut peers = Vec::new();
1814 for i in 0..peer_count {
1815 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
1816 let ephemeral_bytes = [i as u8; 32];
1817 let msg_handler = MessageHandler { chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler };
1818 let peer = PeerManager::new(msg_handler, node_secret, &ephemeral_bytes, &cfgs[i].logger, IgnoringMessageHandler {});
1825 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) {
1826 let secp_ctx = Secp256k1::new();
1827 let a_id = PublicKey::from_secret_key(&secp_ctx, &peer_a.our_node_secret);
1828 let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1829 let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1830 let initial_data = peer_b.new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
1831 peer_a.new_inbound_connection(fd_a.clone(), None).unwrap();
1832 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
1833 peer_a.process_events();
1834 assert_eq!(peer_b.read_event(&mut fd_b, &fd_a.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
1835 peer_b.process_events();
1836 assert_eq!(peer_a.read_event(&mut fd_a, &fd_b.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
1837 peer_a.process_events();
1838 assert_eq!(peer_b.read_event(&mut fd_b, &fd_a.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
1839 (fd_a.clone(), fd_b.clone())
1843 fn test_disconnect_peer() {
1844 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
1845 // push a DisconnectPeer event to remove the node flagged by id
1846 let cfgs = create_peermgr_cfgs(2);
1847 let chan_handler = test_utils::TestChannelMessageHandler::new();
1848 let mut peers = create_network(2, &cfgs);
1849 establish_connection(&peers[0], &peers[1]);
1850 assert_eq!(peers[0].peers.read().unwrap().peers.len(), 1);
1852 let secp_ctx = Secp256k1::new();
1853 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
1855 chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
1857 action: msgs::ErrorAction::DisconnectPeer { msg: None },
1859 assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1);
1860 peers[0].message_handler.chan_handler = &chan_handler;
1862 peers[0].process_events();
1863 assert_eq!(peers[0].peers.read().unwrap().peers.len(), 0);
1867 fn test_timer_tick_occurred() {
1868 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
1869 let cfgs = create_peermgr_cfgs(2);
1870 let peers = create_network(2, &cfgs);
1871 establish_connection(&peers[0], &peers[1]);
1872 assert_eq!(peers[0].peers.read().unwrap().peers.len(), 1);
1874 // peers[0] awaiting_pong is set to true, but the Peer is still connected
1875 peers[0].timer_tick_occurred();
1876 peers[0].process_events();
1877 assert_eq!(peers[0].peers.read().unwrap().peers.len(), 1);
1879 // Since timer_tick_occurred() is called again when awaiting_pong is true, all Peers are disconnected
1880 peers[0].timer_tick_occurred();
1881 peers[0].process_events();
1882 assert_eq!(peers[0].peers.read().unwrap().peers.len(), 0);
1886 fn test_do_attempt_write_data() {
1887 // Create 2 peers with custom TestRoutingMessageHandlers and connect them.
1888 let cfgs = create_peermgr_cfgs(2);
1889 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
1890 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
1891 let peers = create_network(2, &cfgs);
1893 // By calling establish_connect, we trigger do_attempt_write_data between
1894 // the peers. Previously this function would mistakenly enter an infinite loop
1895 // when there were more channel messages available than could fit into a peer's
1896 // buffer. This issue would now be detected by this test (because we use custom
1897 // RoutingMessageHandlers that intentionally return more channel messages
1898 // than can fit into a peer's buffer).
1899 let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
1901 // Make each peer to read the messages that the other peer just wrote to them. Note that
1902 // due to the max-message-before-ping limits this may take a few iterations to complete.
1903 for _ in 0..150/super::BUFFER_DRAIN_MSGS_PER_TICK + 1 {
1904 peers[1].process_events();
1905 let a_read_data = fd_b.outbound_data.lock().unwrap().split_off(0);
1906 assert!(!a_read_data.is_empty());
1908 peers[0].read_event(&mut fd_a, &a_read_data).unwrap();
1909 peers[0].process_events();
1911 let b_read_data = fd_a.outbound_data.lock().unwrap().split_off(0);
1912 assert!(!b_read_data.is_empty());
1913 peers[1].read_event(&mut fd_b, &b_read_data).unwrap();
1915 peers[0].process_events();
1916 assert_eq!(fd_a.outbound_data.lock().unwrap().len(), 0, "Until A receives data, it shouldn't send more messages");
1919 // Check that each peer has received the expected number of channel updates and channel
1921 assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 100);
1922 assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 50);
1923 assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 100);
1924 assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 50);
1928 fn test_handshake_timeout() {
1929 // Tests that we time out a peer still waiting on handshake completion after a full timer
1931 let cfgs = create_peermgr_cfgs(2);
1932 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
1933 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
1934 let peers = create_network(2, &cfgs);
1936 let secp_ctx = Secp256k1::new();
1937 let a_id = PublicKey::from_secret_key(&secp_ctx, &peers[0].our_node_secret);
1938 let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1939 let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1940 let initial_data = peers[1].new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
1941 peers[0].new_inbound_connection(fd_a.clone(), None).unwrap();
1943 // If we get a single timer tick before completion, that's fine
1944 assert_eq!(peers[0].peers.read().unwrap().peers.len(), 1);
1945 peers[0].timer_tick_occurred();
1946 assert_eq!(peers[0].peers.read().unwrap().peers.len(), 1);
1948 assert_eq!(peers[0].read_event(&mut fd_a, &initial_data).unwrap(), false);
1949 peers[0].process_events();
1950 assert_eq!(peers[1].read_event(&mut fd_b, &fd_a.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
1951 peers[1].process_events();
1953 // ...but if we get a second timer tick, we should disconnect the peer
1954 peers[0].timer_tick_occurred();
1955 assert_eq!(peers[0].peers.read().unwrap().peers.len(), 0);
1957 assert!(peers[0].read_event(&mut fd_a, &fd_b.outbound_data.lock().unwrap().split_off(0)).is_err());
1961 fn test_filter_addresses(){
1962 // Tests the filter_addresses function.
1965 let ip_address = NetAddress::IPv4{addr: [10, 0, 0, 0], port: 1000};
1966 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
1967 let ip_address = NetAddress::IPv4{addr: [10, 0, 255, 201], port: 1000};
1968 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
1969 let ip_address = NetAddress::IPv4{addr: [10, 255, 255, 255], port: 1000};
1970 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
1973 let ip_address = NetAddress::IPv4{addr: [0, 0, 0, 0], port: 1000};
1974 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
1975 let ip_address = NetAddress::IPv4{addr: [0, 0, 255, 187], port: 1000};
1976 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
1977 let ip_address = NetAddress::IPv4{addr: [0, 255, 255, 255], port: 1000};
1978 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
1981 let ip_address = NetAddress::IPv4{addr: [100, 64, 0, 0], port: 1000};
1982 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
1983 let ip_address = NetAddress::IPv4{addr: [100, 78, 255, 0], port: 1000};
1984 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
1985 let ip_address = NetAddress::IPv4{addr: [100, 127, 255, 255], port: 1000};
1986 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
1989 let ip_address = NetAddress::IPv4{addr: [127, 0, 0, 0], port: 1000};
1990 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
1991 let ip_address = NetAddress::IPv4{addr: [127, 65, 73, 0], port: 1000};
1992 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
1993 let ip_address = NetAddress::IPv4{addr: [127, 255, 255, 255], port: 1000};
1994 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
1997 let ip_address = NetAddress::IPv4{addr: [169, 254, 0, 0], port: 1000};
1998 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
1999 let ip_address = NetAddress::IPv4{addr: [169, 254, 221, 101], port: 1000};
2000 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2001 let ip_address = NetAddress::IPv4{addr: [169, 254, 255, 255], port: 1000};
2002 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2005 let ip_address = NetAddress::IPv4{addr: [172, 16, 0, 0], port: 1000};
2006 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2007 let ip_address = NetAddress::IPv4{addr: [172, 27, 101, 23], port: 1000};
2008 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2009 let ip_address = NetAddress::IPv4{addr: [172, 31, 255, 255], port: 1000};
2010 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2013 let ip_address = NetAddress::IPv4{addr: [192, 168, 0, 0], port: 1000};
2014 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2015 let ip_address = NetAddress::IPv4{addr: [192, 168, 205, 159], port: 1000};
2016 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2017 let ip_address = NetAddress::IPv4{addr: [192, 168, 255, 255], port: 1000};
2018 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2020 // For (192.88.99/24)
2021 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 0], port: 1000};
2022 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2023 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 140], port: 1000};
2024 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2025 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 255], port: 1000};
2026 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2028 // For other IPv4 addresses
2029 let ip_address = NetAddress::IPv4{addr: [188, 255, 99, 0], port: 1000};
2030 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2031 let ip_address = NetAddress::IPv4{addr: [123, 8, 129, 14], port: 1000};
2032 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2033 let ip_address = NetAddress::IPv4{addr: [2, 88, 9, 255], port: 1000};
2034 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2037 let ip_address = NetAddress::IPv6{addr: [32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], port: 1000};
2038 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2039 let ip_address = NetAddress::IPv6{addr: [45, 34, 209, 190, 0, 123, 55, 34, 0, 0, 3, 27, 201, 0, 0, 0], port: 1000};
2040 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2041 let ip_address = NetAddress::IPv6{addr: [63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], port: 1000};
2042 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2044 // For other IPv6 addresses
2045 let ip_address = NetAddress::IPv6{addr: [24, 240, 12, 32, 0, 0, 0, 0, 20, 97, 0, 32, 121, 254, 0, 0], port: 1000};
2046 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2047 let ip_address = NetAddress::IPv6{addr: [68, 23, 56, 63, 0, 0, 2, 7, 75, 109, 0, 39, 0, 0, 0, 0], port: 1000};
2048 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2049 let ip_address = NetAddress::IPv6{addr: [101, 38, 140, 230, 100, 0, 30, 98, 0, 26, 0, 0, 57, 96, 0, 0], port: 1000};
2050 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2053 assert_eq!(filter_addresses(None), None);