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