e75c2c96e98c9e28dc24170f379c58bb42b6c4ac
[rust-lightning] / lightning / src / ln / peer_handler.rs
1 //! Top level peer message handling and socket handling logic lives here.
2 //!
3 //! Instead of actually servicing sockets ourselves we require that you implement the
4 //! SocketDescriptor interface and use that to receive actions which you should perform on the
5 //! socket, and call into PeerManager with bytes read from the socket. The PeerManager will then
6 //! call into the provided message handlers (probably a ChannelManager and NetGraphmsgHandler) with messages
7 //! they should handle, and encoding/sending response messages.
8
9 use bitcoin::secp256k1::key::{SecretKey,PublicKey};
10
11 use ln::features::InitFeatures;
12 use ln::msgs;
13 use ln::msgs::ChannelMessageHandler;
14 use ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager};
15 use util::ser::{VecWriter, Writeable};
16 use ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
17 use ln::wire;
18 use ln::wire::Encode;
19 use util::byte_utils;
20 use util::events::{MessageSendEvent, MessageSendEventsProvider};
21 use util::logger::Logger;
22
23 use std::collections::{HashMap,hash_map,HashSet,LinkedList};
24 use std::sync::{Arc, Mutex};
25 use std::sync::atomic::{AtomicUsize, Ordering};
26 use std::{cmp,error,hash,fmt};
27 use std::ops::Deref;
28
29 use bitcoin::hashes::sha256::Hash as Sha256;
30 use bitcoin::hashes::sha256::HashEngine as Sha256Engine;
31 use bitcoin::hashes::{HashEngine, Hash};
32
33 /// Provides references to trait impls which handle different types of messages.
34 pub struct MessageHandler<CM: Deref> where CM::Target: msgs::ChannelMessageHandler {
35         /// A message handler which handles messages specific to channels. Usually this is just a
36         /// ChannelManager object.
37         pub chan_handler: CM,
38         /// A message handler which handles messages updating our knowledge of the network channel
39         /// graph. Usually this is just a NetGraphMsgHandlerMonitor object.
40         pub route_handler: Arc<msgs::RoutingMessageHandler>,
41 }
42
43 /// Provides an object which can be used to send data to and which uniquely identifies a connection
44 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
45 /// implement Hash to meet the PeerManager API.
46 ///
47 /// For efficiency, Clone should be relatively cheap for this type.
48 ///
49 /// You probably want to just extend an int and put a file descriptor in a struct and implement
50 /// send_data. Note that if you are using a higher-level net library that may call close() itself,
51 /// be careful to ensure you don't have races whereby you might register a new connection with an
52 /// fd which is the same as a previous one which has yet to be removed via
53 /// PeerManager::socket_disconnected().
54 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
55         /// Attempts to send some data from the given slice to the peer.
56         ///
57         /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
58         /// Note that in the disconnected case, socket_disconnected must still fire and further write
59         /// attempts may occur until that time.
60         ///
61         /// If the returned size is smaller than data.len(), a write_available event must
62         /// trigger the next time more data can be written. Additionally, until the a send_data event
63         /// completes fully, no further read_events should trigger on the same peer!
64         ///
65         /// If a read_event on this descriptor had previously returned true (indicating that read
66         /// events should be paused to prevent DoS in the send buffer), resume_read may be set
67         /// indicating that read events on this descriptor should resume. A resume_read of false does
68         /// *not* imply that further read events should be paused.
69         fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize;
70         /// Disconnect the socket pointed to by this SocketDescriptor. Once this function returns, no
71         /// more calls to write_buffer_space_avail, read_event or socket_disconnected may be made with
72         /// this descriptor. No socket_disconnected call should be generated as a result of this call,
73         /// though races may occur whereby disconnect_socket is called after a call to
74         /// socket_disconnected but prior to socket_disconnected returning.
75         fn disconnect_socket(&mut self);
76 }
77
78 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
79 /// generate no further read_event/write_buffer_space_avail calls for the descriptor, only
80 /// triggering a single socket_disconnected call (unless it was provided in response to a
81 /// new_*_connection event, in which case no such socket_disconnected() must be called and the
82 /// socket silently disconencted).
83 pub struct PeerHandleError {
84         /// Used to indicate that we probably can't make any future connections to this peer, implying
85         /// we should go ahead and force-close any channels we have with it.
86         no_connection_possible: bool,
87 }
88 impl fmt::Debug for PeerHandleError {
89         fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
90                 formatter.write_str("Peer Sent Invalid Data")
91         }
92 }
93 impl fmt::Display for PeerHandleError {
94         fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
95                 formatter.write_str("Peer Sent Invalid Data")
96         }
97 }
98 impl error::Error for PeerHandleError {
99         fn description(&self) -> &str {
100                 "Peer Sent Invalid Data"
101         }
102 }
103
104 enum InitSyncTracker{
105         NoSyncRequested,
106         ChannelsSyncing(u64),
107         NodesSyncing(PublicKey),
108 }
109
110 struct Peer {
111         channel_encryptor: PeerChannelEncryptor,
112         outbound: bool,
113         their_node_id: Option<PublicKey>,
114         their_features: Option<InitFeatures>,
115
116         pending_outbound_buffer: LinkedList<Vec<u8>>,
117         pending_outbound_buffer_first_msg_offset: usize,
118         awaiting_write_event: bool,
119
120         pending_read_buffer: Vec<u8>,
121         pending_read_buffer_pos: usize,
122         pending_read_is_header: bool,
123
124         sync_status: InitSyncTracker,
125
126         awaiting_pong: bool,
127 }
128
129 impl Peer {
130         /// Returns true if the channel announcements/updates for the given channel should be
131         /// forwarded to this peer.
132         /// If we are sending our routing table to this peer and we have not yet sent channel
133         /// announcements/updates for the given channel_id then we will send it when we get to that
134         /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
135         /// sent the old versions, we should send the update, and so return true here.
136         fn should_forward_channel_announcement(&self, channel_id: u64)->bool{
137                 match self.sync_status {
138                         InitSyncTracker::NoSyncRequested => true,
139                         InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
140                         InitSyncTracker::NodesSyncing(_) => true,
141                 }
142         }
143
144         /// Similar to the above, but for node announcements indexed by node_id.
145         fn should_forward_node_announcement(&self, node_id: PublicKey) -> bool {
146                 match self.sync_status {
147                         InitSyncTracker::NoSyncRequested => true,
148                         InitSyncTracker::ChannelsSyncing(_) => false,
149                         InitSyncTracker::NodesSyncing(pk) => pk < node_id,
150                 }
151         }
152 }
153
154 struct PeerHolder<Descriptor: SocketDescriptor> {
155         peers: HashMap<Descriptor, Peer>,
156         /// Added to by do_read_event for cases where we pushed a message onto the send buffer but
157         /// didn't call do_attempt_write_data to avoid reentrancy. Cleared in process_events()
158         peers_needing_send: HashSet<Descriptor>,
159         /// Only add to this set when noise completes:
160         node_id_to_descriptor: HashMap<PublicKey, Descriptor>,
161 }
162
163 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
164 fn _check_usize_is_32_or_64() {
165         // See below, less than 32 bit pointers may be unsafe here!
166         unsafe { mem::transmute::<*const usize, [u8; 4]>(panic!()); }
167 }
168
169 /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
170 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
171 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
172 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
173 /// issues such as overly long function definitions.
174 pub type SimpleArcPeerManager<SD, M, T, F, L> = Arc<PeerManager<SD, SimpleArcChannelManager<M, T, F, L>, Arc<L>>>;
175
176 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
177 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
178 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
179 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
180 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
181 /// helps with issues such as long function definitions.
182 pub type SimpleRefPeerManager<'a, 'b, 'c, 'd, 'e, SD, M, T, F, L> = PeerManager<SD, SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L>, &'e L>;
183
184 /// A PeerManager manages a set of peers, described by their SocketDescriptor and marshalls socket
185 /// events into messages which it passes on to its MessageHandlers.
186 ///
187 /// Rather than using a plain PeerManager, it is preferable to use either a SimpleArcPeerManager
188 /// a SimpleRefPeerManager, for conciseness. See their documentation for more details, but
189 /// essentially you should default to using a SimpleRefPeerManager, and use a
190 /// SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when
191 /// you're using lightning-net-tokio.
192 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref, L: Deref> where CM::Target: msgs::ChannelMessageHandler, L::Target: Logger {
193         message_handler: MessageHandler<CM>,
194         peers: Mutex<PeerHolder<Descriptor>>,
195         our_node_secret: SecretKey,
196         ephemeral_key_midstate: Sha256Engine,
197
198         // Usize needs to be at least 32 bits to avoid overflowing both low and high. If usize is 64
199         // bits we will never realistically count into high:
200         peer_counter_low: AtomicUsize,
201         peer_counter_high: AtomicUsize,
202
203         logger: L,
204 }
205
206 macro_rules! encode_msg {
207         ($msg: expr) => {{
208                 let mut buffer = VecWriter(Vec::new());
209                 wire::write($msg, &mut buffer).unwrap();
210                 buffer.0
211         }}
212 }
213
214 /// Manages and reacts to connection events. You probably want to use file descriptors as PeerIds.
215 /// PeerIds may repeat, but only after socket_disconnected() has been called.
216 impl<Descriptor: SocketDescriptor, CM: Deref, L: Deref> PeerManager<Descriptor, CM, L> where CM::Target: msgs::ChannelMessageHandler, L::Target: Logger {
217         /// Constructs a new PeerManager with the given message handlers and node_id secret key
218         /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
219         /// cryptographically secure random bytes.
220         pub fn new(message_handler: MessageHandler<CM>, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> PeerManager<Descriptor, CM, L> {
221                 let mut ephemeral_key_midstate = Sha256::engine();
222                 ephemeral_key_midstate.input(ephemeral_random_data);
223
224                 PeerManager {
225                         message_handler,
226                         peers: Mutex::new(PeerHolder {
227                                 peers: HashMap::new(),
228                                 peers_needing_send: HashSet::new(),
229                                 node_id_to_descriptor: HashMap::new()
230                         }),
231                         our_node_secret,
232                         ephemeral_key_midstate,
233                         peer_counter_low: AtomicUsize::new(0),
234                         peer_counter_high: AtomicUsize::new(0),
235                         logger,
236                 }
237         }
238
239         /// Get the list of node ids for peers which have completed the initial handshake.
240         ///
241         /// For outbound connections, this will be the same as the their_node_id parameter passed in to
242         /// new_outbound_connection, however entries will only appear once the initial handshake has
243         /// completed and we are sure the remote peer has the private key for the given node_id.
244         pub fn get_peer_node_ids(&self) -> Vec<PublicKey> {
245                 let peers = self.peers.lock().unwrap();
246                 peers.peers.values().filter_map(|p| {
247                         if !p.channel_encryptor.is_ready_for_encryption() || p.their_features.is_none() {
248                                 return None;
249                         }
250                         p.their_node_id
251                 }).collect()
252         }
253
254         fn get_ephemeral_key(&self) -> SecretKey {
255                 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
256                 let low = self.peer_counter_low.fetch_add(1, Ordering::AcqRel);
257                 let high = if low == 0 {
258                         self.peer_counter_high.fetch_add(1, Ordering::AcqRel)
259                 } else {
260                         self.peer_counter_high.load(Ordering::Acquire)
261                 };
262                 ephemeral_hash.input(&byte_utils::le64_to_array(low as u64));
263                 ephemeral_hash.input(&byte_utils::le64_to_array(high as u64));
264                 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!")
265         }
266
267         /// Indicates a new outbound connection has been established to a node with the given node_id.
268         /// Note that if an Err is returned here you MUST NOT call socket_disconnected for the new
269         /// descriptor but must disconnect the connection immediately.
270         ///
271         /// Returns a small number of bytes to send to the remote node (currently always 50).
272         ///
273         /// Panics if descriptor is duplicative with some other descriptor which has not yet had a
274         /// socket_disconnected().
275         pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor) -> Result<Vec<u8>, PeerHandleError> {
276                 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
277                 let res = peer_encryptor.get_act_one().to_vec();
278                 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
279
280                 let mut peers = self.peers.lock().unwrap();
281                 if peers.peers.insert(descriptor, Peer {
282                         channel_encryptor: peer_encryptor,
283                         outbound: true,
284                         their_node_id: None,
285                         their_features: None,
286
287                         pending_outbound_buffer: LinkedList::new(),
288                         pending_outbound_buffer_first_msg_offset: 0,
289                         awaiting_write_event: false,
290
291                         pending_read_buffer: pending_read_buffer,
292                         pending_read_buffer_pos: 0,
293                         pending_read_is_header: false,
294
295                         sync_status: InitSyncTracker::NoSyncRequested,
296
297                         awaiting_pong: false,
298                 }).is_some() {
299                         panic!("PeerManager driver duplicated descriptors!");
300                 };
301                 Ok(res)
302         }
303
304         /// Indicates a new inbound connection has been established.
305         ///
306         /// May refuse the connection by returning an Err, but will never write bytes to the remote end
307         /// (outbound connector always speaks first). Note that if an Err is returned here you MUST NOT
308         /// call socket_disconnected for the new descriptor but must disconnect the connection
309         /// immediately.
310         ///
311         /// Panics if descriptor is duplicative with some other descriptor which has not yet had
312         /// socket_disconnected called.
313         pub fn new_inbound_connection(&self, descriptor: Descriptor) -> Result<(), PeerHandleError> {
314                 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret);
315                 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
316
317                 let mut peers = self.peers.lock().unwrap();
318                 if peers.peers.insert(descriptor, Peer {
319                         channel_encryptor: peer_encryptor,
320                         outbound: false,
321                         their_node_id: None,
322                         their_features: None,
323
324                         pending_outbound_buffer: LinkedList::new(),
325                         pending_outbound_buffer_first_msg_offset: 0,
326                         awaiting_write_event: false,
327
328                         pending_read_buffer: pending_read_buffer,
329                         pending_read_buffer_pos: 0,
330                         pending_read_is_header: false,
331
332                         sync_status: InitSyncTracker::NoSyncRequested,
333
334                         awaiting_pong: false,
335                 }).is_some() {
336                         panic!("PeerManager driver duplicated descriptors!");
337                 };
338                 Ok(())
339         }
340
341         fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer) {
342                 macro_rules! encode_and_send_msg {
343                         ($msg: expr) => {
344                                 {
345                                         log_trace!(self.logger, "Encoding and sending sync update message of type {} to {}", $msg.type_id(), log_pubkey!(peer.their_node_id.unwrap()));
346                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!($msg)[..]));
347                                 }
348                         }
349                 }
350                 const MSG_BUFF_SIZE: usize = 10;
351                 while !peer.awaiting_write_event {
352                         if peer.pending_outbound_buffer.len() < MSG_BUFF_SIZE {
353                                 match peer.sync_status {
354                                         InitSyncTracker::NoSyncRequested => {},
355                                         InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
356                                                 let steps = ((MSG_BUFF_SIZE - peer.pending_outbound_buffer.len() + 2) / 3) as u8;
357                                                 let all_messages = self.message_handler.route_handler.get_next_channel_announcements(c, steps);
358                                                 for &(ref announce, ref update_a_option, ref update_b_option) in all_messages.iter() {
359                                                         encode_and_send_msg!(announce);
360                                                         if let &Some(ref update_a) = update_a_option {
361                                                                 encode_and_send_msg!(update_a);
362                                                         }
363                                                         if let &Some(ref update_b) = update_b_option {
364                                                                 encode_and_send_msg!(update_b);
365                                                         }
366                                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
367                                                 }
368                                                 if all_messages.is_empty() || all_messages.len() != steps as usize {
369                                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
370                                                 }
371                                         },
372                                         InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
373                                                 let steps = (MSG_BUFF_SIZE - peer.pending_outbound_buffer.len()) as u8;
374                                                 let all_messages = self.message_handler.route_handler.get_next_node_announcements(None, steps);
375                                                 for msg in all_messages.iter() {
376                                                         encode_and_send_msg!(msg);
377                                                         peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
378                                                 }
379                                                 if all_messages.is_empty() || all_messages.len() != steps as usize {
380                                                         peer.sync_status = InitSyncTracker::NoSyncRequested;
381                                                 }
382                                         },
383                                         InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
384                                         InitSyncTracker::NodesSyncing(key) => {
385                                                 let steps = (MSG_BUFF_SIZE - peer.pending_outbound_buffer.len()) as u8;
386                                                 let all_messages = self.message_handler.route_handler.get_next_node_announcements(Some(&key), steps);
387                                                 for msg in all_messages.iter() {
388                                                         encode_and_send_msg!(msg);
389                                                         peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
390                                                 }
391                                                 if all_messages.is_empty() || all_messages.len() != steps as usize {
392                                                         peer.sync_status = InitSyncTracker::NoSyncRequested;
393                                                 }
394                                         },
395                                 }
396                         }
397
398                         if {
399                                 let next_buff = match peer.pending_outbound_buffer.front() {
400                                         None => return,
401                                         Some(buff) => buff,
402                                 };
403
404                                 let should_be_reading = peer.pending_outbound_buffer.len() < MSG_BUFF_SIZE;
405                                 let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
406                                 let data_sent = descriptor.send_data(pending, should_be_reading);
407                                 peer.pending_outbound_buffer_first_msg_offset += data_sent;
408                                 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() { true } else { false }
409                         } {
410                                 peer.pending_outbound_buffer_first_msg_offset = 0;
411                                 peer.pending_outbound_buffer.pop_front();
412                         } else {
413                                 peer.awaiting_write_event = true;
414                         }
415                 }
416         }
417
418         /// Indicates that there is room to write data to the given socket descriptor.
419         ///
420         /// May return an Err to indicate that the connection should be closed.
421         ///
422         /// Will most likely call send_data on the descriptor passed in (or the descriptor handed into
423         /// new_*\_connection) before returning. Thus, be very careful with reentrancy issues! The
424         /// invariants around calling write_buffer_space_avail in case a write did not fully complete
425         /// must still hold - be ready to call write_buffer_space_avail again if a write call generated
426         /// here isn't sufficient! Panics if the descriptor was not previously registered in a
427         /// new_\*_connection event.
428         pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
429                 let mut peers = self.peers.lock().unwrap();
430                 match peers.peers.get_mut(descriptor) {
431                         None => panic!("Descriptor for write_event is not already known to PeerManager"),
432                         Some(peer) => {
433                                 peer.awaiting_write_event = false;
434                                 self.do_attempt_write_data(descriptor, peer);
435                         }
436                 };
437                 Ok(())
438         }
439
440         /// Indicates that data was read from the given socket descriptor.
441         ///
442         /// May return an Err to indicate that the connection should be closed.
443         ///
444         /// Will *not* call back into send_data on any descriptors to avoid reentrancy complexity.
445         /// Thus, however, you almost certainly want to call process_events() after any read_event to
446         /// generate send_data calls to handle responses.
447         ///
448         /// If Ok(true) is returned, further read_events should not be triggered until a send_data call
449         /// on this file descriptor has resume_read set (preventing DoS issues in the send buffer).
450         ///
451         /// Panics if the descriptor was not previously registered in a new_*_connection event.
452         pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
453                 match self.do_read_event(peer_descriptor, data) {
454                         Ok(res) => Ok(res),
455                         Err(e) => {
456                                 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
457                                 Err(e)
458                         }
459                 }
460         }
461
462         /// Append a message to a peer's pending outbound/write buffer, and update the map of peers needing sends accordingly.
463         fn enqueue_message<M: Encode + Writeable>(&self, peers_needing_send: &mut HashSet<Descriptor>, peer: &mut Peer, descriptor: Descriptor, message: &M) {
464                 let mut buffer = VecWriter(Vec::new());
465                 wire::write(message, &mut buffer).unwrap(); // crash if the write failed
466                 let encoded_message = buffer.0;
467
468                 log_trace!(self.logger, "Enqueueing message of type {} to {}", message.type_id(), log_pubkey!(peer.their_node_id.unwrap()));
469                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_message[..]));
470                 peers_needing_send.insert(descriptor);
471         }
472
473         fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
474                 let pause_read = {
475                         let mut peers_lock = self.peers.lock().unwrap();
476                         let peers = &mut *peers_lock;
477                         let pause_read = match peers.peers.get_mut(peer_descriptor) {
478                                 None => panic!("Descriptor for read_event is not already known to PeerManager"),
479                                 Some(peer) => {
480                                         assert!(peer.pending_read_buffer.len() > 0);
481                                         assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
482
483                                         let mut read_pos = 0;
484                                         while read_pos < data.len() {
485                                                 {
486                                                         let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
487                                                         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]);
488                                                         read_pos += data_to_copy;
489                                                         peer.pending_read_buffer_pos += data_to_copy;
490                                                 }
491
492                                                 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
493                                                         peer.pending_read_buffer_pos = 0;
494
495                                                         macro_rules! try_potential_handleerror {
496                                                                 ($thing: expr) => {
497                                                                         match $thing {
498                                                                                 Ok(x) => x,
499                                                                                 Err(e) => {
500                                                                                         match e.action {
501                                                                                                 msgs::ErrorAction::DisconnectPeer { msg: _ } => {
502                                                                                                         //TODO: Try to push msg
503                                                                                                         log_trace!(self.logger, "Got Err handling message, disconnecting peer because {}", e.err);
504                                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
505                                                                                                 },
506                                                                                                 msgs::ErrorAction::IgnoreError => {
507                                                                                                         log_trace!(self.logger, "Got Err handling message, ignoring because {}", e.err);
508                                                                                                         continue;
509                                                                                                 },
510                                                                                                 msgs::ErrorAction::SendErrorMessage { msg } => {
511                                                                                                         log_trace!(self.logger, "Got Err handling message, sending Error message because {}", e.err);
512                                                                                                         self.enqueue_message(&mut peers.peers_needing_send, peer, peer_descriptor.clone(), &msg);
513                                                                                                         continue;
514                                                                                                 },
515                                                                                         }
516                                                                                 }
517                                                                         };
518                                                                 }
519                                                         }
520
521                                                         macro_rules! insert_node_id {
522                                                                 () => {
523                                                                         match peers.node_id_to_descriptor.entry(peer.their_node_id.unwrap()) {
524                                                                                 hash_map::Entry::Occupied(_) => {
525                                                                                         log_trace!(self.logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap()));
526                                                                                         peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
527                                                                                         return Err(PeerHandleError{ no_connection_possible: false })
528                                                                                 },
529                                                                                 hash_map::Entry::Vacant(entry) => {
530                                                                                         log_trace!(self.logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap()));
531                                                                                         entry.insert(peer_descriptor.clone())
532                                                                                 },
533                                                                         };
534                                                                 }
535                                                         }
536
537                                                         let next_step = peer.channel_encryptor.get_noise_step();
538                                                         match next_step {
539                                                                 NextNoiseStep::ActOne => {
540                                                                         let act_two = try_potential_handleerror!(peer.channel_encryptor.process_act_one_with_keys(&peer.pending_read_buffer[..], &self.our_node_secret, self.get_ephemeral_key())).to_vec();
541                                                                         peer.pending_outbound_buffer.push_back(act_two);
542                                                                         peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
543                                                                 },
544                                                                 NextNoiseStep::ActTwo => {
545                                                                         let (act_three, their_node_id) = try_potential_handleerror!(peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], &self.our_node_secret));
546                                                                         peer.pending_outbound_buffer.push_back(act_three.to_vec());
547                                                                         peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
548                                                                         peer.pending_read_is_header = true;
549
550                                                                         peer.their_node_id = Some(their_node_id);
551                                                                         insert_node_id!();
552                                                                         let mut features = InitFeatures::known();
553                                                                         if !self.message_handler.route_handler.should_request_full_sync(&peer.their_node_id.unwrap()) {
554                                                                                 features.clear_initial_routing_sync();
555                                                                         }
556
557                                                                         let resp = msgs::Init { features };
558                                                                         self.enqueue_message(&mut peers.peers_needing_send, peer, peer_descriptor.clone(), &resp);
559                                                                 },
560                                                                 NextNoiseStep::ActThree => {
561                                                                         let their_node_id = try_potential_handleerror!(peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
562                                                                         peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
563                                                                         peer.pending_read_is_header = true;
564                                                                         peer.their_node_id = Some(their_node_id);
565                                                                         insert_node_id!();
566                                                                 },
567                                                                 NextNoiseStep::NoiseComplete => {
568                                                                         if peer.pending_read_is_header {
569                                                                                 let msg_len = try_potential_handleerror!(peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
570                                                                                 peer.pending_read_buffer = Vec::with_capacity(msg_len as usize + 16);
571                                                                                 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
572                                                                                 if msg_len < 2 { // Need at least the message type tag
573                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
574                                                                                 }
575                                                                                 peer.pending_read_is_header = false;
576                                                                         } else {
577                                                                                 let msg_data = try_potential_handleerror!(peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
578                                                                                 assert!(msg_data.len() >= 2);
579
580                                                                                 // Reset read buffer
581                                                                                 peer.pending_read_buffer = [0; 18].to_vec();
582                                                                                 peer.pending_read_is_header = true;
583
584                                                                                 let mut reader = ::std::io::Cursor::new(&msg_data[..]);
585                                                                                 let message_result = wire::read(&mut reader);
586                                                                                 let message = match message_result {
587                                                                                         Ok(x) => x,
588                                                                                         Err(e) => {
589                                                                                                 match e {
590                                                                                                         msgs::DecodeError::UnknownVersion => return Err(PeerHandleError { no_connection_possible: false }),
591                                                                                                         msgs::DecodeError::UnknownRequiredFeature => {
592                                                                                                                 log_debug!(self.logger, "Got a channel/node announcement with an known required feature flag, you may want to update!");
593                                                                                                                 continue;
594                                                                                                         }
595                                                                                                         msgs::DecodeError::InvalidValue => {
596                                                                                                                 log_debug!(self.logger, "Got an invalid value while deserializing message");
597                                                                                                                 return Err(PeerHandleError { no_connection_possible: false });
598                                                                                                         }
599                                                                                                         msgs::DecodeError::ShortRead => {
600                                                                                                                 log_debug!(self.logger, "Deserialization failed due to shortness of message");
601                                                                                                                 return Err(PeerHandleError { no_connection_possible: false });
602                                                                                                         }
603                                                                                                         msgs::DecodeError::BadLengthDescriptor => return Err(PeerHandleError { no_connection_possible: false }),
604                                                                                                         msgs::DecodeError::Io(_) => return Err(PeerHandleError { no_connection_possible: false }),
605                                                                                                 }
606                                                                                         }
607                                                                                 };
608
609                                                                                 log_trace!(self.logger, "Received message of type {} from {}", message.type_id(), log_pubkey!(peer.their_node_id.unwrap()));
610
611                                                                                 // Need an Init as first message
612                                                                                 if let wire::Message::Init(_) = message {
613                                                                                 } else if peer.their_features.is_none() {
614                                                                                         log_trace!(self.logger, "Peer {} sent non-Init first message", log_pubkey!(peer.their_node_id.unwrap()));
615                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
616                                                                                 }
617
618                                                                                 match message {
619                                                                                         // Setup and Control messages:
620                                                                                         wire::Message::Init(msg) => {
621                                                                                                 if msg.features.requires_unknown_bits() {
622                                                                                                         log_info!(self.logger, "Peer global features required unknown version bits");
623                                                                                                         return Err(PeerHandleError{ no_connection_possible: true });
624                                                                                                 }
625                                                                                                 if msg.features.requires_unknown_bits() {
626                                                                                                         log_info!(self.logger, "Peer local features required unknown version bits");
627                                                                                                         return Err(PeerHandleError{ no_connection_possible: true });
628                                                                                                 }
629                                                                                                 if peer.their_features.is_some() {
630                                                                                                         return Err(PeerHandleError{ no_connection_possible: false });
631                                                                                                 }
632
633                                                                                                 log_info!(self.logger, "Received peer Init message: data_loss_protect: {}, initial_routing_sync: {}, upfront_shutdown_script: {}, static_remote_key: {}, unkown local flags: {}, unknown global flags: {}",
634                                                                                                         if msg.features.supports_data_loss_protect() { "supported" } else { "not supported"},
635                                                                                                         if msg.features.initial_routing_sync() { "requested" } else { "not requested" },
636                                                                                                         if msg.features.supports_upfront_shutdown_script() { "supported" } else { "not supported"},
637                                                                                                         if msg.features.supports_static_remote_key() { "supported" } else { "not supported"},
638                                                                                                         if msg.features.supports_unknown_bits() { "present" } else { "none" },
639                                                                                                         if msg.features.supports_unknown_bits() { "present" } else { "none" });
640
641                                                                                                 if msg.features.initial_routing_sync() {
642                                                                                                         peer.sync_status = InitSyncTracker::ChannelsSyncing(0);
643                                                                                                         peers.peers_needing_send.insert(peer_descriptor.clone());
644                                                                                                 }
645                                                                                                 if !msg.features.supports_static_remote_key() {
646                                                                                                         log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting with no_connection_possible", log_pubkey!(peer.their_node_id.unwrap()));
647                                                                                                         return Err(PeerHandleError{ no_connection_possible: true });
648                                                                                                 }
649
650                                                                                                 if !peer.outbound {
651                                                                                                         let mut features = InitFeatures::known();
652                                                                                                         if !self.message_handler.route_handler.should_request_full_sync(&peer.their_node_id.unwrap()) {
653                                                                                                                 features.clear_initial_routing_sync();
654                                                                                                         }
655
656                                                                                                         let resp = msgs::Init { features };
657                                                                                                         self.enqueue_message(&mut peers.peers_needing_send, peer, peer_descriptor.clone(), &resp);
658                                                                                                 }
659
660                                                                                                 self.message_handler.chan_handler.peer_connected(&peer.their_node_id.unwrap(), &msg);
661                                                                                                 peer.their_features = Some(msg.features);
662                                                                                         },
663                                                                                         wire::Message::Error(msg) => {
664                                                                                                 let mut data_is_printable = true;
665                                                                                                 for b in msg.data.bytes() {
666                                                                                                         if b < 32 || b > 126 {
667                                                                                                                 data_is_printable = false;
668                                                                                                                 break;
669                                                                                                         }
670                                                                                                 }
671
672                                                                                                 if data_is_printable {
673                                                                                                         log_debug!(self.logger, "Got Err message from {}: {}", log_pubkey!(peer.their_node_id.unwrap()), msg.data);
674                                                                                                 } else {
675                                                                                                         log_debug!(self.logger, "Got Err message from {} with non-ASCII error message", log_pubkey!(peer.their_node_id.unwrap()));
676                                                                                                 }
677                                                                                                 self.message_handler.chan_handler.handle_error(&peer.their_node_id.unwrap(), &msg);
678                                                                                                 if msg.channel_id == [0; 32] {
679                                                                                                         return Err(PeerHandleError{ no_connection_possible: true });
680                                                                                                 }
681                                                                                         },
682
683                                                                                         wire::Message::Ping(msg) => {
684                                                                                                 if msg.ponglen < 65532 {
685                                                                                                         let resp = msgs::Pong { byteslen: msg.ponglen };
686                                                                                                         self.enqueue_message(&mut peers.peers_needing_send, peer, peer_descriptor.clone(), &resp);
687                                                                                                 }
688                                                                                         },
689                                                                                         wire::Message::Pong(_msg) => {
690                                                                                                 peer.awaiting_pong = false;
691                                                                                         },
692
693                                                                                         // Channel messages:
694                                                                                         wire::Message::OpenChannel(msg) => {
695                                                                                                 self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg);
696                                                                                         },
697                                                                                         wire::Message::AcceptChannel(msg) => {
698                                                                                                 self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg);
699                                                                                         },
700
701                                                                                         wire::Message::FundingCreated(msg) => {
702                                                                                                 self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg);
703                                                                                         },
704                                                                                         wire::Message::FundingSigned(msg) => {
705                                                                                                 self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg);
706                                                                                         },
707                                                                                         wire::Message::FundingLocked(msg) => {
708                                                                                                 self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg);
709                                                                                         },
710
711                                                                                         wire::Message::Shutdown(msg) => {
712                                                                                                 self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), &msg);
713                                                                                         },
714                                                                                         wire::Message::ClosingSigned(msg) => {
715                                                                                                 self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg);
716                                                                                         },
717
718                                                                                         // Commitment messages:
719                                                                                         wire::Message::UpdateAddHTLC(msg) => {
720                                                                                                 self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg);
721                                                                                         },
722                                                                                         wire::Message::UpdateFulfillHTLC(msg) => {
723                                                                                                 self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg);
724                                                                                         },
725                                                                                         wire::Message::UpdateFailHTLC(msg) => {
726                                                                                                 self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg);
727                                                                                         },
728                                                                                         wire::Message::UpdateFailMalformedHTLC(msg) => {
729                                                                                                 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg);
730                                                                                         },
731
732                                                                                         wire::Message::CommitmentSigned(msg) => {
733                                                                                                 self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg);
734                                                                                         },
735                                                                                         wire::Message::RevokeAndACK(msg) => {
736                                                                                                 self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg);
737                                                                                         },
738                                                                                         wire::Message::UpdateFee(msg) => {
739                                                                                                 self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg);
740                                                                                         },
741                                                                                         wire::Message::ChannelReestablish(msg) => {
742                                                                                                 self.message_handler.chan_handler.handle_channel_reestablish(&peer.their_node_id.unwrap(), &msg);
743                                                                                         },
744
745                                                                                         // Routing messages:
746                                                                                         wire::Message::AnnouncementSignatures(msg) => {
747                                                                                                 self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg);
748                                                                                         },
749                                                                                         wire::Message::ChannelAnnouncement(msg) => {
750                                                                                                 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_announcement(&msg));
751
752                                                                                                 if should_forward {
753                                                                                                         // TODO: forward msg along to all our other peers!
754                                                                                                 }
755                                                                                         },
756                                                                                         wire::Message::NodeAnnouncement(msg) => {
757                                                                                                 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_node_announcement(&msg));
758
759                                                                                                 if should_forward {
760                                                                                                         // TODO: forward msg along to all our other peers!
761                                                                                                 }
762                                                                                         },
763                                                                                         wire::Message::ChannelUpdate(msg) => {
764                                                                                                 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_update(&msg));
765
766                                                                                                 if should_forward {
767                                                                                                         // TODO: forward msg along to all our other peers!
768                                                                                                 }
769                                                                                         },
770
771                                                                                         // Unknown messages:
772                                                                                         wire::Message::Unknown(msg_type) if msg_type.is_even() => {
773                                                                                                 log_debug!(self.logger, "Received unknown even message of type {}, disconnecting peer!", msg_type);
774                                                                                                 // Fail the channel if message is an even, unknown type as per BOLT #1.
775                                                                                                 return Err(PeerHandleError{ no_connection_possible: true });
776                                                                                         },
777                                                                                         wire::Message::Unknown(msg_type) => {
778                                                                                                 log_trace!(self.logger, "Received unknown odd message of type {}, ignoring", msg_type);
779                                                                                         },
780                                                                                 }
781                                                                         }
782                                                                 }
783                                                         }
784                                                 }
785                                         }
786
787                                         self.do_attempt_write_data(peer_descriptor, peer);
788
789                                         peer.pending_outbound_buffer.len() > 10 // pause_read
790                                 }
791                         };
792
793                         pause_read
794                 };
795
796                 Ok(pause_read)
797         }
798
799         /// Checks for any events generated by our handlers and processes them. Includes sending most
800         /// response messages as well as messages generated by calls to handler functions directly (eg
801         /// functions like ChannelManager::process_pending_htlc_forward or send_payment).
802         pub fn process_events(&self) {
803                 {
804                         // TODO: There are some DoS attacks here where you can flood someone's outbound send
805                         // buffer by doing things like announcing channels on another node. We should be willing to
806                         // drop optional-ish messages when send buffers get full!
807
808                         let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
809                         let mut peers_lock = self.peers.lock().unwrap();
810                         let peers = &mut *peers_lock;
811                         for event in events_generated.drain(..) {
812                                 macro_rules! get_peer_for_forwarding {
813                                         ($node_id: expr, $handle_no_such_peer: block) => {
814                                                 {
815                                                         let descriptor = match peers.node_id_to_descriptor.get($node_id) {
816                                                                 Some(descriptor) => descriptor.clone(),
817                                                                 None => {
818                                                                         $handle_no_such_peer;
819                                                                         continue;
820                                                                 },
821                                                         };
822                                                         match peers.peers.get_mut(&descriptor) {
823                                                                 Some(peer) => {
824                                                                         if peer.their_features.is_none() {
825                                                                                 $handle_no_such_peer;
826                                                                                 continue;
827                                                                         }
828                                                                         (descriptor, peer)
829                                                                 },
830                                                                 None => panic!("Inconsistent peers set state!"),
831                                                         }
832                                                 }
833                                         }
834                                 }
835                                 match event {
836                                         MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
837                                                 log_trace!(self.logger, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
838                                                                 log_pubkey!(node_id),
839                                                                 log_bytes!(msg.temporary_channel_id));
840                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
841                                                                 //TODO: Drop the pending channel? (or just let it timeout, but that sucks)
842                                                         });
843                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
844                                                 self.do_attempt_write_data(&mut descriptor, peer);
845                                         },
846                                         MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
847                                                 log_trace!(self.logger, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
848                                                                 log_pubkey!(node_id),
849                                                                 log_bytes!(msg.temporary_channel_id));
850                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
851                                                                 //TODO: Drop the pending channel? (or just let it timeout, but that sucks)
852                                                         });
853                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
854                                                 self.do_attempt_write_data(&mut descriptor, peer);
855                                         },
856                                         MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
857                                                 log_trace!(self.logger, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
858                                                                 log_pubkey!(node_id),
859                                                                 log_bytes!(msg.temporary_channel_id),
860                                                                 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
861                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
862                                                                 //TODO: generate a DiscardFunding event indicating to the wallet that
863                                                                 //they should just throw away this funding transaction
864                                                         });
865                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
866                                                 self.do_attempt_write_data(&mut descriptor, peer);
867                                         },
868                                         MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
869                                                 log_trace!(self.logger, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
870                                                                 log_pubkey!(node_id),
871                                                                 log_bytes!(msg.channel_id));
872                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
873                                                                 //TODO: generate a DiscardFunding event indicating to the wallet that
874                                                                 //they should just throw away this funding transaction
875                                                         });
876                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
877                                                 self.do_attempt_write_data(&mut descriptor, peer);
878                                         },
879                                         MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
880                                                 log_trace!(self.logger, "Handling SendFundingLocked event in peer_handler for node {} for channel {}",
881                                                                 log_pubkey!(node_id),
882                                                                 log_bytes!(msg.channel_id));
883                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
884                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
885                                                         });
886                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
887                                                 self.do_attempt_write_data(&mut descriptor, peer);
888                                         },
889                                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
890                                                 log_trace!(self.logger, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
891                                                                 log_pubkey!(node_id),
892                                                                 log_bytes!(msg.channel_id));
893                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
894                                                                 //TODO: generate a DiscardFunding event indicating to the wallet that
895                                                                 //they should just throw away this funding transaction
896                                                         });
897                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
898                                                 self.do_attempt_write_data(&mut descriptor, peer);
899                                         },
900                                         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 } } => {
901                                                 log_trace!(self.logger, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
902                                                                 log_pubkey!(node_id),
903                                                                 update_add_htlcs.len(),
904                                                                 update_fulfill_htlcs.len(),
905                                                                 update_fail_htlcs.len(),
906                                                                 log_bytes!(commitment_signed.channel_id));
907                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
908                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
909                                                         });
910                                                 for msg in update_add_htlcs {
911                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
912                                                 }
913                                                 for msg in update_fulfill_htlcs {
914                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
915                                                 }
916                                                 for msg in update_fail_htlcs {
917                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
918                                                 }
919                                                 for msg in update_fail_malformed_htlcs {
920                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
921                                                 }
922                                                 if let &Some(ref msg) = update_fee {
923                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
924                                                 }
925                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_signed)));
926                                                 self.do_attempt_write_data(&mut descriptor, peer);
927                                         },
928                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
929                                                 log_trace!(self.logger, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
930                                                                 log_pubkey!(node_id),
931                                                                 log_bytes!(msg.channel_id));
932                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
933                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
934                                                         });
935                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
936                                                 self.do_attempt_write_data(&mut descriptor, peer);
937                                         },
938                                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
939                                                 log_trace!(self.logger, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
940                                                                 log_pubkey!(node_id),
941                                                                 log_bytes!(msg.channel_id));
942                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
943                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
944                                                         });
945                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
946                                                 self.do_attempt_write_data(&mut descriptor, peer);
947                                         },
948                                         MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
949                                                 log_trace!(self.logger, "Handling Shutdown event in peer_handler for node {} for channel {}",
950                                                                 log_pubkey!(node_id),
951                                                                 log_bytes!(msg.channel_id));
952                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
953                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
954                                                         });
955                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
956                                                 self.do_attempt_write_data(&mut descriptor, peer);
957                                         },
958                                         MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
959                                                 log_trace!(self.logger, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
960                                                                 log_pubkey!(node_id),
961                                                                 log_bytes!(msg.channel_id));
962                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
963                                                                 //TODO: Do whatever we're gonna do for handling dropped messages
964                                                         });
965                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
966                                                 self.do_attempt_write_data(&mut descriptor, peer);
967                                         },
968                                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
969                                                 log_trace!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
970                                                 if self.message_handler.route_handler.handle_channel_announcement(msg).is_ok() && self.message_handler.route_handler.handle_channel_update(update_msg).is_ok() {
971                                                         let encoded_msg = encode_msg!(msg);
972                                                         let encoded_update_msg = encode_msg!(update_msg);
973
974                                                         for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
975                                                                 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
976                                                                                 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
977                                                                         continue
978                                                                 }
979                                                                 match peer.their_node_id {
980                                                                         None => continue,
981                                                                         Some(their_node_id) => {
982                                                                                 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
983                                                                                         continue
984                                                                                 }
985                                                                         }
986                                                                 }
987                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
988                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_update_msg[..]));
989                                                                 self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
990                                                         }
991                                                 }
992                                         },
993                                         MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
994                                                 log_trace!(self.logger, "Handling BroadcastNodeAnnouncement event in peer_handler");
995                                                 if self.message_handler.route_handler.handle_node_announcement(msg).is_ok() {
996                                                         let encoded_msg = encode_msg!(msg);
997
998                                                         for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
999                                                                 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1000                                                                                 !peer.should_forward_node_announcement(msg.contents.node_id) {
1001                                                                         continue
1002                                                                 }
1003                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
1004                                                                 self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
1005                                                         }
1006                                                 }
1007                                         },
1008                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
1009                                                 log_trace!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1010                                                 if self.message_handler.route_handler.handle_channel_update(msg).is_ok() {
1011                                                         let encoded_msg = encode_msg!(msg);
1012
1013                                                         for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
1014                                                                 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1015                                                                                 !peer.should_forward_channel_announcement(msg.contents.short_channel_id)  {
1016                                                                         continue
1017                                                                 }
1018                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
1019                                                                 self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
1020                                                         }
1021                                                 }
1022                                         },
1023                                         MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
1024                                                 self.message_handler.route_handler.handle_htlc_fail_channel_update(update);
1025                                         },
1026                                         MessageSendEvent::HandleError { ref node_id, ref action } => {
1027                                                 match *action {
1028                                                         msgs::ErrorAction::DisconnectPeer { ref msg } => {
1029                                                                 if let Some(mut descriptor) = peers.node_id_to_descriptor.remove(node_id) {
1030                                                                         peers.peers_needing_send.remove(&descriptor);
1031                                                                         if let Some(mut peer) = peers.peers.remove(&descriptor) {
1032                                                                                 if let Some(ref msg) = *msg {
1033                                                                                         log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
1034                                                                                                         log_pubkey!(node_id),
1035                                                                                                         msg.data);
1036                                                                                         peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1037                                                                                         // This isn't guaranteed to work, but if there is enough free
1038                                                                                         // room in the send buffer, put the error message there...
1039                                                                                         self.do_attempt_write_data(&mut descriptor, &mut peer);
1040                                                                                 } else {
1041                                                                                         log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with no message", log_pubkey!(node_id));
1042                                                                                 }
1043                                                                         }
1044                                                                         descriptor.disconnect_socket();
1045                                                                         self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1046                                                                 }
1047                                                         },
1048                                                         msgs::ErrorAction::IgnoreError => {},
1049                                                         msgs::ErrorAction::SendErrorMessage { ref msg } => {
1050                                                                 log_trace!(self.logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
1051                                                                                 log_pubkey!(node_id),
1052                                                                                 msg.data);
1053                                                                 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
1054                                                                         //TODO: Do whatever we're gonna do for handling dropped messages
1055                                                                 });
1056                                                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1057                                                                 self.do_attempt_write_data(&mut descriptor, peer);
1058                                                         },
1059                                                 }
1060                                         }
1061                                 }
1062                         }
1063
1064                         for mut descriptor in peers.peers_needing_send.drain() {
1065                                 match peers.peers.get_mut(&descriptor) {
1066                                         Some(peer) => self.do_attempt_write_data(&mut descriptor, peer),
1067                                         None => panic!("Inconsistent peers set state!"),
1068                                 }
1069                         }
1070                 }
1071         }
1072
1073         /// Indicates that the given socket descriptor's connection is now closed.
1074         ///
1075         /// This must only be called if the socket has been disconnected by the peer or your own
1076         /// decision to disconnect it and must NOT be called in any case where other parts of this
1077         /// library (eg PeerHandleError, explicit disconnect_socket calls) instruct you to disconnect
1078         /// the peer.
1079         ///
1080         /// Panics if the descriptor was not previously registered in a successful new_*_connection event.
1081         pub fn socket_disconnected(&self, descriptor: &Descriptor) {
1082                 self.disconnect_event_internal(descriptor, false);
1083         }
1084
1085         fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
1086                 let mut peers = self.peers.lock().unwrap();
1087                 peers.peers_needing_send.remove(descriptor);
1088                 let peer_option = peers.peers.remove(descriptor);
1089                 match peer_option {
1090                         None => panic!("Descriptor for disconnect_event is not already known to PeerManager"),
1091                         Some(peer) => {
1092                                 match peer.their_node_id {
1093                                         Some(node_id) => {
1094                                                 peers.node_id_to_descriptor.remove(&node_id);
1095                                                 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1096                                         },
1097                                         None => {}
1098                                 }
1099                         }
1100                 };
1101         }
1102
1103         /// This function should be called roughly once every 30 seconds.
1104         /// It will send pings to each peer and disconnect those which did not respond to the last round of pings.
1105
1106         /// Will most likely call send_data on all of the registered descriptors, thus, be very careful with reentrancy issues!
1107         pub fn timer_tick_occured(&self) {
1108                 let mut peers_lock = self.peers.lock().unwrap();
1109                 {
1110                         let peers = &mut *peers_lock;
1111                         let peers_needing_send = &mut peers.peers_needing_send;
1112                         let node_id_to_descriptor = &mut peers.node_id_to_descriptor;
1113                         let peers = &mut peers.peers;
1114                         let mut descriptors_needing_disconnect = Vec::new();
1115
1116                         peers.retain(|descriptor, peer| {
1117                                 if peer.awaiting_pong {
1118                                         peers_needing_send.remove(descriptor);
1119                                         descriptors_needing_disconnect.push(descriptor.clone());
1120                                         match peer.their_node_id {
1121                                                 Some(node_id) => {
1122                                                         log_trace!(self.logger, "Disconnecting peer with id {} due to ping timeout", node_id);
1123                                                         node_id_to_descriptor.remove(&node_id);
1124                                                         self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1125                                                 }
1126                                                 None => {
1127                                                         // This can't actually happen as we should have hit
1128                                                         // is_ready_for_encryption() previously on this same peer.
1129                                                         unreachable!();
1130                                                 },
1131                                         }
1132                                         return false;
1133                                 }
1134
1135                                 if !peer.channel_encryptor.is_ready_for_encryption() {
1136                                         // The peer needs to complete its handshake before we can exchange messages
1137                                         return true;
1138                                 }
1139
1140                                 let ping = msgs::Ping {
1141                                         ponglen: 0,
1142                                         byteslen: 64,
1143                                 };
1144                                 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(&ping)));
1145
1146                                 let mut descriptor_clone = descriptor.clone();
1147                                 self.do_attempt_write_data(&mut descriptor_clone, peer);
1148
1149                                 peer.awaiting_pong = true;
1150                                 true
1151                         });
1152
1153                         for mut descriptor in descriptors_needing_disconnect.drain(..) {
1154                                 descriptor.disconnect_socket();
1155                         }
1156                 }
1157         }
1158 }
1159
1160 #[cfg(test)]
1161 mod tests {
1162         use bitcoin::secp256k1::Signature;
1163         use bitcoin::BitcoinHash;
1164         use bitcoin::network::constants::Network;
1165         use bitcoin::blockdata::constants::genesis_block;
1166         use ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor};
1167         use ln::msgs;
1168         use ln::features::ChannelFeatures;
1169         use util::events;
1170         use util::test_utils;
1171
1172         use bitcoin::secp256k1::Secp256k1;
1173         use bitcoin::secp256k1::key::{SecretKey, PublicKey};
1174
1175         use rand::{thread_rng, Rng};
1176
1177         use std;
1178         use std::cmp::min;
1179         use std::sync::{Arc, Mutex};
1180         use std::sync::atomic::{AtomicUsize, Ordering};
1181
1182         #[derive(Clone)]
1183         struct FileDescriptor {
1184                 fd: u16,
1185                 outbound_data: Arc<Mutex<Vec<u8>>>,
1186         }
1187         impl PartialEq for FileDescriptor {
1188                 fn eq(&self, other: &Self) -> bool {
1189                         self.fd == other.fd
1190                 }
1191         }
1192         impl Eq for FileDescriptor { }
1193         impl std::hash::Hash for FileDescriptor {
1194                 fn hash<H: std::hash::Hasher>(&self, hasher: &mut H) {
1195                         self.fd.hash(hasher)
1196                 }
1197         }
1198
1199         impl SocketDescriptor for FileDescriptor {
1200                 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
1201                         self.outbound_data.lock().unwrap().extend_from_slice(data);
1202                         data.len()
1203                 }
1204
1205                 fn disconnect_socket(&mut self) {}
1206         }
1207
1208         struct PeerManagerCfg {
1209                 chan_handler: test_utils::TestChannelMessageHandler,
1210                 logger: test_utils::TestLogger,
1211         }
1212
1213         fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
1214                 let mut cfgs = Vec::new();
1215                 for _ in 0..peer_count {
1216                         let chan_handler = test_utils::TestChannelMessageHandler::new();
1217                         let logger = test_utils::TestLogger::new();
1218                         cfgs.push(
1219                                 PeerManagerCfg{
1220                                         chan_handler,
1221                                         logger,
1222                                 }
1223                         );
1224                 }
1225
1226                 cfgs
1227         }
1228
1229         fn create_network<'a>(peer_count: usize, cfgs: &'a Vec<PeerManagerCfg>, routing_handlers: Option<&'a Vec<Arc<msgs::RoutingMessageHandler>>>) -> Vec<PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestLogger>> {
1230                 let mut peers = Vec::new();
1231                 let mut rng = thread_rng();
1232                 let mut ephemeral_bytes = [0; 32];
1233                 rng.fill_bytes(&mut ephemeral_bytes);
1234
1235                 for i in 0..peer_count {
1236                         let router = if let Some(routers) = routing_handlers { routers[i].clone() } else {
1237                                 Arc::new(test_utils::TestRoutingMessageHandler::new())
1238                         };
1239                         let node_id = {
1240                                 let mut key_slice = [0;32];
1241                                 rng.fill_bytes(&mut key_slice);
1242                                 SecretKey::from_slice(&key_slice).unwrap()
1243                         };
1244                         let msg_handler = MessageHandler { chan_handler: &cfgs[i].chan_handler, route_handler: router };
1245                         let peer = PeerManager::new(msg_handler, node_id, &ephemeral_bytes, &cfgs[i].logger);
1246                         peers.push(peer);
1247                 }
1248
1249                 peers
1250         }
1251
1252         fn establish_connection<'a>(peer_a: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestLogger>, peer_b: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestLogger>) -> (FileDescriptor, FileDescriptor) {
1253                 let secp_ctx = Secp256k1::new();
1254                 let a_id = PublicKey::from_secret_key(&secp_ctx, &peer_a.our_node_secret);
1255                 let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1256                 let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1257                 let initial_data = peer_b.new_outbound_connection(a_id, fd_b.clone()).unwrap();
1258                 peer_a.new_inbound_connection(fd_a.clone()).unwrap();
1259                 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
1260                 assert_eq!(peer_b.read_event(&mut fd_b, &fd_a.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
1261                 assert_eq!(peer_a.read_event(&mut fd_a, &fd_b.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
1262                 (fd_a.clone(), fd_b.clone())
1263         }
1264
1265         fn establish_connection_and_read_events<'a>(peer_a: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestLogger>, peer_b: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestLogger>) -> (FileDescriptor, FileDescriptor) {
1266                 let (mut fd_a, mut fd_b) = establish_connection(peer_a, peer_b);
1267                 assert_eq!(peer_b.read_event(&mut fd_b, &fd_a.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
1268                 assert_eq!(peer_a.read_event(&mut fd_a, &fd_b.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
1269                 (fd_a.clone(), fd_b.clone())
1270         }
1271
1272         #[test]
1273         fn test_disconnect_peer() {
1274                 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
1275                 // push a DisconnectPeer event to remove the node flagged by id
1276                 let cfgs = create_peermgr_cfgs(2);
1277                 let chan_handler = test_utils::TestChannelMessageHandler::new();
1278                 let mut peers = create_network(2, &cfgs, None);
1279                 establish_connection(&peers[0], &peers[1]);
1280                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1281
1282                 let secp_ctx = Secp256k1::new();
1283                 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
1284
1285                 chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
1286                         node_id: their_id,
1287                         action: msgs::ErrorAction::DisconnectPeer { msg: None },
1288                 });
1289                 assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1);
1290                 peers[0].message_handler.chan_handler = &chan_handler;
1291
1292                 peers[0].process_events();
1293                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);
1294         }
1295
1296         #[test]
1297         fn test_timer_tick_occurred() {
1298                 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
1299                 let cfgs = create_peermgr_cfgs(2);
1300                 let peers = create_network(2, &cfgs, None);
1301                 establish_connection(&peers[0], &peers[1]);
1302                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1303
1304                 // peers[0] awaiting_pong is set to true, but the Peer is still connected
1305                 peers[0].timer_tick_occured();
1306                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1307
1308                 // Since timer_tick_occured() is called again when awaiting_pong is true, all Peers are disconnected
1309                 peers[0].timer_tick_occured();
1310                 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);
1311         }
1312
1313         pub struct TestRoutingMessageHandler {
1314                 pub chan_upds_recvd: AtomicUsize,
1315                 pub chan_anns_recvd: AtomicUsize,
1316                 pub chan_anns_sent: AtomicUsize,
1317         }
1318
1319         impl TestRoutingMessageHandler {
1320                 pub fn new() -> Self {
1321                         TestRoutingMessageHandler {
1322                                 chan_upds_recvd: AtomicUsize::new(0),
1323                                 chan_anns_recvd: AtomicUsize::new(0),
1324                                 chan_anns_sent: AtomicUsize::new(0),
1325                         }
1326                 }
1327
1328         }
1329         impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
1330                 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, msgs::LightningError> {
1331                         Err(msgs::LightningError { err: "", action: msgs::ErrorAction::IgnoreError })
1332                 }
1333                 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, msgs::LightningError> {
1334                         self.chan_anns_recvd.fetch_add(1, Ordering::AcqRel);
1335                         Err(msgs::LightningError { err: "", action: msgs::ErrorAction::IgnoreError })
1336                 }
1337                 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, msgs::LightningError> {
1338                         self.chan_upds_recvd.fetch_add(1, Ordering::AcqRel);
1339                         Err(msgs::LightningError { err: "", action: msgs::ErrorAction::IgnoreError })
1340                 }
1341                 fn handle_htlc_fail_channel_update(&self, _update: &msgs::HTLCFailChannelUpdate) {}
1342                 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
1343                         let mut chan_anns = Vec::new();
1344                         const TOTAL_UPDS: u64 = 100;
1345                         let end: u64 =  min(starting_point + batch_amount as u64, TOTAL_UPDS - self.chan_anns_sent.load(Ordering::Acquire) as u64);
1346                         for i in starting_point..end {
1347                                 let chan_upd_1 = get_dummy_channel_update(i);
1348                                 let chan_upd_2 = get_dummy_channel_update(i);
1349                                 let chan_ann = get_dummy_channel_announcement(i);
1350
1351                                 chan_anns.push((chan_ann, Some(chan_upd_1), Some(chan_upd_2)));
1352                         }
1353
1354                         self.chan_anns_sent.fetch_add(chan_anns.len(), Ordering::AcqRel);
1355                         chan_anns
1356                 }
1357
1358                 fn get_next_node_announcements(&self, _starting_point: Option<&PublicKey>, _batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
1359                         Vec::new()
1360                 }
1361
1362                 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
1363                         true
1364                 }
1365         }
1366
1367         fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnouncement {
1368                 use bitcoin::secp256k1::ffi::Signature as FFISignature;
1369                 let secp_ctx = Secp256k1::new();
1370                 let network = Network::Testnet;
1371                 let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap();
1372                 let node_2_privkey = SecretKey::from_slice(&[41; 32]).unwrap();
1373                 let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
1374                 let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
1375                 let unsigned_ann = msgs::UnsignedChannelAnnouncement {
1376                         features: ChannelFeatures::known(),
1377                         chain_hash: genesis_block(network).header.bitcoin_hash(),
1378                         short_channel_id: short_chan_id,
1379                         node_id_1: PublicKey::from_secret_key(&secp_ctx, &node_1_privkey),
1380                         node_id_2: PublicKey::from_secret_key(&secp_ctx, &node_2_privkey),
1381                         bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, &node_1_btckey),
1382                         bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, &node_2_btckey),
1383                         excess_data: Vec::new(),
1384                 };
1385
1386                 msgs::ChannelAnnouncement {
1387                         node_signature_1: Signature::from(FFISignature::new()),
1388                         node_signature_2: Signature::from(FFISignature::new()),
1389                         bitcoin_signature_1: Signature::from(FFISignature::new()),
1390                         bitcoin_signature_2: Signature::from(FFISignature::new()),
1391                         contents: unsigned_ann,
1392                 }
1393         }
1394
1395         fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate {
1396                 use bitcoin::secp256k1::ffi::Signature as FFISignature;
1397                 let network = Network::Testnet;
1398                 msgs::ChannelUpdate {
1399                         signature: Signature::from(FFISignature::new()),
1400                         contents: msgs::UnsignedChannelUpdate {
1401                                 chain_hash: genesis_block(network).header.bitcoin_hash(),
1402                                 short_channel_id: short_chan_id,
1403                                 timestamp: 0,
1404                                 flags: 0,
1405                                 cltv_expiry_delta: 0,
1406                                 htlc_minimum_msat: 0,
1407                                 fee_base_msat: 0,
1408                                 fee_proportional_millionths: 0,
1409                                 excess_data: vec![],
1410                         }
1411                 }
1412         }
1413
1414         #[test]
1415         fn test_do_attempt_write_data() {
1416                 // Create 2 peers with custom TestRoutingMessageHandlers and connect them.
1417                 let cfgs = create_peermgr_cfgs(2);
1418                 let mut routing_handlers: Vec<Arc<msgs::RoutingMessageHandler>> = Vec::new();
1419                 let mut routing_handlers_concrete: Vec<Arc<TestRoutingMessageHandler>> = Vec::new();
1420                 for _ in 0..2 {
1421                         let routing_handler = Arc::new(TestRoutingMessageHandler::new());
1422                         routing_handlers.push(routing_handler.clone());
1423                         routing_handlers_concrete.push(routing_handler.clone());
1424                 }
1425                 let peers = create_network(2, &cfgs, Some(&routing_handlers));
1426
1427                 // By calling establish_connect, we trigger do_attempt_write_data between
1428                 // the peers. Previously this function would mistakenly enter an infinite loop
1429                 // when there were more channel messages available than could fit into a peer's
1430                 // buffer. This issue would now be detected by this test (because we use custom
1431                 // RoutingMessageHandlers that intentionally return more channel messages
1432                 // than can fit into a peer's buffer).
1433                 let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
1434
1435                 // Make each peer to read the messages that the other peer just wrote to them.
1436                 peers[1].read_event(&mut fd_b, &fd_a.outbound_data.lock().unwrap().split_off(0)).unwrap();
1437                 peers[0].read_event(&mut fd_a, &fd_b.outbound_data.lock().unwrap().split_off(0)).unwrap();
1438
1439                 // Check that each peer has received the expected number of channel updates and channel
1440                 // announcements.
1441                 assert_eq!(routing_handlers_concrete[0].clone().chan_upds_recvd.load(Ordering::Acquire), 100);
1442                 assert_eq!(routing_handlers_concrete[0].clone().chan_anns_recvd.load(Ordering::Acquire), 50);
1443                 assert_eq!(routing_handlers_concrete[1].clone().chan_upds_recvd.load(Ordering::Acquire), 100);
1444                 assert_eq!(routing_handlers_concrete[1].clone().chan_anns_recvd.load(Ordering::Acquire), 50);
1445         }
1446
1447         #[test]
1448         fn limit_initial_routing_sync_requests() {
1449                 // Inbound peer 0 requests initial_routing_sync, but outbound peer 1 does not.
1450                 {
1451                         let cfgs = create_peermgr_cfgs(2);
1452                         let routing_handlers: Vec<Arc<msgs::RoutingMessageHandler>> = vec![
1453                                 Arc::new(test_utils::TestRoutingMessageHandler::new().set_request_full_sync()),
1454                                 Arc::new(test_utils::TestRoutingMessageHandler::new()),
1455                         ];
1456                         let peers = create_network(2, &cfgs, Some(&routing_handlers));
1457                         let (fd_0_to_1, fd_1_to_0) = establish_connection_and_read_events(&peers[0], &peers[1]);
1458
1459                         let peer_0 = peers[0].peers.lock().unwrap();
1460                         let peer_1 = peers[1].peers.lock().unwrap();
1461
1462                         let peer_0_features = peer_1.peers.get(&fd_1_to_0).unwrap().their_features.as_ref();
1463                         let peer_1_features = peer_0.peers.get(&fd_0_to_1).unwrap().their_features.as_ref();
1464
1465                         assert!(peer_0_features.unwrap().initial_routing_sync());
1466                         assert!(!peer_1_features.unwrap().initial_routing_sync());
1467                 }
1468
1469                 // Outbound peer 1 requests initial_routing_sync, but inbound peer 0 does not.
1470                 {
1471                         let cfgs = create_peermgr_cfgs(2);
1472                         let routing_handlers: Vec<Arc<msgs::RoutingMessageHandler>> = vec![
1473                                 Arc::new(test_utils::TestRoutingMessageHandler::new()),
1474                                 Arc::new(test_utils::TestRoutingMessageHandler::new().set_request_full_sync()),
1475                         ];
1476                         let peers = create_network(2, &cfgs, Some(&routing_handlers));
1477                         let (fd_0_to_1, fd_1_to_0) = establish_connection_and_read_events(&peers[0], &peers[1]);
1478
1479                         let peer_0 = peers[0].peers.lock().unwrap();
1480                         let peer_1 = peers[1].peers.lock().unwrap();
1481
1482                         let peer_0_features = peer_1.peers.get(&fd_1_to_0).unwrap().their_features.as_ref();
1483                         let peer_1_features = peer_0.peers.get(&fd_0_to_1).unwrap().their_features.as_ref();
1484
1485                         assert!(!peer_0_features.unwrap().initial_routing_sync());
1486                         assert!(peer_1_features.unwrap().initial_routing_sync());
1487                 }
1488         }
1489 }