Fetch our `InitFeatures` from `ChannelMessageHandler`
[rust-lightning] / lightning / src / ln / peer_handler.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
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
8 // licenses.
9
10 //! Top level peer message handling and socket handling logic lives here.
11 //!
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 P2PGossipSync) with
16 //! messages they should handle, and encoding/sending response messages.
17
18 use bitcoin::secp256k1::{self, Secp256k1, SecretKey, PublicKey};
19
20 use ln::features::{InitFeatures, NodeFeatures};
21 use ln::msgs;
22 use ln::msgs::{ChannelMessageHandler, LightningError, NetAddress, OnionMessageHandler, RoutingMessageHandler};
23 use ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager};
24 use util::ser::{VecWriter, Writeable, Writer};
25 use ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
26 use ln::wire;
27 use ln::wire::Encode;
28 use routing::gossip::{NetworkGraph, P2PGossipSync};
29 use util::atomic_counter::AtomicCounter;
30 use util::crypto::sign;
31 use util::events::{MessageSendEvent, MessageSendEventsProvider, OnionMessageProvider};
32 use util::logger::Logger;
33
34 use prelude::*;
35 use io;
36 use alloc::collections::LinkedList;
37 use sync::{Arc, Mutex, MutexGuard, FairRwLock};
38 use core::sync::atomic::{AtomicBool, AtomicU64, Ordering};
39 use core::{cmp, hash, fmt, mem};
40 use core::ops::Deref;
41 use core::convert::Infallible;
42 #[cfg(feature = "std")] use std::error;
43
44 use bitcoin::hashes::sha256::Hash as Sha256;
45 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
46 use bitcoin::hashes::sha256::HashEngine as Sha256Engine;
47 use bitcoin::hashes::{HashEngine, Hash};
48
49 /// Handler for BOLT1-compliant messages.
50 pub trait CustomMessageHandler: wire::CustomMessageReader {
51         /// Called with the message type that was received and the buffer to be read.
52         /// Can return a `MessageHandlingError` if the message could not be handled.
53         fn handle_custom_message(&self, msg: Self::CustomMessage, sender_node_id: &PublicKey) -> Result<(), LightningError>;
54
55         /// Gets the list of pending messages which were generated by the custom message
56         /// handler, clearing the list in the process. The first tuple element must
57         /// correspond to the intended recipients node ids. If no connection to one of the
58         /// specified node does not exist, the message is simply not sent to it.
59         fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)>;
60 }
61
62 /// A dummy struct which implements `RoutingMessageHandler` without storing any routing information
63 /// or doing any processing. You can provide one of these as the route_handler in a MessageHandler.
64 pub struct IgnoringMessageHandler{}
65 impl MessageSendEventsProvider for IgnoringMessageHandler {
66         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> { Vec::new() }
67 }
68 impl RoutingMessageHandler for IgnoringMessageHandler {
69         fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> { Ok(false) }
70         fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> { Ok(false) }
71         fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> { Ok(false) }
72         fn get_next_channel_announcement(&self, _starting_point: u64) ->
73                 Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> { None }
74         fn get_next_node_announcement(&self, _starting_point: Option<&PublicKey>) -> Option<msgs::NodeAnnouncement> { None }
75         fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init) {}
76         fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), LightningError> { Ok(()) }
77         fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), LightningError> { Ok(()) }
78         fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), LightningError> { Ok(()) }
79         fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), LightningError> { Ok(()) }
80 }
81 impl OnionMessageProvider for IgnoringMessageHandler {
82         fn next_onion_message_for_peer(&self, _peer_node_id: PublicKey) -> Option<msgs::OnionMessage> { None }
83 }
84 impl OnionMessageHandler for IgnoringMessageHandler {
85         fn handle_onion_message(&self, _their_node_id: &PublicKey, _msg: &msgs::OnionMessage) {}
86         fn peer_connected(&self, _their_node_id: &PublicKey, _init: &msgs::Init) {}
87         fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
88 }
89 impl Deref for IgnoringMessageHandler {
90         type Target = IgnoringMessageHandler;
91         fn deref(&self) -> &Self { self }
92 }
93
94 // Implement Type for Infallible, note that it cannot be constructed, and thus you can never call a
95 // method that takes self for it.
96 impl wire::Type for Infallible {
97         fn type_id(&self) -> u16 {
98                 unreachable!();
99         }
100 }
101 impl Writeable for Infallible {
102         fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
103                 unreachable!();
104         }
105 }
106
107 impl wire::CustomMessageReader for IgnoringMessageHandler {
108         type CustomMessage = Infallible;
109         fn read<R: io::Read>(&self, _message_type: u16, _buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {
110                 Ok(None)
111         }
112 }
113
114 impl CustomMessageHandler for IgnoringMessageHandler {
115         fn handle_custom_message(&self, _msg: Infallible, _sender_node_id: &PublicKey) -> Result<(), LightningError> {
116                 // Since we always return `None` in the read the handle method should never be called.
117                 unreachable!();
118         }
119
120         fn get_and_clear_pending_msg(&self) -> Vec<(PublicKey, Self::CustomMessage)> { Vec::new() }
121 }
122
123 /// A dummy struct which implements `ChannelMessageHandler` without having any channels.
124 /// You can provide one of these as the route_handler in a MessageHandler.
125 pub struct ErroringMessageHandler {
126         message_queue: Mutex<Vec<MessageSendEvent>>
127 }
128 impl ErroringMessageHandler {
129         /// Constructs a new ErroringMessageHandler
130         pub fn new() -> Self {
131                 Self { message_queue: Mutex::new(Vec::new()) }
132         }
133         fn push_error(&self, node_id: &PublicKey, channel_id: [u8; 32]) {
134                 self.message_queue.lock().unwrap().push(MessageSendEvent::HandleError {
135                         action: msgs::ErrorAction::SendErrorMessage {
136                                 msg: msgs::ErrorMessage { channel_id, data: "We do not support channel messages, sorry.".to_owned() },
137                         },
138                         node_id: node_id.clone(),
139                 });
140         }
141 }
142 impl MessageSendEventsProvider for ErroringMessageHandler {
143         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
144                 let mut res = Vec::new();
145                 mem::swap(&mut res, &mut self.message_queue.lock().unwrap());
146                 res
147         }
148 }
149 impl ChannelMessageHandler for ErroringMessageHandler {
150         // Any messages which are related to a specific channel generate an error message to let the
151         // peer know we don't care about channels.
152         fn handle_open_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::OpenChannel) {
153                 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
154         }
155         fn handle_accept_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::AcceptChannel) {
156                 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
157         }
158         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
159                 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
160         }
161         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
162                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
163         }
164         fn handle_channel_ready(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
165                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
166         }
167         fn handle_shutdown(&self, their_node_id: &PublicKey, _their_features: &InitFeatures, msg: &msgs::Shutdown) {
168                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
169         }
170         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
171                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
172         }
173         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
174                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
175         }
176         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
177                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
178         }
179         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
180                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
181         }
182         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
183                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
184         }
185         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
186                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
187         }
188         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
189                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
190         }
191         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
192                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
193         }
194         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
195                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
196         }
197         fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
198                 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
199         }
200         // msgs::ChannelUpdate does not contain the channel_id field, so we just drop them.
201         fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {}
202         fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
203         fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) {}
204         fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
205         fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
206         fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures { InitFeatures::known() }
207 }
208 impl Deref for ErroringMessageHandler {
209         type Target = ErroringMessageHandler;
210         fn deref(&self) -> &Self { self }
211 }
212
213 /// Provides references to trait impls which handle different types of messages.
214 pub struct MessageHandler<CM: Deref, RM: Deref, OM: Deref> where
215                 CM::Target: ChannelMessageHandler,
216                 RM::Target: RoutingMessageHandler,
217                 OM::Target: OnionMessageHandler,
218 {
219         /// A message handler which handles messages specific to channels. Usually this is just a
220         /// [`ChannelManager`] object or an [`ErroringMessageHandler`].
221         ///
222         /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
223         pub chan_handler: CM,
224         /// A message handler which handles messages updating our knowledge of the network channel
225         /// graph. Usually this is just a [`P2PGossipSync`] object or an [`IgnoringMessageHandler`].
226         ///
227         /// [`P2PGossipSync`]: crate::routing::gossip::P2PGossipSync
228         pub route_handler: RM,
229
230         /// A message handler which handles onion messages. For now, this can only be an
231         /// [`IgnoringMessageHandler`].
232         pub onion_message_handler: OM,
233 }
234
235 /// Provides an object which can be used to send data to and which uniquely identifies a connection
236 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
237 /// implement Hash to meet the PeerManager API.
238 ///
239 /// For efficiency, Clone should be relatively cheap for this type.
240 ///
241 /// Two descriptors may compare equal (by [`cmp::Eq`] and [`hash::Hash`]) as long as the original
242 /// has been disconnected, the [`PeerManager`] has been informed of the disconnection (either by it
243 /// having triggered the disconnection or a call to [`PeerManager::socket_disconnected`]), and no
244 /// further calls to the [`PeerManager`] related to the original socket occur. This allows you to
245 /// use a file descriptor for your SocketDescriptor directly, however for simplicity you may wish
246 /// to simply use another value which is guaranteed to be globally unique instead.
247 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
248         /// Attempts to send some data from the given slice to the peer.
249         ///
250         /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
251         /// Note that in the disconnected case, [`PeerManager::socket_disconnected`] must still be
252         /// called and further write attempts may occur until that time.
253         ///
254         /// If the returned size is smaller than `data.len()`, a
255         /// [`PeerManager::write_buffer_space_avail`] call must be made the next time more data can be
256         /// written. Additionally, until a `send_data` event completes fully, no further
257         /// [`PeerManager::read_event`] calls should be made for the same peer! Because this is to
258         /// prevent denial-of-service issues, you should not read or buffer any data from the socket
259         /// until then.
260         ///
261         /// If a [`PeerManager::read_event`] call on this descriptor had previously returned true
262         /// (indicating that read events should be paused to prevent DoS in the send buffer),
263         /// `resume_read` may be set indicating that read events on this descriptor should resume. A
264         /// `resume_read` of false carries no meaning, and should not cause any action.
265         fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize;
266         /// Disconnect the socket pointed to by this SocketDescriptor.
267         ///
268         /// You do *not* need to call [`PeerManager::socket_disconnected`] with this socket after this
269         /// call (doing so is a noop).
270         fn disconnect_socket(&mut self);
271 }
272
273 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
274 /// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the
275 /// descriptor.
276 #[derive(Clone)]
277 pub struct PeerHandleError {
278         /// Used to indicate that we probably can't make any future connections to this peer (e.g.
279         /// because we required features that our peer was missing, or vice versa).
280         ///
281         /// While LDK's [`ChannelManager`] will not do it automatically, you likely wish to force-close
282         /// any channels with this peer or check for new versions of LDK.
283         ///
284         /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
285         pub no_connection_possible: bool,
286 }
287 impl fmt::Debug for PeerHandleError {
288         fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
289                 formatter.write_str("Peer Sent Invalid Data")
290         }
291 }
292 impl fmt::Display for PeerHandleError {
293         fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
294                 formatter.write_str("Peer Sent Invalid Data")
295         }
296 }
297
298 #[cfg(feature = "std")]
299 impl error::Error for PeerHandleError {
300         fn description(&self) -> &str {
301                 "Peer Sent Invalid Data"
302         }
303 }
304
305 enum InitSyncTracker{
306         NoSyncRequested,
307         ChannelsSyncing(u64),
308         NodesSyncing(PublicKey),
309 }
310
311 /// The ratio between buffer sizes at which we stop sending initial sync messages vs when we stop
312 /// forwarding gossip messages to peers altogether.
313 const FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO: usize = 2;
314
315 /// When the outbound buffer has this many messages, we'll stop reading bytes from the peer until
316 /// we have fewer than this many messages in the outbound buffer again.
317 /// We also use this as the target number of outbound gossip messages to keep in the write buffer,
318 /// refilled as we send bytes.
319 const OUTBOUND_BUFFER_LIMIT_READ_PAUSE: usize = 12;
320 /// When the outbound buffer has this many messages, we'll simply skip relaying gossip messages to
321 /// the peer.
322 const OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP: usize = OUTBOUND_BUFFER_LIMIT_READ_PAUSE * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO;
323
324 /// If we've sent a ping, and are still awaiting a response, we may need to churn our way through
325 /// the socket receive buffer before receiving the ping.
326 ///
327 /// On a fairly old Arm64 board, with Linux defaults, this can take as long as 20 seconds, not
328 /// including any network delays, outbound traffic, or the same for messages from other peers.
329 ///
330 /// Thus, to avoid needlessly disconnecting a peer, we allow a peer to take this many timer ticks
331 /// per connected peer to respond to a ping, as long as they send us at least one message during
332 /// each tick, ensuring we aren't actually just disconnected.
333 /// With a timer tick interval of ten seconds, this translates to about 40 seconds per connected
334 /// peer.
335 ///
336 /// When we improve parallelism somewhat we should reduce this to e.g. this many timer ticks per
337 /// two connected peers, assuming most LDK-running systems have at least two cores.
338 const MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER: i8 = 4;
339
340 /// This is the minimum number of messages we expect a peer to be able to handle within one timer
341 /// tick. Once we have sent this many messages since the last ping, we send a ping right away to
342 /// ensures we don't just fill up our send buffer and leave the peer with too many messages to
343 /// process before the next ping.
344 ///
345 /// Note that we continue responding to other messages even after we've sent this many messages, so
346 /// it's more of a general guideline used for gossip backfill (and gossip forwarding, times
347 /// [`FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO`]) than a hard limit.
348 const BUFFER_DRAIN_MSGS_PER_TICK: usize = 32;
349
350 struct Peer {
351         channel_encryptor: PeerChannelEncryptor,
352         their_node_id: Option<PublicKey>,
353         their_features: Option<InitFeatures>,
354         their_net_address: Option<NetAddress>,
355
356         pending_outbound_buffer: LinkedList<Vec<u8>>,
357         pending_outbound_buffer_first_msg_offset: usize,
358         // Queue gossip broadcasts separately from `pending_outbound_buffer` so we can easily prioritize
359         // channel messages over them.
360         gossip_broadcast_buffer: LinkedList<Vec<u8>>,
361         awaiting_write_event: bool,
362
363         pending_read_buffer: Vec<u8>,
364         pending_read_buffer_pos: usize,
365         pending_read_is_header: bool,
366
367         sync_status: InitSyncTracker,
368
369         msgs_sent_since_pong: usize,
370         awaiting_pong_timer_tick_intervals: i8,
371         received_message_since_timer_tick: bool,
372         sent_gossip_timestamp_filter: bool,
373 }
374
375 impl Peer {
376         /// Returns true if the channel announcements/updates for the given channel should be
377         /// forwarded to this peer.
378         /// If we are sending our routing table to this peer and we have not yet sent channel
379         /// announcements/updates for the given channel_id then we will send it when we get to that
380         /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
381         /// sent the old versions, we should send the update, and so return true here.
382         fn should_forward_channel_announcement(&self, channel_id: u64) -> bool {
383                 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
384                         !self.sent_gossip_timestamp_filter {
385                                 return false;
386                         }
387                 match self.sync_status {
388                         InitSyncTracker::NoSyncRequested => true,
389                         InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
390                         InitSyncTracker::NodesSyncing(_) => true,
391                 }
392         }
393
394         /// Similar to the above, but for node announcements indexed by node_id.
395         fn should_forward_node_announcement(&self, node_id: PublicKey) -> bool {
396                 if self.their_features.as_ref().unwrap().supports_gossip_queries() &&
397                         !self.sent_gossip_timestamp_filter {
398                                 return false;
399                         }
400                 match self.sync_status {
401                         InitSyncTracker::NoSyncRequested => true,
402                         InitSyncTracker::ChannelsSyncing(_) => false,
403                         InitSyncTracker::NodesSyncing(pk) => pk < node_id,
404                 }
405         }
406
407         /// Returns whether we should be reading bytes from this peer, based on whether its outbound
408         /// buffer still has space and we don't need to pause reads to get some writes out.
409         fn should_read(&self) -> bool {
410                 self.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE
411         }
412
413         /// Determines if we should push additional gossip background sync (aka "backfill") onto a peer's
414         /// outbound buffer. This is checked every time the peer's buffer may have been drained.
415         fn should_buffer_gossip_backfill(&self) -> bool {
416                 self.pending_outbound_buffer.is_empty() && self.gossip_broadcast_buffer.is_empty()
417                         && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
418         }
419
420         /// Determines if we should push an onion message onto a peer's outbound buffer. This is checked
421         /// every time the peer's buffer may have been drained.
422         fn should_buffer_onion_message(&self) -> bool {
423                 self.pending_outbound_buffer.is_empty()
424                         && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
425         }
426
427         /// Determines if we should push additional gossip broadcast messages onto a peer's outbound
428         /// buffer. This is checked every time the peer's buffer may have been drained.
429         fn should_buffer_gossip_broadcast(&self) -> bool {
430                 self.pending_outbound_buffer.is_empty()
431                         && self.msgs_sent_since_pong < BUFFER_DRAIN_MSGS_PER_TICK
432         }
433
434         /// Returns whether this peer's outbound buffers are full and we should drop gossip broadcasts.
435         fn buffer_full_drop_gossip_broadcast(&self) -> bool {
436                 let total_outbound_buffered =
437                         self.gossip_broadcast_buffer.len() + self.pending_outbound_buffer.len();
438
439                 total_outbound_buffered > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP ||
440                         self.msgs_sent_since_pong > BUFFER_DRAIN_MSGS_PER_TICK * FORWARD_INIT_SYNC_BUFFER_LIMIT_RATIO
441         }
442 }
443
444 /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
445 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
446 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
447 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
448 /// issues such as overly long function definitions.
449 ///
450 /// (C-not exported) as Arcs don't make sense in bindings
451 pub type SimpleArcPeerManager<SD, M, T, F, C, L> = PeerManager<SD, Arc<SimpleArcChannelManager<M, T, F, L>>, Arc<P2PGossipSync<Arc<NetworkGraph<Arc<L>>>, Arc<C>, Arc<L>>>, IgnoringMessageHandler, Arc<L>, Arc<IgnoringMessageHandler>>;
452
453 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
454 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
455 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
456 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
457 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
458 /// helps with issues such as long function definitions.
459 ///
460 /// (C-not exported) as Arcs don't make sense in bindings
461 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 P2PGossipSync<&'g NetworkGraph<&'f L>, &'h C, &'f L>, IgnoringMessageHandler, &'f L, IgnoringMessageHandler>;
462
463 /// A PeerManager manages a set of peers, described by their [`SocketDescriptor`] and marshalls
464 /// socket events into messages which it passes on to its [`MessageHandler`].
465 ///
466 /// Locks are taken internally, so you must never assume that reentrancy from a
467 /// [`SocketDescriptor`] call back into [`PeerManager`] methods will not deadlock.
468 ///
469 /// Calls to [`read_event`] will decode relevant messages and pass them to the
470 /// [`ChannelMessageHandler`], likely doing message processing in-line. Thus, the primary form of
471 /// parallelism in Rust-Lightning is in calls to [`read_event`]. Note, however, that calls to any
472 /// [`PeerManager`] functions related to the same connection must occur only in serial, making new
473 /// calls only after previous ones have returned.
474 ///
475 /// Rather than using a plain PeerManager, it is preferable to use either a SimpleArcPeerManager
476 /// a SimpleRefPeerManager, for conciseness. See their documentation for more details, but
477 /// essentially you should default to using a SimpleRefPeerManager, and use a
478 /// SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when
479 /// you're using lightning-net-tokio.
480 ///
481 /// [`read_event`]: PeerManager::read_event
482 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref> where
483                 CM::Target: ChannelMessageHandler,
484                 RM::Target: RoutingMessageHandler,
485                 OM::Target: OnionMessageHandler,
486                 L::Target: Logger,
487                 CMH::Target: CustomMessageHandler {
488         message_handler: MessageHandler<CM, RM, OM>,
489         /// Connection state for each connected peer - we have an outer read-write lock which is taken
490         /// as read while we're doing processing for a peer and taken write when a peer is being added
491         /// or removed.
492         ///
493         /// The inner Peer lock is held for sending and receiving bytes, but note that we do *not* hold
494         /// it while we're processing a message. This is fine as [`PeerManager::read_event`] requires
495         /// that there be no parallel calls for a given peer, so mutual exclusion of messages handed to
496         /// the `MessageHandler`s for a given peer is already guaranteed.
497         peers: FairRwLock<HashMap<Descriptor, Mutex<Peer>>>,
498         /// Only add to this set when noise completes.
499         /// Locked *after* peers. When an item is removed, it must be removed with the `peers` write
500         /// lock held. Entries may be added with only the `peers` read lock held (though the
501         /// `Descriptor` value must already exist in `peers`).
502         node_id_to_descriptor: Mutex<HashMap<PublicKey, Descriptor>>,
503         /// We can only have one thread processing events at once, but we don't usually need the full
504         /// `peers` write lock to do so, so instead we block on this empty mutex when entering
505         /// `process_events`.
506         event_processing_lock: Mutex<()>,
507         /// Because event processing is global and always does all available work before returning,
508         /// there is no reason for us to have many event processors waiting on the lock at once.
509         /// Instead, we limit the total blocked event processors to always exactly one by setting this
510         /// when an event process call is waiting.
511         blocked_event_processors: AtomicBool,
512
513         /// Used to track the last value sent in a node_announcement "timestamp" field. We ensure this
514         /// value increases strictly since we don't assume access to a time source.
515         last_node_announcement_serial: AtomicU64,
516
517         our_node_secret: SecretKey,
518         ephemeral_key_midstate: Sha256Engine,
519         custom_message_handler: CMH,
520
521         peer_counter: AtomicCounter,
522
523         logger: L,
524         secp_ctx: Secp256k1<secp256k1::SignOnly>
525 }
526
527 enum MessageHandlingError {
528         PeerHandleError(PeerHandleError),
529         LightningError(LightningError),
530 }
531
532 impl From<PeerHandleError> for MessageHandlingError {
533         fn from(error: PeerHandleError) -> Self {
534                 MessageHandlingError::PeerHandleError(error)
535         }
536 }
537
538 impl From<LightningError> for MessageHandlingError {
539         fn from(error: LightningError) -> Self {
540                 MessageHandlingError::LightningError(error)
541         }
542 }
543
544 macro_rules! encode_msg {
545         ($msg: expr) => {{
546                 let mut buffer = VecWriter(Vec::new());
547                 wire::write($msg, &mut buffer).unwrap();
548                 buffer.0
549         }}
550 }
551
552 impl<Descriptor: SocketDescriptor, CM: Deref, OM: Deref, L: Deref> PeerManager<Descriptor, CM, IgnoringMessageHandler, OM, L, IgnoringMessageHandler> where
553                 CM::Target: ChannelMessageHandler,
554                 OM::Target: OnionMessageHandler,
555                 L::Target: Logger {
556         /// Constructs a new `PeerManager` with the given `ChannelMessageHandler` and
557         /// `OnionMessageHandler`. No routing message handler is used and network graph messages are
558         /// ignored.
559         ///
560         /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
561         /// cryptographically secure random bytes.
562         ///
563         /// `current_time` is used as an always-increasing counter that survives across restarts and is
564         /// incremented irregularly internally. In general it is best to simply use the current UNIX
565         /// timestamp, however if it is not available a persistent counter that increases once per
566         /// minute should suffice.
567         ///
568         /// (C-not exported) as we can't export a PeerManager with a dummy route handler
569         pub fn new_channel_only(channel_message_handler: CM, onion_message_handler: OM, our_node_secret: SecretKey, current_time: u64, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
570                 Self::new(MessageHandler {
571                         chan_handler: channel_message_handler,
572                         route_handler: IgnoringMessageHandler{},
573                         onion_message_handler,
574                 }, our_node_secret, current_time, ephemeral_random_data, logger, IgnoringMessageHandler{})
575         }
576 }
577
578 impl<Descriptor: SocketDescriptor, RM: Deref, L: Deref> PeerManager<Descriptor, ErroringMessageHandler, RM, IgnoringMessageHandler, L, IgnoringMessageHandler> where
579                 RM::Target: RoutingMessageHandler,
580                 L::Target: Logger {
581         /// Constructs a new `PeerManager` with the given `RoutingMessageHandler`. No channel message
582         /// handler or onion message handler is used and onion and channel messages will be ignored (or
583         /// generate error messages). Note that some other lightning implementations time-out connections
584         /// after some time if no channel is built with the peer.
585         ///
586         /// `current_time` is used as an always-increasing counter that survives across restarts and is
587         /// incremented irregularly internally. In general it is best to simply use the current UNIX
588         /// timestamp, however if it is not available a persistent counter that increases once per
589         /// minute should suffice.
590         ///
591         /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
592         /// cryptographically secure random bytes.
593         ///
594         /// (C-not exported) as we can't export a PeerManager with a dummy channel handler
595         pub fn new_routing_only(routing_message_handler: RM, our_node_secret: SecretKey, current_time: u64, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
596                 Self::new(MessageHandler {
597                         chan_handler: ErroringMessageHandler::new(),
598                         route_handler: routing_message_handler,
599                         onion_message_handler: IgnoringMessageHandler{},
600                 }, our_node_secret, current_time, ephemeral_random_data, logger, IgnoringMessageHandler{})
601         }
602 }
603
604 /// A simple wrapper that optionally prints " from <pubkey>" for an optional pubkey.
605 /// This works around `format!()` taking a reference to each argument, preventing
606 /// `if let Some(node_id) = peer.their_node_id { format!(.., node_id) } else { .. }` from compiling
607 /// due to lifetime errors.
608 struct OptionalFromDebugger<'a>(&'a Option<PublicKey>);
609 impl core::fmt::Display for OptionalFromDebugger<'_> {
610         fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
611                 if let Some(node_id) = self.0 { write!(f, " from {}", log_pubkey!(node_id)) } else { Ok(()) }
612         }
613 }
614
615 /// A function used to filter out local or private addresses
616 /// https://www.iana.org./assignments/ipv4-address-space/ipv4-address-space.xhtml
617 /// https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml
618 fn filter_addresses(ip_address: Option<NetAddress>) -> Option<NetAddress> {
619         match ip_address{
620                 // For IPv4 range 10.0.0.0 - 10.255.255.255 (10/8)
621                 Some(NetAddress::IPv4{addr: [10, _, _, _], port: _}) => None,
622                 // For IPv4 range 0.0.0.0 - 0.255.255.255 (0/8)
623                 Some(NetAddress::IPv4{addr: [0, _, _, _], port: _}) => None,
624                 // For IPv4 range 100.64.0.0 - 100.127.255.255 (100.64/10)
625                 Some(NetAddress::IPv4{addr: [100, 64..=127, _, _], port: _}) => None,
626                 // For IPv4 range       127.0.0.0 - 127.255.255.255 (127/8)
627                 Some(NetAddress::IPv4{addr: [127, _, _, _], port: _}) => None,
628                 // For IPv4 range       169.254.0.0 - 169.254.255.255 (169.254/16)
629                 Some(NetAddress::IPv4{addr: [169, 254, _, _], port: _}) => None,
630                 // For IPv4 range 172.16.0.0 - 172.31.255.255 (172.16/12)
631                 Some(NetAddress::IPv4{addr: [172, 16..=31, _, _], port: _}) => None,
632                 // For IPv4 range 192.168.0.0 - 192.168.255.255 (192.168/16)
633                 Some(NetAddress::IPv4{addr: [192, 168, _, _], port: _}) => None,
634                 // For IPv4 range 192.88.99.0 - 192.88.99.255  (192.88.99/24)
635                 Some(NetAddress::IPv4{addr: [192, 88, 99, _], port: _}) => None,
636                 // For IPv6 range 2000:0000:0000:0000:0000:0000:0000:0000 - 3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff (2000::/3)
637                 Some(NetAddress::IPv6{addr: [0x20..=0x3F, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _], port: _}) => ip_address,
638                 // For remaining addresses
639                 Some(NetAddress::IPv6{addr: _, port: _}) => None,
640                 Some(..) => ip_address,
641                 None => None,
642         }
643 }
644
645 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CMH: Deref> PeerManager<Descriptor, CM, RM, OM, L, CMH> where
646                 CM::Target: ChannelMessageHandler,
647                 RM::Target: RoutingMessageHandler,
648                 OM::Target: OnionMessageHandler,
649                 L::Target: Logger,
650                 CMH::Target: CustomMessageHandler {
651         /// Constructs a new PeerManager with the given message handlers and node_id secret key
652         /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
653         /// cryptographically secure random bytes.
654         ///
655         /// `current_time` is used as an always-increasing counter that survives across restarts and is
656         /// incremented irregularly internally. In general it is best to simply use the current UNIX
657         /// timestamp, however if it is not available a persistent counter that increases once per
658         /// minute should suffice.
659         pub fn new(message_handler: MessageHandler<CM, RM, OM>, our_node_secret: SecretKey, current_time: u64, ephemeral_random_data: &[u8; 32], logger: L, custom_message_handler: CMH) -> Self {
660                 let mut ephemeral_key_midstate = Sha256::engine();
661                 ephemeral_key_midstate.input(ephemeral_random_data);
662
663                 let mut secp_ctx = Secp256k1::signing_only();
664                 let ephemeral_hash = Sha256::from_engine(ephemeral_key_midstate.clone()).into_inner();
665                 secp_ctx.seeded_randomize(&ephemeral_hash);
666
667                 PeerManager {
668                         message_handler,
669                         peers: FairRwLock::new(HashMap::new()),
670                         node_id_to_descriptor: Mutex::new(HashMap::new()),
671                         event_processing_lock: Mutex::new(()),
672                         blocked_event_processors: AtomicBool::new(false),
673                         our_node_secret,
674                         ephemeral_key_midstate,
675                         peer_counter: AtomicCounter::new(),
676                         last_node_announcement_serial: AtomicU64::new(current_time),
677                         logger,
678                         custom_message_handler,
679                         secp_ctx,
680                 }
681         }
682
683         /// Get the list of node ids for peers which have completed the initial handshake.
684         ///
685         /// For outbound connections, this will be the same as the their_node_id parameter passed in to
686         /// new_outbound_connection, however entries will only appear once the initial handshake has
687         /// completed and we are sure the remote peer has the private key for the given node_id.
688         pub fn get_peer_node_ids(&self) -> Vec<PublicKey> {
689                 let peers = self.peers.read().unwrap();
690                 peers.values().filter_map(|peer_mutex| {
691                         let p = peer_mutex.lock().unwrap();
692                         if !p.channel_encryptor.is_ready_for_encryption() || p.their_features.is_none() {
693                                 return None;
694                         }
695                         p.their_node_id
696                 }).collect()
697         }
698
699         fn get_ephemeral_key(&self) -> SecretKey {
700                 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
701                 let counter = self.peer_counter.get_increment();
702                 ephemeral_hash.input(&counter.to_le_bytes());
703                 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!")
704         }
705
706         /// Indicates a new outbound connection has been established to a node with the given node_id
707         /// and an optional remote network address.
708         ///
709         /// The remote network address adds the option to report a remote IP address back to a connecting
710         /// peer using the init message.
711         /// The user should pass the remote network address of the host they are connected to.
712         ///
713         /// If an `Err` is returned here you must disconnect the connection immediately.
714         ///
715         /// Returns a small number of bytes to send to the remote node (currently always 50).
716         ///
717         /// Panics if descriptor is duplicative with some other descriptor which has not yet been
718         /// [`socket_disconnected()`].
719         ///
720         /// [`socket_disconnected()`]: PeerManager::socket_disconnected
721         pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor, remote_network_address: Option<NetAddress>) -> Result<Vec<u8>, PeerHandleError> {
722                 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
723                 let res = peer_encryptor.get_act_one(&self.secp_ctx).to_vec();
724                 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
725
726                 let mut peers = self.peers.write().unwrap();
727                 if peers.insert(descriptor, Mutex::new(Peer {
728                         channel_encryptor: peer_encryptor,
729                         their_node_id: None,
730                         their_features: None,
731                         their_net_address: remote_network_address,
732
733                         pending_outbound_buffer: LinkedList::new(),
734                         pending_outbound_buffer_first_msg_offset: 0,
735                         gossip_broadcast_buffer: LinkedList::new(),
736                         awaiting_write_event: false,
737
738                         pending_read_buffer,
739                         pending_read_buffer_pos: 0,
740                         pending_read_is_header: false,
741
742                         sync_status: InitSyncTracker::NoSyncRequested,
743
744                         msgs_sent_since_pong: 0,
745                         awaiting_pong_timer_tick_intervals: 0,
746                         received_message_since_timer_tick: false,
747                         sent_gossip_timestamp_filter: false,
748                 })).is_some() {
749                         panic!("PeerManager driver duplicated descriptors!");
750                 };
751                 Ok(res)
752         }
753
754         /// Indicates a new inbound connection has been established to a node with an optional remote
755         /// network address.
756         ///
757         /// The remote network address adds the option to report a remote IP address back to a connecting
758         /// peer using the init message.
759         /// The user should pass the remote network address of the host they are connected to.
760         ///
761         /// May refuse the connection by returning an Err, but will never write bytes to the remote end
762         /// (outbound connector always speaks first). If an `Err` is returned here you must disconnect
763         /// the connection immediately.
764         ///
765         /// Panics if descriptor is duplicative with some other descriptor which has not yet been
766         /// [`socket_disconnected()`].
767         ///
768         /// [`socket_disconnected()`]: PeerManager::socket_disconnected
769         pub fn new_inbound_connection(&self, descriptor: Descriptor, remote_network_address: Option<NetAddress>) -> Result<(), PeerHandleError> {
770                 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret, &self.secp_ctx);
771                 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
772
773                 let mut peers = self.peers.write().unwrap();
774                 if peers.insert(descriptor, Mutex::new(Peer {
775                         channel_encryptor: peer_encryptor,
776                         their_node_id: None,
777                         their_features: None,
778                         their_net_address: remote_network_address,
779
780                         pending_outbound_buffer: LinkedList::new(),
781                         pending_outbound_buffer_first_msg_offset: 0,
782                         gossip_broadcast_buffer: LinkedList::new(),
783                         awaiting_write_event: false,
784
785                         pending_read_buffer,
786                         pending_read_buffer_pos: 0,
787                         pending_read_is_header: false,
788
789                         sync_status: InitSyncTracker::NoSyncRequested,
790
791                         msgs_sent_since_pong: 0,
792                         awaiting_pong_timer_tick_intervals: 0,
793                         received_message_since_timer_tick: false,
794                         sent_gossip_timestamp_filter: false,
795                 })).is_some() {
796                         panic!("PeerManager driver duplicated descriptors!");
797                 };
798                 Ok(())
799         }
800
801         fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer) {
802                 while !peer.awaiting_write_event {
803                         if peer.should_buffer_onion_message() {
804                                 if let Some(peer_node_id) = peer.their_node_id {
805                                         if let Some(next_onion_message) =
806                                                 self.message_handler.onion_message_handler.next_onion_message_for_peer(peer_node_id) {
807                                                         self.enqueue_message(peer, &next_onion_message);
808                                         }
809                                 }
810                         }
811                         if peer.should_buffer_gossip_broadcast() {
812                                 if let Some(msg) = peer.gossip_broadcast_buffer.pop_front() {
813                                         peer.pending_outbound_buffer.push_back(msg);
814                                 }
815                         }
816                         if peer.should_buffer_gossip_backfill() {
817                                 match peer.sync_status {
818                                         InitSyncTracker::NoSyncRequested => {},
819                                         InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
820                                                 if let Some((announce, update_a_option, update_b_option)) =
821                                                         self.message_handler.route_handler.get_next_channel_announcement(c)
822                                                 {
823                                                         self.enqueue_message(peer, &announce);
824                                                         if let Some(update_a) = update_a_option {
825                                                                 self.enqueue_message(peer, &update_a);
826                                                         }
827                                                         if let Some(update_b) = update_b_option {
828                                                                 self.enqueue_message(peer, &update_b);
829                                                         }
830                                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
831                                                 } else {
832                                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
833                                                 }
834                                         },
835                                         InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
836                                                 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(None) {
837                                                         self.enqueue_message(peer, &msg);
838                                                         peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
839                                                 } else {
840                                                         peer.sync_status = InitSyncTracker::NoSyncRequested;
841                                                 }
842                                         },
843                                         InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
844                                         InitSyncTracker::NodesSyncing(key) => {
845                                                 if let Some(msg) = self.message_handler.route_handler.get_next_node_announcement(Some(&key)) {
846                                                         self.enqueue_message(peer, &msg);
847                                                         peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
848                                                 } else {
849                                                         peer.sync_status = InitSyncTracker::NoSyncRequested;
850                                                 }
851                                         },
852                                 }
853                         }
854                         if peer.msgs_sent_since_pong >= BUFFER_DRAIN_MSGS_PER_TICK {
855                                 self.maybe_send_extra_ping(peer);
856                         }
857
858                         let next_buff = match peer.pending_outbound_buffer.front() {
859                                 None => return,
860                                 Some(buff) => buff,
861                         };
862
863                         let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
864                         let data_sent = descriptor.send_data(pending, peer.should_read());
865                         peer.pending_outbound_buffer_first_msg_offset += data_sent;
866                         if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() {
867                                 peer.pending_outbound_buffer_first_msg_offset = 0;
868                                 peer.pending_outbound_buffer.pop_front();
869                         } else {
870                                 peer.awaiting_write_event = true;
871                         }
872                 }
873         }
874
875         /// Indicates that there is room to write data to the given socket descriptor.
876         ///
877         /// May return an Err to indicate that the connection should be closed.
878         ///
879         /// May call [`send_data`] on the descriptor passed in (or an equal descriptor) before
880         /// returning. Thus, be very careful with reentrancy issues! The invariants around calling
881         /// [`write_buffer_space_avail`] in case a write did not fully complete must still hold - be
882         /// ready to call `[write_buffer_space_avail`] again if a write call generated here isn't
883         /// sufficient!
884         ///
885         /// [`send_data`]: SocketDescriptor::send_data
886         /// [`write_buffer_space_avail`]: PeerManager::write_buffer_space_avail
887         pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
888                 let peers = self.peers.read().unwrap();
889                 match peers.get(descriptor) {
890                         None => {
891                                 // This is most likely a simple race condition where the user found that the socket
892                                 // was writeable, then we told the user to `disconnect_socket()`, then they called
893                                 // this method. Return an error to make sure we get disconnected.
894                                 return Err(PeerHandleError { no_connection_possible: false });
895                         },
896                         Some(peer_mutex) => {
897                                 let mut peer = peer_mutex.lock().unwrap();
898                                 peer.awaiting_write_event = false;
899                                 self.do_attempt_write_data(descriptor, &mut peer);
900                         }
901                 };
902                 Ok(())
903         }
904
905         /// Indicates that data was read from the given socket descriptor.
906         ///
907         /// May return an Err to indicate that the connection should be closed.
908         ///
909         /// Will *not* call back into [`send_data`] on any descriptors to avoid reentrancy complexity.
910         /// Thus, however, you should call [`process_events`] after any `read_event` to generate
911         /// [`send_data`] calls to handle responses.
912         ///
913         /// If `Ok(true)` is returned, further read_events should not be triggered until a
914         /// [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the
915         /// send buffer).
916         ///
917         /// [`send_data`]: SocketDescriptor::send_data
918         /// [`process_events`]: PeerManager::process_events
919         pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
920                 match self.do_read_event(peer_descriptor, data) {
921                         Ok(res) => Ok(res),
922                         Err(e) => {
923                                 log_trace!(self.logger, "Peer sent invalid data or we decided to disconnect due to a protocol error");
924                                 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
925                                 Err(e)
926                         }
927                 }
928         }
929
930         /// Append a message to a peer's pending outbound/write buffer
931         fn enqueue_message<M: wire::Type>(&self, peer: &mut Peer, message: &M) {
932                 let mut buffer = VecWriter(Vec::with_capacity(2048));
933                 wire::write(message, &mut buffer).unwrap(); // crash if the write failed
934
935                 if is_gossip_msg(message.type_id()) {
936                         log_gossip!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap()));
937                 } else {
938                         log_trace!(self.logger, "Enqueueing message {:?} to {}", message, log_pubkey!(peer.their_node_id.unwrap()))
939                 }
940                 peer.msgs_sent_since_pong += 1;
941                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&buffer.0[..]));
942         }
943
944         /// Append a message to a peer's pending outbound/write gossip broadcast buffer
945         fn enqueue_encoded_gossip_broadcast(&self, peer: &mut Peer, encoded_message: &Vec<u8>) {
946                 peer.msgs_sent_since_pong += 1;
947                 peer.gossip_broadcast_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_message[..]));
948         }
949
950         fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
951                 let mut pause_read = false;
952                 let peers = self.peers.read().unwrap();
953                 let mut msgs_to_forward = Vec::new();
954                 let mut peer_node_id = None;
955                 match peers.get(peer_descriptor) {
956                         None => {
957                                 // This is most likely a simple race condition where the user read some bytes
958                                 // from the socket, then we told the user to `disconnect_socket()`, then they
959                                 // called this method. Return an error to make sure we get disconnected.
960                                 return Err(PeerHandleError { no_connection_possible: false });
961                         },
962                         Some(peer_mutex) => {
963                                 let mut read_pos = 0;
964                                 while read_pos < data.len() {
965                                         macro_rules! try_potential_handleerror {
966                                                 ($peer: expr, $thing: expr) => {
967                                                         match $thing {
968                                                                 Ok(x) => x,
969                                                                 Err(e) => {
970                                                                         match e.action {
971                                                                                 msgs::ErrorAction::DisconnectPeer { msg: _ } => {
972                                                                                         //TODO: Try to push msg
973                                                                                         log_debug!(self.logger, "Error handling message{}; disconnecting peer with: {}", OptionalFromDebugger(&peer_node_id), e.err);
974                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
975                                                                                 },
976                                                                                 msgs::ErrorAction::IgnoreAndLog(level) => {
977                                                                                         log_given_level!(self.logger, level, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
978                                                                                         continue
979                                                                                 },
980                                                                                 msgs::ErrorAction::IgnoreDuplicateGossip => continue, // Don't even bother logging these
981                                                                                 msgs::ErrorAction::IgnoreError => {
982                                                                                         log_debug!(self.logger, "Error handling message{}; ignoring: {}", OptionalFromDebugger(&peer_node_id), e.err);
983                                                                                         continue;
984                                                                                 },
985                                                                                 msgs::ErrorAction::SendErrorMessage { msg } => {
986                                                                                         log_debug!(self.logger, "Error handling message{}; sending error message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
987                                                                                         self.enqueue_message($peer, &msg);
988                                                                                         continue;
989                                                                                 },
990                                                                                 msgs::ErrorAction::SendWarningMessage { msg, log_level } => {
991                                                                                         log_given_level!(self.logger, log_level, "Error handling message{}; sending warning message with: {}", OptionalFromDebugger(&peer_node_id), e.err);
992                                                                                         self.enqueue_message($peer, &msg);
993                                                                                         continue;
994                                                                                 },
995                                                                         }
996                                                                 }
997                                                         }
998                                                 }
999                                         }
1000
1001                                         let mut peer_lock = peer_mutex.lock().unwrap();
1002                                         let peer = &mut *peer_lock;
1003                                         let mut msg_to_handle = None;
1004                                         if peer_node_id.is_none() {
1005                                                 peer_node_id = peer.their_node_id.clone();
1006                                         }
1007
1008                                         assert!(peer.pending_read_buffer.len() > 0);
1009                                         assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
1010
1011                                         {
1012                                                 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
1013                                                 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]);
1014                                                 read_pos += data_to_copy;
1015                                                 peer.pending_read_buffer_pos += data_to_copy;
1016                                         }
1017
1018                                         if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
1019                                                 peer.pending_read_buffer_pos = 0;
1020
1021                                                 macro_rules! insert_node_id {
1022                                                         () => {
1023                                                                 match self.node_id_to_descriptor.lock().unwrap().entry(peer.their_node_id.unwrap()) {
1024                                                                         hash_map::Entry::Occupied(_) => {
1025                                                                                 log_trace!(self.logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap()));
1026                                                                                 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
1027                                                                                 return Err(PeerHandleError{ no_connection_possible: false })
1028                                                                         },
1029                                                                         hash_map::Entry::Vacant(entry) => {
1030                                                                                 log_debug!(self.logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap()));
1031                                                                                 entry.insert(peer_descriptor.clone())
1032                                                                         },
1033                                                                 };
1034                                                         }
1035                                                 }
1036
1037                                                 let next_step = peer.channel_encryptor.get_noise_step();
1038                                                 match next_step {
1039                                                         NextNoiseStep::ActOne => {
1040                                                                 let act_two = try_potential_handleerror!(peer, peer.channel_encryptor
1041                                                                         .process_act_one_with_keys(&peer.pending_read_buffer[..],
1042                                                                                 &self.our_node_secret, self.get_ephemeral_key(), &self.secp_ctx)).to_vec();
1043                                                                 peer.pending_outbound_buffer.push_back(act_two);
1044                                                                 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
1045                                                         },
1046                                                         NextNoiseStep::ActTwo => {
1047                                                                 let (act_three, their_node_id) = try_potential_handleerror!(peer,
1048                                                                         peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..],
1049                                                                                 &self.our_node_secret, &self.secp_ctx));
1050                                                                 peer.pending_outbound_buffer.push_back(act_three.to_vec());
1051                                                                 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1052                                                                 peer.pending_read_is_header = true;
1053
1054                                                                 peer.their_node_id = Some(their_node_id);
1055                                                                 insert_node_id!();
1056                                                                 let features = self.message_handler.chan_handler.provided_init_features(&their_node_id);
1057                                                                 let resp = msgs::Init { features, remote_network_address: filter_addresses(peer.their_net_address.clone()) };
1058                                                                 self.enqueue_message(peer, &resp);
1059                                                                 peer.awaiting_pong_timer_tick_intervals = 0;
1060                                                         },
1061                                                         NextNoiseStep::ActThree => {
1062                                                                 let their_node_id = try_potential_handleerror!(peer,
1063                                                                         peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
1064                                                                 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
1065                                                                 peer.pending_read_is_header = true;
1066                                                                 peer.their_node_id = Some(their_node_id);
1067                                                                 insert_node_id!();
1068                                                                 let features = self.message_handler.chan_handler.provided_init_features(&their_node_id);
1069                                                                 let resp = msgs::Init { features, remote_network_address: filter_addresses(peer.their_net_address.clone()) };
1070                                                                 self.enqueue_message(peer, &resp);
1071                                                                 peer.awaiting_pong_timer_tick_intervals = 0;
1072                                                         },
1073                                                         NextNoiseStep::NoiseComplete => {
1074                                                                 if peer.pending_read_is_header {
1075                                                                         let msg_len = try_potential_handleerror!(peer,
1076                                                                                 peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
1077                                                                         if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1078                                                                         peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
1079                                                                         if msg_len < 2 { // Need at least the message type tag
1080                                                                                 return Err(PeerHandleError{ no_connection_possible: false });
1081                                                                         }
1082                                                                         peer.pending_read_is_header = false;
1083                                                                 } else {
1084                                                                         let msg_data = try_potential_handleerror!(peer,
1085                                                                                 peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
1086                                                                         assert!(msg_data.len() >= 2);
1087
1088                                                                         // Reset read buffer
1089                                                                         if peer.pending_read_buffer.capacity() > 8192 { peer.pending_read_buffer = Vec::new(); }
1090                                                                         peer.pending_read_buffer.resize(18, 0);
1091                                                                         peer.pending_read_is_header = true;
1092
1093                                                                         let mut reader = io::Cursor::new(&msg_data[..]);
1094                                                                         let message_result = wire::read(&mut reader, &*self.custom_message_handler);
1095                                                                         let message = match message_result {
1096                                                                                 Ok(x) => x,
1097                                                                                 Err(e) => {
1098                                                                                         match e {
1099                                                                                                 // Note that to avoid recursion we never call
1100                                                                                                 // `do_attempt_write_data` from here, causing
1101                                                                                                 // the messages enqueued here to not actually
1102                                                                                                 // be sent before the peer is disconnected.
1103                                                                                                 (msgs::DecodeError::UnknownRequiredFeature, Some(ty)) if is_gossip_msg(ty) => {
1104                                                                                                         log_gossip!(self.logger, "Got a channel/node announcement with an unknown required feature flag, you may want to update!");
1105                                                                                                         continue;
1106                                                                                                 }
1107                                                                                                 (msgs::DecodeError::UnsupportedCompression, _) => {
1108                                                                                                         log_gossip!(self.logger, "We don't support zlib-compressed message fields, sending a warning and ignoring message");
1109                                                                                                         self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: "Unsupported message compression: zlib".to_owned() });
1110                                                                                                         continue;
1111                                                                                                 }
1112                                                                                                 (_, Some(ty)) if is_gossip_msg(ty) => {
1113                                                                                                         log_gossip!(self.logger, "Got an invalid value while deserializing a gossip message");
1114                                                                                                         self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: "Unreadable/bogus gossip message".to_owned() });
1115                                                                                                         continue;
1116                                                                                                 }
1117                                                                                                 (msgs::DecodeError::UnknownRequiredFeature, ty) => {
1118                                                                                                         log_gossip!(self.logger, "Received a message with an unknown required feature flag or TLV, you may want to update!");
1119                                                                                                         self.enqueue_message(peer, &msgs::WarningMessage { channel_id: [0; 32], data: format!("Received an unknown required feature/TLV in message type {:?}", ty) });
1120                                                                                                         return Err(PeerHandleError { no_connection_possible: false });
1121                                                                                                 }
1122                                                                                                 (msgs::DecodeError::UnknownVersion, _) => return Err(PeerHandleError { no_connection_possible: false }),
1123                                                                                                 (msgs::DecodeError::InvalidValue, _) => {
1124                                                                                                         log_debug!(self.logger, "Got an invalid value while deserializing message");
1125                                                                                                         return Err(PeerHandleError { no_connection_possible: false });
1126                                                                                                 }
1127                                                                                                 (msgs::DecodeError::ShortRead, _) => {
1128                                                                                                         log_debug!(self.logger, "Deserialization failed due to shortness of message");
1129                                                                                                         return Err(PeerHandleError { no_connection_possible: false });
1130                                                                                                 }
1131                                                                                                 (msgs::DecodeError::BadLengthDescriptor, _) => return Err(PeerHandleError { no_connection_possible: false }),
1132                                                                                                 (msgs::DecodeError::Io(_), _) => return Err(PeerHandleError { no_connection_possible: false }),
1133                                                                                         }
1134                                                                                 }
1135                                                                         };
1136
1137                                                                         msg_to_handle = Some(message);
1138                                                                 }
1139                                                         }
1140                                                 }
1141                                         }
1142                                         pause_read = !peer.should_read();
1143
1144                                         if let Some(message) = msg_to_handle {
1145                                                 match self.handle_message(&peer_mutex, peer_lock, message) {
1146                                                         Err(handling_error) => match handling_error {
1147                                                                 MessageHandlingError::PeerHandleError(e) => { return Err(e) },
1148                                                                 MessageHandlingError::LightningError(e) => {
1149                                                                         try_potential_handleerror!(&mut peer_mutex.lock().unwrap(), Err(e));
1150                                                                 },
1151                                                         },
1152                                                         Ok(Some(msg)) => {
1153                                                                 msgs_to_forward.push(msg);
1154                                                         },
1155                                                         Ok(None) => {},
1156                                                 }
1157                                         }
1158                                 }
1159                         }
1160                 }
1161
1162                 for msg in msgs_to_forward.drain(..) {
1163                         self.forward_broadcast_msg(&*peers, &msg, peer_node_id.as_ref());
1164                 }
1165
1166                 Ok(pause_read)
1167         }
1168
1169         /// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer
1170         /// Returns the message back if it needs to be broadcasted to all other peers.
1171         fn handle_message(
1172                 &self,
1173                 peer_mutex: &Mutex<Peer>,
1174                 mut peer_lock: MutexGuard<Peer>,
1175                 message: wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>
1176         ) -> Result<Option<wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>>, MessageHandlingError> {
1177                 let their_node_id = peer_lock.their_node_id.clone().expect("We know the peer's public key by the time we receive messages");
1178                 peer_lock.received_message_since_timer_tick = true;
1179
1180                 // Need an Init as first message
1181                 if let wire::Message::Init(msg) = message {
1182                         if msg.features.requires_unknown_bits() {
1183                                 log_debug!(self.logger, "Peer features required unknown version bits");
1184                                 return Err(PeerHandleError{ no_connection_possible: true }.into());
1185                         }
1186                         if peer_lock.their_features.is_some() {
1187                                 return Err(PeerHandleError{ no_connection_possible: false }.into());
1188                         }
1189
1190                         log_info!(self.logger, "Received peer Init message from {}: {}", log_pubkey!(their_node_id), msg.features);
1191
1192                         // For peers not supporting gossip queries start sync now, otherwise wait until we receive a filter.
1193                         if msg.features.initial_routing_sync() && !msg.features.supports_gossip_queries() {
1194                                 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1195                         }
1196
1197                         if !msg.features.supports_static_remote_key() {
1198                                 log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting with no_connection_possible", log_pubkey!(their_node_id));
1199                                 return Err(PeerHandleError{ no_connection_possible: true }.into());
1200                         }
1201
1202                         self.message_handler.route_handler.peer_connected(&their_node_id, &msg);
1203                         self.message_handler.chan_handler.peer_connected(&their_node_id, &msg);
1204                         self.message_handler.onion_message_handler.peer_connected(&their_node_id, &msg);
1205
1206                         peer_lock.their_features = Some(msg.features);
1207                         return Ok(None);
1208                 } else if peer_lock.their_features.is_none() {
1209                         log_debug!(self.logger, "Peer {} sent non-Init first message", log_pubkey!(their_node_id));
1210                         return Err(PeerHandleError{ no_connection_possible: false }.into());
1211                 }
1212
1213                 if let wire::Message::GossipTimestampFilter(_msg) = message {
1214                         // When supporting gossip messages, start inital gossip sync only after we receive
1215                         // a GossipTimestampFilter
1216                         if peer_lock.their_features.as_ref().unwrap().supports_gossip_queries() &&
1217                                 !peer_lock.sent_gossip_timestamp_filter {
1218                                 peer_lock.sent_gossip_timestamp_filter = true;
1219                                 peer_lock.sync_status = InitSyncTracker::ChannelsSyncing(0);
1220                         }
1221                         return Ok(None);
1222                 }
1223
1224                 let their_features = peer_lock.their_features.clone();
1225                 mem::drop(peer_lock);
1226
1227                 if is_gossip_msg(message.type_id()) {
1228                         log_gossip!(self.logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1229                 } else {
1230                         log_trace!(self.logger, "Received message {:?} from {}", message, log_pubkey!(their_node_id));
1231                 }
1232
1233                 let mut should_forward = None;
1234
1235                 match message {
1236                         // Setup and Control messages:
1237                         wire::Message::Init(_) => {
1238                                 // Handled above
1239                         },
1240                         wire::Message::GossipTimestampFilter(_) => {
1241                                 // Handled above
1242                         },
1243                         wire::Message::Error(msg) => {
1244                                 let mut data_is_printable = true;
1245                                 for b in msg.data.bytes() {
1246                                         if b < 32 || b > 126 {
1247                                                 data_is_printable = false;
1248                                                 break;
1249                                         }
1250                                 }
1251
1252                                 if data_is_printable {
1253                                         log_debug!(self.logger, "Got Err message from {}: {}", log_pubkey!(their_node_id), msg.data);
1254                                 } else {
1255                                         log_debug!(self.logger, "Got Err message from {} with non-ASCII error message", log_pubkey!(their_node_id));
1256                                 }
1257                                 self.message_handler.chan_handler.handle_error(&their_node_id, &msg);
1258                                 if msg.channel_id == [0; 32] {
1259                                         return Err(PeerHandleError{ no_connection_possible: true }.into());
1260                                 }
1261                         },
1262                         wire::Message::Warning(msg) => {
1263                                 let mut data_is_printable = true;
1264                                 for b in msg.data.bytes() {
1265                                         if b < 32 || b > 126 {
1266                                                 data_is_printable = false;
1267                                                 break;
1268                                         }
1269                                 }
1270
1271                                 if data_is_printable {
1272                                         log_debug!(self.logger, "Got warning message from {}: {}", log_pubkey!(their_node_id), msg.data);
1273                                 } else {
1274                                         log_debug!(self.logger, "Got warning message from {} with non-ASCII error message", log_pubkey!(their_node_id));
1275                                 }
1276                         },
1277
1278                         wire::Message::Ping(msg) => {
1279                                 if msg.ponglen < 65532 {
1280                                         let resp = msgs::Pong { byteslen: msg.ponglen };
1281                                         self.enqueue_message(&mut *peer_mutex.lock().unwrap(), &resp);
1282                                 }
1283                         },
1284                         wire::Message::Pong(_msg) => {
1285                                 let mut peer_lock = peer_mutex.lock().unwrap();
1286                                 peer_lock.awaiting_pong_timer_tick_intervals = 0;
1287                                 peer_lock.msgs_sent_since_pong = 0;
1288                         },
1289
1290                         // Channel messages:
1291                         wire::Message::OpenChannel(msg) => {
1292                                 self.message_handler.chan_handler.handle_open_channel(&their_node_id, their_features.clone().unwrap(), &msg);
1293                         },
1294                         wire::Message::AcceptChannel(msg) => {
1295                                 self.message_handler.chan_handler.handle_accept_channel(&their_node_id, their_features.clone().unwrap(), &msg);
1296                         },
1297
1298                         wire::Message::FundingCreated(msg) => {
1299                                 self.message_handler.chan_handler.handle_funding_created(&their_node_id, &msg);
1300                         },
1301                         wire::Message::FundingSigned(msg) => {
1302                                 self.message_handler.chan_handler.handle_funding_signed(&their_node_id, &msg);
1303                         },
1304                         wire::Message::ChannelReady(msg) => {
1305                                 self.message_handler.chan_handler.handle_channel_ready(&their_node_id, &msg);
1306                         },
1307
1308                         wire::Message::Shutdown(msg) => {
1309                                 self.message_handler.chan_handler.handle_shutdown(&their_node_id, their_features.as_ref().unwrap(), &msg);
1310                         },
1311                         wire::Message::ClosingSigned(msg) => {
1312                                 self.message_handler.chan_handler.handle_closing_signed(&their_node_id, &msg);
1313                         },
1314
1315                         // Commitment messages:
1316                         wire::Message::UpdateAddHTLC(msg) => {
1317                                 self.message_handler.chan_handler.handle_update_add_htlc(&their_node_id, &msg);
1318                         },
1319                         wire::Message::UpdateFulfillHTLC(msg) => {
1320                                 self.message_handler.chan_handler.handle_update_fulfill_htlc(&their_node_id, &msg);
1321                         },
1322                         wire::Message::UpdateFailHTLC(msg) => {
1323                                 self.message_handler.chan_handler.handle_update_fail_htlc(&their_node_id, &msg);
1324                         },
1325                         wire::Message::UpdateFailMalformedHTLC(msg) => {
1326                                 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&their_node_id, &msg);
1327                         },
1328
1329                         wire::Message::CommitmentSigned(msg) => {
1330                                 self.message_handler.chan_handler.handle_commitment_signed(&their_node_id, &msg);
1331                         },
1332                         wire::Message::RevokeAndACK(msg) => {
1333                                 self.message_handler.chan_handler.handle_revoke_and_ack(&their_node_id, &msg);
1334                         },
1335                         wire::Message::UpdateFee(msg) => {
1336                                 self.message_handler.chan_handler.handle_update_fee(&their_node_id, &msg);
1337                         },
1338                         wire::Message::ChannelReestablish(msg) => {
1339                                 self.message_handler.chan_handler.handle_channel_reestablish(&their_node_id, &msg);
1340                         },
1341
1342                         // Routing messages:
1343                         wire::Message::AnnouncementSignatures(msg) => {
1344                                 self.message_handler.chan_handler.handle_announcement_signatures(&their_node_id, &msg);
1345                         },
1346                         wire::Message::ChannelAnnouncement(msg) => {
1347                                 if self.message_handler.route_handler.handle_channel_announcement(&msg)
1348                                                 .map_err(|e| -> MessageHandlingError { e.into() })? {
1349                                         should_forward = Some(wire::Message::ChannelAnnouncement(msg));
1350                                 }
1351                         },
1352                         wire::Message::NodeAnnouncement(msg) => {
1353                                 if self.message_handler.route_handler.handle_node_announcement(&msg)
1354                                                 .map_err(|e| -> MessageHandlingError { e.into() })? {
1355                                         should_forward = Some(wire::Message::NodeAnnouncement(msg));
1356                                 }
1357                         },
1358                         wire::Message::ChannelUpdate(msg) => {
1359                                 self.message_handler.chan_handler.handle_channel_update(&their_node_id, &msg);
1360                                 if self.message_handler.route_handler.handle_channel_update(&msg)
1361                                                 .map_err(|e| -> MessageHandlingError { e.into() })? {
1362                                         should_forward = Some(wire::Message::ChannelUpdate(msg));
1363                                 }
1364                         },
1365                         wire::Message::QueryShortChannelIds(msg) => {
1366                                 self.message_handler.route_handler.handle_query_short_channel_ids(&their_node_id, msg)?;
1367                         },
1368                         wire::Message::ReplyShortChannelIdsEnd(msg) => {
1369                                 self.message_handler.route_handler.handle_reply_short_channel_ids_end(&their_node_id, msg)?;
1370                         },
1371                         wire::Message::QueryChannelRange(msg) => {
1372                                 self.message_handler.route_handler.handle_query_channel_range(&their_node_id, msg)?;
1373                         },
1374                         wire::Message::ReplyChannelRange(msg) => {
1375                                 self.message_handler.route_handler.handle_reply_channel_range(&their_node_id, msg)?;
1376                         },
1377
1378                         // Onion message:
1379                         wire::Message::OnionMessage(msg) => {
1380                                 self.message_handler.onion_message_handler.handle_onion_message(&their_node_id, &msg);
1381                         },
1382
1383                         // Unknown messages:
1384                         wire::Message::Unknown(type_id) if message.is_even() => {
1385                                 log_debug!(self.logger, "Received unknown even message of type {}, disconnecting peer!", type_id);
1386                                 // Fail the channel if message is an even, unknown type as per BOLT #1.
1387                                 return Err(PeerHandleError{ no_connection_possible: true }.into());
1388                         },
1389                         wire::Message::Unknown(type_id) => {
1390                                 log_trace!(self.logger, "Received unknown odd message of type {}, ignoring", type_id);
1391                         },
1392                         wire::Message::Custom(custom) => {
1393                                 self.custom_message_handler.handle_custom_message(custom, &their_node_id)?;
1394                         },
1395                 };
1396                 Ok(should_forward)
1397         }
1398
1399         fn forward_broadcast_msg(&self, peers: &HashMap<Descriptor, Mutex<Peer>>, msg: &wire::Message<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>, except_node: Option<&PublicKey>) {
1400                 match msg {
1401                         wire::Message::ChannelAnnouncement(ref msg) => {
1402                                 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced channel's counterparties: {:?}", except_node, msg);
1403                                 let encoded_msg = encode_msg!(msg);
1404
1405                                 for (_, peer_mutex) in peers.iter() {
1406                                         let mut peer = peer_mutex.lock().unwrap();
1407                                         if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1408                                                         !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1409                                                 continue
1410                                         }
1411                                         if peer.buffer_full_drop_gossip_broadcast() {
1412                                                 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1413                                                 continue;
1414                                         }
1415                                         if peer.their_node_id.as_ref() == Some(&msg.contents.node_id_1) ||
1416                                            peer.their_node_id.as_ref() == Some(&msg.contents.node_id_2) {
1417                                                 continue;
1418                                         }
1419                                         if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1420                                                 continue;
1421                                         }
1422                                         self.enqueue_encoded_gossip_broadcast(&mut *peer, &encoded_msg);
1423                                 }
1424                         },
1425                         wire::Message::NodeAnnouncement(ref msg) => {
1426                                 log_gossip!(self.logger, "Sending message to all peers except {:?} or the announced node: {:?}", except_node, msg);
1427                                 let encoded_msg = encode_msg!(msg);
1428
1429                                 for (_, peer_mutex) in peers.iter() {
1430                                         let mut peer = peer_mutex.lock().unwrap();
1431                                         if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1432                                                         !peer.should_forward_node_announcement(msg.contents.node_id) {
1433                                                 continue
1434                                         }
1435                                         if peer.buffer_full_drop_gossip_broadcast() {
1436                                                 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1437                                                 continue;
1438                                         }
1439                                         if peer.their_node_id.as_ref() == Some(&msg.contents.node_id) {
1440                                                 continue;
1441                                         }
1442                                         if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1443                                                 continue;
1444                                         }
1445                                         self.enqueue_encoded_gossip_broadcast(&mut *peer, &encoded_msg);
1446                                 }
1447                         },
1448                         wire::Message::ChannelUpdate(ref msg) => {
1449                                 log_gossip!(self.logger, "Sending message to all peers except {:?}: {:?}", except_node, msg);
1450                                 let encoded_msg = encode_msg!(msg);
1451
1452                                 for (_, peer_mutex) in peers.iter() {
1453                                         let mut peer = peer_mutex.lock().unwrap();
1454                                         if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1455                                                         !peer.should_forward_channel_announcement(msg.contents.short_channel_id)  {
1456                                                 continue
1457                                         }
1458                                         if peer.buffer_full_drop_gossip_broadcast() {
1459                                                 log_gossip!(self.logger, "Skipping broadcast message to {:?} as its outbound buffer is full", peer.their_node_id);
1460                                                 continue;
1461                                         }
1462                                         if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1463                                                 continue;
1464                                         }
1465                                         self.enqueue_encoded_gossip_broadcast(&mut *peer, &encoded_msg);
1466                                 }
1467                         },
1468                         _ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),
1469                 }
1470         }
1471
1472         /// Checks for any events generated by our handlers and processes them. Includes sending most
1473         /// response messages as well as messages generated by calls to handler functions directly (eg
1474         /// functions like [`ChannelManager::process_pending_htlc_forwards`] or [`send_payment`]).
1475         ///
1476         /// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1477         /// issues!
1478         ///
1479         /// You don't have to call this function explicitly if you are using [`lightning-net-tokio`]
1480         /// or one of the other clients provided in our language bindings.
1481         ///
1482         /// Note that if there are any other calls to this function waiting on lock(s) this may return
1483         /// without doing any work. All available events that need handling will be handled before the
1484         /// other calls return.
1485         ///
1486         /// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1487         /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
1488         /// [`send_data`]: SocketDescriptor::send_data
1489         pub fn process_events(&self) {
1490                 let mut _single_processor_lock = self.event_processing_lock.try_lock();
1491                 if _single_processor_lock.is_err() {
1492                         // While we could wake the older sleeper here with a CV and make more even waiting
1493                         // times, that would be a lot of overengineering for a simple "reduce total waiter
1494                         // count" goal.
1495                         match self.blocked_event_processors.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) {
1496                                 Err(val) => {
1497                                         debug_assert!(val, "compare_exchange failed spuriously?");
1498                                         return;
1499                                 },
1500                                 Ok(val) => {
1501                                         debug_assert!(!val, "compare_exchange succeeded spuriously?");
1502                                         // We're the only waiter, as the running process_events may have emptied the
1503                                         // pending events "long" ago and there are new events for us to process, wait until
1504                                         // its done and process any leftover events before returning.
1505                                         _single_processor_lock = Ok(self.event_processing_lock.lock().unwrap());
1506                                         self.blocked_event_processors.store(false, Ordering::Release);
1507                                 }
1508                         }
1509                 }
1510
1511                 let mut peers_to_disconnect = HashMap::new();
1512                 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
1513                 events_generated.append(&mut self.message_handler.route_handler.get_and_clear_pending_msg_events());
1514
1515                 {
1516                         // TODO: There are some DoS attacks here where you can flood someone's outbound send
1517                         // buffer by doing things like announcing channels on another node. We should be willing to
1518                         // drop optional-ish messages when send buffers get full!
1519
1520                         let peers_lock = self.peers.read().unwrap();
1521                         let peers = &*peers_lock;
1522                         macro_rules! get_peer_for_forwarding {
1523                                 ($node_id: expr) => {
1524                                         {
1525                                                 if peers_to_disconnect.get($node_id).is_some() {
1526                                                         // If we've "disconnected" this peer, do not send to it.
1527                                                         continue;
1528                                                 }
1529                                                 let descriptor_opt = self.node_id_to_descriptor.lock().unwrap().get($node_id).cloned();
1530                                                 match descriptor_opt {
1531                                                         Some(descriptor) => match peers.get(&descriptor) {
1532                                                                 Some(peer_mutex) => {
1533                                                                         let peer_lock = peer_mutex.lock().unwrap();
1534                                                                         if peer_lock.their_features.is_none() {
1535                                                                                 continue;
1536                                                                         }
1537                                                                         peer_lock
1538                                                                 },
1539                                                                 None => {
1540                                                                         debug_assert!(false, "Inconsistent peers set state!");
1541                                                                         continue;
1542                                                                 }
1543                                                         },
1544                                                         None => {
1545                                                                 continue;
1546                                                         },
1547                                                 }
1548                                         }
1549                                 }
1550                         }
1551                         for event in events_generated.drain(..) {
1552                                 match event {
1553                                         MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
1554                                                 log_debug!(self.logger, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
1555                                                                 log_pubkey!(node_id),
1556                                                                 log_bytes!(msg.temporary_channel_id));
1557                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1558                                         },
1559                                         MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
1560                                                 log_debug!(self.logger, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
1561                                                                 log_pubkey!(node_id),
1562                                                                 log_bytes!(msg.temporary_channel_id));
1563                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1564                                         },
1565                                         MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
1566                                                 log_debug!(self.logger, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
1567                                                                 log_pubkey!(node_id),
1568                                                                 log_bytes!(msg.temporary_channel_id),
1569                                                                 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
1570                                                 // TODO: If the peer is gone we should generate a DiscardFunding event
1571                                                 // indicating to the wallet that they should just throw away this funding transaction
1572                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1573                                         },
1574                                         MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
1575                                                 log_debug!(self.logger, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
1576                                                                 log_pubkey!(node_id),
1577                                                                 log_bytes!(msg.channel_id));
1578                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1579                                         },
1580                                         MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
1581                                                 log_debug!(self.logger, "Handling SendChannelReady event in peer_handler for node {} for channel {}",
1582                                                                 log_pubkey!(node_id),
1583                                                                 log_bytes!(msg.channel_id));
1584                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1585                                         },
1586                                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
1587                                                 log_debug!(self.logger, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
1588                                                                 log_pubkey!(node_id),
1589                                                                 log_bytes!(msg.channel_id));
1590                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1591                                         },
1592                                         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 } } => {
1593                                                 log_debug!(self.logger, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
1594                                                                 log_pubkey!(node_id),
1595                                                                 update_add_htlcs.len(),
1596                                                                 update_fulfill_htlcs.len(),
1597                                                                 update_fail_htlcs.len(),
1598                                                                 log_bytes!(commitment_signed.channel_id));
1599                                                 let mut peer = get_peer_for_forwarding!(node_id);
1600                                                 for msg in update_add_htlcs {
1601                                                         self.enqueue_message(&mut *peer, msg);
1602                                                 }
1603                                                 for msg in update_fulfill_htlcs {
1604                                                         self.enqueue_message(&mut *peer, msg);
1605                                                 }
1606                                                 for msg in update_fail_htlcs {
1607                                                         self.enqueue_message(&mut *peer, msg);
1608                                                 }
1609                                                 for msg in update_fail_malformed_htlcs {
1610                                                         self.enqueue_message(&mut *peer, msg);
1611                                                 }
1612                                                 if let &Some(ref msg) = update_fee {
1613                                                         self.enqueue_message(&mut *peer, msg);
1614                                                 }
1615                                                 self.enqueue_message(&mut *peer, commitment_signed);
1616                                         },
1617                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1618                                                 log_debug!(self.logger, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
1619                                                                 log_pubkey!(node_id),
1620                                                                 log_bytes!(msg.channel_id));
1621                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1622                                         },
1623                                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1624                                                 log_debug!(self.logger, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
1625                                                                 log_pubkey!(node_id),
1626                                                                 log_bytes!(msg.channel_id));
1627                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1628                                         },
1629                                         MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
1630                                                 log_debug!(self.logger, "Handling Shutdown event in peer_handler for node {} for channel {}",
1631                                                                 log_pubkey!(node_id),
1632                                                                 log_bytes!(msg.channel_id));
1633                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1634                                         },
1635                                         MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
1636                                                 log_debug!(self.logger, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
1637                                                                 log_pubkey!(node_id),
1638                                                                 log_bytes!(msg.channel_id));
1639                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1640                                         },
1641                                         MessageSendEvent::SendChannelAnnouncement { ref node_id, ref msg, ref update_msg } => {
1642                                                 log_debug!(self.logger, "Handling SendChannelAnnouncement event in peer_handler for node {} for short channel id {}",
1643                                                                 log_pubkey!(node_id),
1644                                                                 msg.contents.short_channel_id);
1645                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1646                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), update_msg);
1647                                         },
1648                                         MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
1649                                                 log_debug!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1650                                                 match self.message_handler.route_handler.handle_channel_announcement(&msg) {
1651                                                         Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1652                                                                 self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None),
1653                                                         _ => {},
1654                                                 }
1655                                                 match self.message_handler.route_handler.handle_channel_update(&update_msg) {
1656                                                         Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1657                                                                 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(update_msg), None),
1658                                                         _ => {},
1659                                                 }
1660                                         },
1661                                         MessageSendEvent::BroadcastChannelUpdate { msg } => {
1662                                                 log_debug!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1663                                                 match self.message_handler.route_handler.handle_channel_update(&msg) {
1664                                                         Ok(_) | Err(LightningError { action: msgs::ErrorAction::IgnoreDuplicateGossip, .. }) =>
1665                                                                 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None),
1666                                                         _ => {},
1667                                                 }
1668                                         },
1669                                         MessageSendEvent::SendChannelUpdate { ref node_id, ref msg } => {
1670                                                 log_trace!(self.logger, "Handling SendChannelUpdate event in peer_handler for node {} for channel {}",
1671                                                                 log_pubkey!(node_id), msg.contents.short_channel_id);
1672                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1673                                         },
1674                                         MessageSendEvent::HandleError { ref node_id, ref action } => {
1675                                                 match *action {
1676                                                         msgs::ErrorAction::DisconnectPeer { ref msg } => {
1677                                                                 // We do not have the peers write lock, so we just store that we're
1678                                                                 // about to disconenct the peer and do it after we finish
1679                                                                 // processing most messages.
1680                                                                 peers_to_disconnect.insert(*node_id, msg.clone());
1681                                                         },
1682                                                         msgs::ErrorAction::IgnoreAndLog(level) => {
1683                                                                 log_given_level!(self.logger, level, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
1684                                                         },
1685                                                         msgs::ErrorAction::IgnoreDuplicateGossip => {},
1686                                                         msgs::ErrorAction::IgnoreError => {
1687                                                                 log_debug!(self.logger, "Received a HandleError event to be ignored for node {}", log_pubkey!(node_id));
1688                                                         },
1689                                                         msgs::ErrorAction::SendErrorMessage { ref msg } => {
1690                                                                 log_trace!(self.logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
1691                                                                                 log_pubkey!(node_id),
1692                                                                                 msg.data);
1693                                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1694                                                         },
1695                                                         msgs::ErrorAction::SendWarningMessage { ref msg, ref log_level } => {
1696                                                                 log_given_level!(self.logger, *log_level, "Handling SendWarningMessage HandleError event in peer_handler for node {} with message {}",
1697                                                                                 log_pubkey!(node_id),
1698                                                                                 msg.data);
1699                                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1700                                                         },
1701                                                 }
1702                                         },
1703                                         MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
1704                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1705                                         },
1706                                         MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
1707                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1708                                         }
1709                                         MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
1710                                                 log_gossip!(self.logger, "Handling SendReplyChannelRange event in peer_handler for node {} with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}",
1711                                                         log_pubkey!(node_id),
1712                                                         msg.short_channel_ids.len(),
1713                                                         msg.first_blocknum,
1714                                                         msg.number_of_blocks,
1715                                                         msg.sync_complete);
1716                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1717                                         }
1718                                         MessageSendEvent::SendGossipTimestampFilter { ref node_id, ref msg } => {
1719                                                 self.enqueue_message(&mut *get_peer_for_forwarding!(node_id), msg);
1720                                         }
1721                                 }
1722                         }
1723
1724                         for (node_id, msg) in self.custom_message_handler.get_and_clear_pending_msg() {
1725                                 if peers_to_disconnect.get(&node_id).is_some() { continue; }
1726                                 self.enqueue_message(&mut *get_peer_for_forwarding!(&node_id), &msg);
1727                         }
1728
1729                         for (descriptor, peer_mutex) in peers.iter() {
1730                                 self.do_attempt_write_data(&mut (*descriptor).clone(), &mut *peer_mutex.lock().unwrap());
1731                         }
1732                 }
1733                 if !peers_to_disconnect.is_empty() {
1734                         let mut peers_lock = self.peers.write().unwrap();
1735                         let peers = &mut *peers_lock;
1736                         for (node_id, msg) in peers_to_disconnect.drain() {
1737                                 // Note that since we are holding the peers *write* lock we can
1738                                 // remove from node_id_to_descriptor immediately (as no other
1739                                 // thread can be holding the peer lock if we have the global write
1740                                 // lock).
1741
1742                                 if let Some(mut descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
1743                                         if let Some(peer_mutex) = peers.remove(&descriptor) {
1744                                                 if let Some(msg) = msg {
1745                                                         log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
1746                                                                         log_pubkey!(node_id),
1747                                                                         msg.data);
1748                                                         let mut peer = peer_mutex.lock().unwrap();
1749                                                         self.enqueue_message(&mut *peer, &msg);
1750                                                         // This isn't guaranteed to work, but if there is enough free
1751                                                         // room in the send buffer, put the error message there...
1752                                                         self.do_attempt_write_data(&mut descriptor, &mut *peer);
1753                                                 } else {
1754                                                         log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with no message", log_pubkey!(node_id));
1755                                                 }
1756                                         }
1757                                         descriptor.disconnect_socket();
1758                                         self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1759                                         self.message_handler.onion_message_handler.peer_disconnected(&node_id, false);
1760                                 }
1761                         }
1762                 }
1763         }
1764
1765         /// Indicates that the given socket descriptor's connection is now closed.
1766         pub fn socket_disconnected(&self, descriptor: &Descriptor) {
1767                 self.disconnect_event_internal(descriptor, false);
1768         }
1769
1770         fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
1771                 let mut peers = self.peers.write().unwrap();
1772                 let peer_option = peers.remove(descriptor);
1773                 match peer_option {
1774                         None => {
1775                                 // This is most likely a simple race condition where the user found that the socket
1776                                 // was disconnected, then we told the user to `disconnect_socket()`, then they
1777                                 // called this method. Either way we're disconnected, return.
1778                         },
1779                         Some(peer_lock) => {
1780                                 let peer = peer_lock.lock().unwrap();
1781                                 if let Some(node_id) = peer.their_node_id {
1782                                         log_trace!(self.logger,
1783                                                 "Handling disconnection of peer {}, with {}future connection to the peer possible.",
1784                                                 log_pubkey!(node_id), if no_connection_possible { "no " } else { "" });
1785                                         self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
1786                                         self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1787                                         self.message_handler.onion_message_handler.peer_disconnected(&node_id, no_connection_possible);
1788                                 }
1789                         }
1790                 };
1791         }
1792
1793         /// Disconnect a peer given its node id.
1794         ///
1795         /// Set `no_connection_possible` to true to prevent any further connection with this peer,
1796         /// force-closing any channels we have with it.
1797         ///
1798         /// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the
1799         /// peer. Thus, be very careful about reentrancy issues.
1800         ///
1801         /// [`disconnect_socket`]: SocketDescriptor::disconnect_socket
1802         pub fn disconnect_by_node_id(&self, node_id: PublicKey, no_connection_possible: bool) {
1803                 let mut peers_lock = self.peers.write().unwrap();
1804                 if let Some(mut descriptor) = self.node_id_to_descriptor.lock().unwrap().remove(&node_id) {
1805                         log_trace!(self.logger, "Disconnecting peer with id {} due to client request", node_id);
1806                         peers_lock.remove(&descriptor);
1807                         self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1808                         self.message_handler.onion_message_handler.peer_disconnected(&node_id, no_connection_possible);
1809                         descriptor.disconnect_socket();
1810                 }
1811         }
1812
1813         /// Disconnects all currently-connected peers. This is useful on platforms where there may be
1814         /// an indication that TCP sockets have stalled even if we weren't around to time them out
1815         /// using regular ping/pongs.
1816         pub fn disconnect_all_peers(&self) {
1817                 let mut peers_lock = self.peers.write().unwrap();
1818                 self.node_id_to_descriptor.lock().unwrap().clear();
1819                 let peers = &mut *peers_lock;
1820                 for (mut descriptor, peer) in peers.drain() {
1821                         if let Some(node_id) = peer.lock().unwrap().their_node_id {
1822                                 log_trace!(self.logger, "Disconnecting peer with id {} due to client request to disconnect all peers", node_id);
1823                                 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1824                                 self.message_handler.onion_message_handler.peer_disconnected(&node_id, false);
1825                         }
1826                         descriptor.disconnect_socket();
1827                 }
1828         }
1829
1830         /// This is called when we're blocked on sending additional gossip messages until we receive a
1831         /// pong. If we aren't waiting on a pong, we take this opportunity to send a ping (setting
1832         /// `awaiting_pong_timer_tick_intervals` to a special flag value to indicate this).
1833         fn maybe_send_extra_ping(&self, peer: &mut Peer) {
1834                 if peer.awaiting_pong_timer_tick_intervals == 0 {
1835                         peer.awaiting_pong_timer_tick_intervals = -1;
1836                         let ping = msgs::Ping {
1837                                 ponglen: 0,
1838                                 byteslen: 64,
1839                         };
1840                         self.enqueue_message(peer, &ping);
1841                 }
1842         }
1843
1844         /// Send pings to each peer and disconnect those which did not respond to the last round of
1845         /// pings.
1846         ///
1847         /// This may be called on any timescale you want, however, roughly once every ten seconds is
1848         /// preferred. The call rate determines both how often we send a ping to our peers and how much
1849         /// time they have to respond before we disconnect them.
1850         ///
1851         /// May call [`send_data`] on all [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1852         /// issues!
1853         ///
1854         /// [`send_data`]: SocketDescriptor::send_data
1855         pub fn timer_tick_occurred(&self) {
1856                 let mut descriptors_needing_disconnect = Vec::new();
1857                 {
1858                         let peers_lock = self.peers.read().unwrap();
1859
1860                         for (descriptor, peer_mutex) in peers_lock.iter() {
1861                                 let mut peer = peer_mutex.lock().unwrap();
1862                                 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_node_id.is_none() {
1863                                         // The peer needs to complete its handshake before we can exchange messages. We
1864                                         // give peers one timer tick to complete handshake, reusing
1865                                         // `awaiting_pong_timer_tick_intervals` to track number of timer ticks taken
1866                                         // for handshake completion.
1867                                         if peer.awaiting_pong_timer_tick_intervals != 0 {
1868                                                 descriptors_needing_disconnect.push(descriptor.clone());
1869                                         } else {
1870                                                 peer.awaiting_pong_timer_tick_intervals = 1;
1871                                         }
1872                                         continue;
1873                                 }
1874
1875                                 if peer.awaiting_pong_timer_tick_intervals == -1 {
1876                                         // Magic value set in `maybe_send_extra_ping`.
1877                                         peer.awaiting_pong_timer_tick_intervals = 1;
1878                                         peer.received_message_since_timer_tick = false;
1879                                         continue;
1880                                 }
1881
1882                                 if (peer.awaiting_pong_timer_tick_intervals > 0 && !peer.received_message_since_timer_tick)
1883                                         || peer.awaiting_pong_timer_tick_intervals as u64 >
1884                                                 MAX_BUFFER_DRAIN_TICK_INTERVALS_PER_PEER as u64 * peers_lock.len() as u64
1885                                 {
1886                                         descriptors_needing_disconnect.push(descriptor.clone());
1887                                         continue;
1888                                 }
1889                                 peer.received_message_since_timer_tick = false;
1890
1891                                 if peer.awaiting_pong_timer_tick_intervals > 0 {
1892                                         peer.awaiting_pong_timer_tick_intervals += 1;
1893                                         continue;
1894                                 }
1895
1896                                 peer.awaiting_pong_timer_tick_intervals = 1;
1897                                 let ping = msgs::Ping {
1898                                         ponglen: 0,
1899                                         byteslen: 64,
1900                                 };
1901                                 self.enqueue_message(&mut *peer, &ping);
1902                                 self.do_attempt_write_data(&mut (descriptor.clone()), &mut *peer);
1903                         }
1904                 }
1905
1906                 if !descriptors_needing_disconnect.is_empty() {
1907                         {
1908                                 let mut peers_lock = self.peers.write().unwrap();
1909                                 for descriptor in descriptors_needing_disconnect.iter() {
1910                                         if let Some(peer) = peers_lock.remove(descriptor) {
1911                                                 if let Some(node_id) = peer.lock().unwrap().their_node_id {
1912                                                         log_trace!(self.logger, "Disconnecting peer with id {} due to ping timeout", node_id);
1913                                                         self.node_id_to_descriptor.lock().unwrap().remove(&node_id);
1914                                                         self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1915                                                         self.message_handler.onion_message_handler.peer_disconnected(&node_id, false);
1916                                                 }
1917                                         }
1918                                 }
1919                         }
1920
1921                         for mut descriptor in descriptors_needing_disconnect.drain(..) {
1922                                 descriptor.disconnect_socket();
1923                         }
1924                 }
1925         }
1926
1927         #[allow(dead_code)]
1928         // Messages of up to 64KB should never end up more than half full with addresses, as that would
1929         // be absurd. We ensure this by checking that at least 100 (our stated public contract on when
1930         // broadcast_node_announcement panics) of the maximum-length addresses would fit in a 64KB
1931         // message...
1932         const HALF_MESSAGE_IS_ADDRS: u32 = ::core::u16::MAX as u32 / (NetAddress::MAX_LEN as u32 + 1) / 2;
1933         #[deny(const_err)]
1934         #[allow(dead_code)]
1935         // ...by failing to compile if the number of addresses that would be half of a message is
1936         // smaller than 100:
1937         const STATIC_ASSERT: u32 = Self::HALF_MESSAGE_IS_ADDRS - 100;
1938
1939         /// Generates a signed node_announcement from the given arguments, sending it to all connected
1940         /// peers. Note that peers will likely ignore this message unless we have at least one public
1941         /// channel which has at least six confirmations on-chain.
1942         ///
1943         /// `rgb` is a node "color" and `alias` is a printable human-readable string to describe this
1944         /// node to humans. They carry no in-protocol meaning.
1945         ///
1946         /// `addresses` represent the set (possibly empty) of socket addresses on which this node
1947         /// accepts incoming connections. These will be included in the node_announcement, publicly
1948         /// tying these addresses together and to this node. If you wish to preserve user privacy,
1949         /// addresses should likely contain only Tor Onion addresses.
1950         ///
1951         /// Panics if `addresses` is absurdly large (more than 100).
1952         ///
1953         /// [`get_and_clear_pending_msg_events`]: MessageSendEventsProvider::get_and_clear_pending_msg_events
1954         pub fn broadcast_node_announcement(&self, rgb: [u8; 3], alias: [u8; 32], mut addresses: Vec<NetAddress>) {
1955                 if addresses.len() > 100 {
1956                         panic!("More than half the message size was taken up by public addresses!");
1957                 }
1958
1959                 // While all existing nodes handle unsorted addresses just fine, the spec requires that
1960                 // addresses be sorted for future compatibility.
1961                 addresses.sort_by_key(|addr| addr.get_id());
1962
1963                 let announcement = msgs::UnsignedNodeAnnouncement {
1964                         features: self.message_handler.chan_handler.provided_node_features(),
1965                         timestamp: self.last_node_announcement_serial.fetch_add(1, Ordering::AcqRel) as u32,
1966                         node_id: PublicKey::from_secret_key(&self.secp_ctx, &self.our_node_secret),
1967                         rgb, alias, addresses,
1968                         excess_address_data: Vec::new(),
1969                         excess_data: Vec::new(),
1970                 };
1971                 let msghash = hash_to_message!(&Sha256dHash::hash(&announcement.encode()[..])[..]);
1972                 let node_announce_sig = sign(&self.secp_ctx, &msghash, &self.our_node_secret);
1973
1974                 let msg = msgs::NodeAnnouncement {
1975                         signature: node_announce_sig,
1976                         contents: announcement
1977                 };
1978
1979                 log_debug!(self.logger, "Broadcasting NodeAnnouncement after passing it to our own RoutingMessageHandler.");
1980                 let _ = self.message_handler.route_handler.handle_node_announcement(&msg);
1981                 self.forward_broadcast_msg(&*self.peers.read().unwrap(), &wire::Message::NodeAnnouncement(msg), None);
1982         }
1983 }
1984
1985 fn is_gossip_msg(type_id: u16) -> bool {
1986         match type_id {
1987                 msgs::ChannelAnnouncement::TYPE |
1988                 msgs::ChannelUpdate::TYPE |
1989                 msgs::NodeAnnouncement::TYPE |
1990                 msgs::QueryChannelRange::TYPE |
1991                 msgs::ReplyChannelRange::TYPE |
1992                 msgs::QueryShortChannelIds::TYPE |
1993                 msgs::ReplyShortChannelIdsEnd::TYPE => true,
1994                 _ => false
1995         }
1996 }
1997
1998 #[cfg(test)]
1999 mod tests {
2000         use ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor, IgnoringMessageHandler, filter_addresses};
2001         use ln::{msgs, wire};
2002         use ln::msgs::NetAddress;
2003         use util::events;
2004         use util::test_utils;
2005
2006         use bitcoin::secp256k1::Secp256k1;
2007         use bitcoin::secp256k1::{SecretKey, PublicKey};
2008
2009         use prelude::*;
2010         use sync::{Arc, Mutex};
2011         use core::sync::atomic::Ordering;
2012
2013         #[derive(Clone)]
2014         struct FileDescriptor {
2015                 fd: u16,
2016                 outbound_data: Arc<Mutex<Vec<u8>>>,
2017         }
2018         impl PartialEq for FileDescriptor {
2019                 fn eq(&self, other: &Self) -> bool {
2020                         self.fd == other.fd
2021                 }
2022         }
2023         impl Eq for FileDescriptor { }
2024         impl core::hash::Hash for FileDescriptor {
2025                 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
2026                         self.fd.hash(hasher)
2027                 }
2028         }
2029
2030         impl SocketDescriptor for FileDescriptor {
2031                 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
2032                         self.outbound_data.lock().unwrap().extend_from_slice(data);
2033                         data.len()
2034                 }
2035
2036                 fn disconnect_socket(&mut self) {}
2037         }
2038
2039         struct PeerManagerCfg {
2040                 chan_handler: test_utils::TestChannelMessageHandler,
2041                 routing_handler: test_utils::TestRoutingMessageHandler,
2042                 logger: test_utils::TestLogger,
2043         }
2044
2045         fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
2046                 let mut cfgs = Vec::new();
2047                 for _ in 0..peer_count {
2048                         cfgs.push(
2049                                 PeerManagerCfg{
2050                                         chan_handler: test_utils::TestChannelMessageHandler::new(),
2051                                         logger: test_utils::TestLogger::new(),
2052                                         routing_handler: test_utils::TestRoutingMessageHandler::new(),
2053                                 }
2054                         );
2055                 }
2056
2057                 cfgs
2058         }
2059
2060         fn create_network<'a>(peer_count: usize, cfgs: &'a Vec<PeerManagerCfg>) -> Vec<PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, IgnoringMessageHandler, &'a test_utils::TestLogger, IgnoringMessageHandler>> {
2061                 let mut peers = Vec::new();
2062                 for i in 0..peer_count {
2063                         let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
2064                         let ephemeral_bytes = [i as u8; 32];
2065                         let msg_handler = MessageHandler { chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler, onion_message_handler: IgnoringMessageHandler {} };
2066                         let peer = PeerManager::new(msg_handler, node_secret, 0, &ephemeral_bytes, &cfgs[i].logger, IgnoringMessageHandler {});
2067                         peers.push(peer);
2068                 }
2069
2070                 peers
2071         }
2072
2073         fn establish_connection<'a>(peer_a: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, IgnoringMessageHandler, &'a test_utils::TestLogger, IgnoringMessageHandler>, peer_b: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, IgnoringMessageHandler, &'a test_utils::TestLogger, IgnoringMessageHandler>) -> (FileDescriptor, FileDescriptor) {
2074                 let secp_ctx = Secp256k1::new();
2075                 let a_id = PublicKey::from_secret_key(&secp_ctx, &peer_a.our_node_secret);
2076                 let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
2077                 let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
2078                 let initial_data = peer_b.new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
2079                 peer_a.new_inbound_connection(fd_a.clone(), None).unwrap();
2080                 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
2081                 peer_a.process_events();
2082
2083                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2084                 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2085
2086                 peer_b.process_events();
2087                 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2088                 assert_eq!(peer_a.read_event(&mut fd_a, &b_data).unwrap(), false);
2089
2090                 peer_a.process_events();
2091                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2092                 assert_eq!(peer_b.read_event(&mut fd_b, &a_data).unwrap(), false);
2093
2094                 (fd_a.clone(), fd_b.clone())
2095         }
2096
2097         #[test]
2098         fn test_disconnect_peer() {
2099                 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2100                 // push a DisconnectPeer event to remove the node flagged by id
2101                 let cfgs = create_peermgr_cfgs(2);
2102                 let chan_handler = test_utils::TestChannelMessageHandler::new();
2103                 let mut peers = create_network(2, &cfgs);
2104                 establish_connection(&peers[0], &peers[1]);
2105                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2106
2107                 let secp_ctx = Secp256k1::new();
2108                 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
2109
2110                 chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
2111                         node_id: their_id,
2112                         action: msgs::ErrorAction::DisconnectPeer { msg: None },
2113                 });
2114                 assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1);
2115                 peers[0].message_handler.chan_handler = &chan_handler;
2116
2117                 peers[0].process_events();
2118                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2119         }
2120
2121         #[test]
2122         fn test_send_simple_msg() {
2123                 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2124                 // push a message from one peer to another.
2125                 let cfgs = create_peermgr_cfgs(2);
2126                 let a_chan_handler = test_utils::TestChannelMessageHandler::new();
2127                 let b_chan_handler = test_utils::TestChannelMessageHandler::new();
2128                 let mut peers = create_network(2, &cfgs);
2129                 let (fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
2130                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2131
2132                 let secp_ctx = Secp256k1::new();
2133                 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
2134
2135                 let msg = msgs::Shutdown { channel_id: [42; 32], scriptpubkey: bitcoin::Script::new() };
2136                 a_chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::SendShutdown {
2137                         node_id: their_id, msg: msg.clone()
2138                 });
2139                 peers[0].message_handler.chan_handler = &a_chan_handler;
2140
2141                 b_chan_handler.expect_receive_msg(wire::Message::Shutdown(msg));
2142                 peers[1].message_handler.chan_handler = &b_chan_handler;
2143
2144                 peers[0].process_events();
2145
2146                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2147                 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
2148         }
2149
2150         #[test]
2151         fn test_disconnect_all_peer() {
2152                 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
2153                 // then calls disconnect_all_peers
2154                 let cfgs = create_peermgr_cfgs(2);
2155                 let peers = create_network(2, &cfgs);
2156                 establish_connection(&peers[0], &peers[1]);
2157                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2158
2159                 peers[0].disconnect_all_peers();
2160                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2161         }
2162
2163         #[test]
2164         fn test_timer_tick_occurred() {
2165                 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
2166                 let cfgs = create_peermgr_cfgs(2);
2167                 let peers = create_network(2, &cfgs);
2168                 establish_connection(&peers[0], &peers[1]);
2169                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2170
2171                 // peers[0] awaiting_pong is set to true, but the Peer is still connected
2172                 peers[0].timer_tick_occurred();
2173                 peers[0].process_events();
2174                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2175
2176                 // Since timer_tick_occurred() is called again when awaiting_pong is true, all Peers are disconnected
2177                 peers[0].timer_tick_occurred();
2178                 peers[0].process_events();
2179                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2180         }
2181
2182         #[test]
2183         fn test_do_attempt_write_data() {
2184                 // Create 2 peers with custom TestRoutingMessageHandlers and connect them.
2185                 let cfgs = create_peermgr_cfgs(2);
2186                 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
2187                 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
2188                 let peers = create_network(2, &cfgs);
2189
2190                 // By calling establish_connect, we trigger do_attempt_write_data between
2191                 // the peers. Previously this function would mistakenly enter an infinite loop
2192                 // when there were more channel messages available than could fit into a peer's
2193                 // buffer. This issue would now be detected by this test (because we use custom
2194                 // RoutingMessageHandlers that intentionally return more channel messages
2195                 // than can fit into a peer's buffer).
2196                 let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
2197
2198                 // Make each peer to read the messages that the other peer just wrote to them. Note that
2199                 // due to the max-message-before-ping limits this may take a few iterations to complete.
2200                 for _ in 0..150/super::BUFFER_DRAIN_MSGS_PER_TICK + 1 {
2201                         peers[1].process_events();
2202                         let a_read_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2203                         assert!(!a_read_data.is_empty());
2204
2205                         peers[0].read_event(&mut fd_a, &a_read_data).unwrap();
2206                         peers[0].process_events();
2207
2208                         let b_read_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2209                         assert!(!b_read_data.is_empty());
2210                         peers[1].read_event(&mut fd_b, &b_read_data).unwrap();
2211
2212                         peers[0].process_events();
2213                         assert_eq!(fd_a.outbound_data.lock().unwrap().len(), 0, "Until A receives data, it shouldn't send more messages");
2214                 }
2215
2216                 // Check that each peer has received the expected number of channel updates and channel
2217                 // announcements.
2218                 assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
2219                 assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
2220                 assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 108);
2221                 assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 54);
2222         }
2223
2224         #[test]
2225         fn test_handshake_timeout() {
2226                 // Tests that we time out a peer still waiting on handshake completion after a full timer
2227                 // tick.
2228                 let cfgs = create_peermgr_cfgs(2);
2229                 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
2230                 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
2231                 let peers = create_network(2, &cfgs);
2232
2233                 let secp_ctx = Secp256k1::new();
2234                 let a_id = PublicKey::from_secret_key(&secp_ctx, &peers[0].our_node_secret);
2235                 let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
2236                 let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
2237                 let initial_data = peers[1].new_outbound_connection(a_id, fd_b.clone(), None).unwrap();
2238                 peers[0].new_inbound_connection(fd_a.clone(), None).unwrap();
2239
2240                 // If we get a single timer tick before completion, that's fine
2241                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2242                 peers[0].timer_tick_occurred();
2243                 assert_eq!(peers[0].peers.read().unwrap().len(), 1);
2244
2245                 assert_eq!(peers[0].read_event(&mut fd_a, &initial_data).unwrap(), false);
2246                 peers[0].process_events();
2247                 let a_data = fd_a.outbound_data.lock().unwrap().split_off(0);
2248                 assert_eq!(peers[1].read_event(&mut fd_b, &a_data).unwrap(), false);
2249                 peers[1].process_events();
2250
2251                 // ...but if we get a second timer tick, we should disconnect the peer
2252                 peers[0].timer_tick_occurred();
2253                 assert_eq!(peers[0].peers.read().unwrap().len(), 0);
2254
2255                 let b_data = fd_b.outbound_data.lock().unwrap().split_off(0);
2256                 assert!(peers[0].read_event(&mut fd_a, &b_data).is_err());
2257         }
2258
2259         #[test]
2260         fn test_filter_addresses(){
2261                 // Tests the filter_addresses function.
2262
2263                 // For (10/8)
2264                 let ip_address = NetAddress::IPv4{addr: [10, 0, 0, 0], port: 1000};
2265                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2266                 let ip_address = NetAddress::IPv4{addr: [10, 0, 255, 201], port: 1000};
2267                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2268                 let ip_address = NetAddress::IPv4{addr: [10, 255, 255, 255], port: 1000};
2269                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2270
2271                 // For (0/8)
2272                 let ip_address = NetAddress::IPv4{addr: [0, 0, 0, 0], port: 1000};
2273                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2274                 let ip_address = NetAddress::IPv4{addr: [0, 0, 255, 187], port: 1000};
2275                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2276                 let ip_address = NetAddress::IPv4{addr: [0, 255, 255, 255], port: 1000};
2277                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2278
2279                 // For (100.64/10)
2280                 let ip_address = NetAddress::IPv4{addr: [100, 64, 0, 0], port: 1000};
2281                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2282                 let ip_address = NetAddress::IPv4{addr: [100, 78, 255, 0], port: 1000};
2283                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2284                 let ip_address = NetAddress::IPv4{addr: [100, 127, 255, 255], port: 1000};
2285                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2286
2287                 // For (127/8)
2288                 let ip_address = NetAddress::IPv4{addr: [127, 0, 0, 0], port: 1000};
2289                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2290                 let ip_address = NetAddress::IPv4{addr: [127, 65, 73, 0], port: 1000};
2291                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2292                 let ip_address = NetAddress::IPv4{addr: [127, 255, 255, 255], port: 1000};
2293                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2294
2295                 // For (169.254/16)
2296                 let ip_address = NetAddress::IPv4{addr: [169, 254, 0, 0], port: 1000};
2297                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2298                 let ip_address = NetAddress::IPv4{addr: [169, 254, 221, 101], port: 1000};
2299                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2300                 let ip_address = NetAddress::IPv4{addr: [169, 254, 255, 255], port: 1000};
2301                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2302
2303                 // For (172.16/12)
2304                 let ip_address = NetAddress::IPv4{addr: [172, 16, 0, 0], port: 1000};
2305                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2306                 let ip_address = NetAddress::IPv4{addr: [172, 27, 101, 23], port: 1000};
2307                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2308                 let ip_address = NetAddress::IPv4{addr: [172, 31, 255, 255], port: 1000};
2309                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2310
2311                 // For (192.168/16)
2312                 let ip_address = NetAddress::IPv4{addr: [192, 168, 0, 0], port: 1000};
2313                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2314                 let ip_address = NetAddress::IPv4{addr: [192, 168, 205, 159], port: 1000};
2315                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2316                 let ip_address = NetAddress::IPv4{addr: [192, 168, 255, 255], port: 1000};
2317                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2318
2319                 // For (192.88.99/24)
2320                 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 0], port: 1000};
2321                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2322                 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 140], port: 1000};
2323                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2324                 let ip_address = NetAddress::IPv4{addr: [192, 88, 99, 255], port: 1000};
2325                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2326
2327                 // For other IPv4 addresses
2328                 let ip_address = NetAddress::IPv4{addr: [188, 255, 99, 0], port: 1000};
2329                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2330                 let ip_address = NetAddress::IPv4{addr: [123, 8, 129, 14], port: 1000};
2331                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2332                 let ip_address = NetAddress::IPv4{addr: [2, 88, 9, 255], port: 1000};
2333                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2334
2335                 // For (2000::/3)
2336                 let ip_address = NetAddress::IPv6{addr: [32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], port: 1000};
2337                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2338                 let ip_address = NetAddress::IPv6{addr: [45, 34, 209, 190, 0, 123, 55, 34, 0, 0, 3, 27, 201, 0, 0, 0], port: 1000};
2339                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2340                 let ip_address = NetAddress::IPv6{addr: [63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], port: 1000};
2341                 assert_eq!(filter_addresses(Some(ip_address.clone())), Some(ip_address.clone()));
2342
2343                 // For other IPv6 addresses
2344                 let ip_address = NetAddress::IPv6{addr: [24, 240, 12, 32, 0, 0, 0, 0, 20, 97, 0, 32, 121, 254, 0, 0], port: 1000};
2345                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2346                 let ip_address = NetAddress::IPv6{addr: [68, 23, 56, 63, 0, 0, 2, 7, 75, 109, 0, 39, 0, 0, 0, 0], port: 1000};
2347                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2348                 let ip_address = NetAddress::IPv6{addr: [101, 38, 140, 230, 100, 0, 30, 98, 0, 26, 0, 0, 57, 96, 0, 0], port: 1000};
2349                 assert_eq!(filter_addresses(Some(ip_address.clone())), None);
2350
2351                 // For (None)
2352                 assert_eq!(filter_addresses(None), None);
2353         }
2354 }