1 //! Top level peer message handling and socket handling logic lives here.
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 Router) with messages
7 //! they should handle, and encoding/sending response messages.
9 use secp256k1::key::{SecretKey,PublicKey};
11 use ln::features::InitFeatures;
13 use ln::msgs::ChannelMessageHandler;
14 use ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager};
15 use ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
19 use util::events::{MessageSendEvent, MessageSendEventsProvider};
20 use util::logger::Logger;
21 use util::ser::Writer;
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};
29 use bitcoin_hashes::sha256::Hash as Sha256;
30 use bitcoin_hashes::sha256::HashEngine as Sha256Engine;
31 use bitcoin_hashes::{HashEngine, Hash};
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.
38 /// A message handler which handles messages updating our knowledge of the network channel
39 /// graph. Usually this is just a Router object.
40 pub route_handler: Arc<msgs::RoutingMessageHandler>,
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.
47 /// For efficiency, Clone should be relatively cheap for this type.
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 close() itself, be
51 /// careful to ensure you don't have races whereby you might register a new connection with an fd
52 /// the same as a yet-to-be-disconnect_event()-ed.
53 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
54 /// Attempts to send some data from the given slice to the peer.
56 /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
57 /// Note that in the disconnected case, a disconnect_event must still fire and further write
58 /// attempts may occur until that time.
60 /// If the returned size is smaller than data.len(), a write_available event must
61 /// trigger the next time more data can be written. Additionally, until the a send_data event
62 /// completes fully, no further read_events should trigger on the same peer!
64 /// If a read_event on this descriptor had previously returned true (indicating that read
65 /// events should be paused to prevent DoS in the send buffer), resume_read may be set
66 /// indicating that read events on this descriptor should resume. A resume_read of false does
67 /// *not* imply that further read events should be paused.
68 fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize;
69 /// Disconnect the socket pointed to by this SocketDescriptor. Once this function returns, no
70 /// more calls to write_event, read_event or disconnect_event may be made with this descriptor.
71 /// No disconnect_event should be generated as a result of this call, though obviously races
72 /// may occur whereby disconnect_socket is called after a call to disconnect_event but prior to
73 /// that event completing.
74 fn disconnect_socket(&mut self);
77 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
78 /// generate no further read/write_events for the descriptor, only triggering a single
79 /// disconnect_event (unless it was provided in response to a new_*_connection event, in which case
80 /// no such disconnect_event must be generated and the socket be silently disconencted).
81 pub struct PeerHandleError {
82 /// Used to indicate that we probably can't make any future connections to this peer, implying
83 /// we should go ahead and force-close any channels we have with it.
84 no_connection_possible: bool,
86 impl fmt::Debug for PeerHandleError {
87 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
88 formatter.write_str("Peer Sent Invalid Data")
91 impl fmt::Display for PeerHandleError {
92 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
93 formatter.write_str("Peer Sent Invalid Data")
96 impl error::Error for PeerHandleError {
97 fn description(&self) -> &str {
98 "Peer Sent Invalid Data"
102 enum InitSyncTracker{
104 ChannelsSyncing(u64),
105 NodesSyncing(PublicKey),
109 channel_encryptor: PeerChannelEncryptor,
111 their_node_id: Option<PublicKey>,
112 their_features: Option<InitFeatures>,
114 pending_outbound_buffer: LinkedList<Vec<u8>>,
115 pending_outbound_buffer_first_msg_offset: usize,
116 awaiting_write_event: bool,
118 pending_read_buffer: Vec<u8>,
119 pending_read_buffer_pos: usize,
120 pending_read_is_header: bool,
122 sync_status: InitSyncTracker,
128 /// Returns true if the channel announcements/updates for the given channel should be
129 /// forwarded to this peer.
130 /// If we are sending our routing table to this peer and we have not yet sent channel
131 /// announcements/updates for the given channel_id then we will send it when we get to that
132 /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
133 /// sent the old versions, we should send the update, and so return true here.
134 fn should_forward_channel(&self, channel_id: u64)->bool{
135 match self.sync_status {
136 InitSyncTracker::NoSyncRequested => true,
137 InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
138 InitSyncTracker::NodesSyncing(_) => true,
143 struct PeerHolder<Descriptor: SocketDescriptor> {
144 peers: HashMap<Descriptor, Peer>,
145 /// Added to by do_read_event for cases where we pushed a message onto the send buffer but
146 /// didn't call do_attempt_write_data to avoid reentrancy. Cleared in process_events()
147 peers_needing_send: HashSet<Descriptor>,
148 /// Only add to this set when noise completes:
149 node_id_to_descriptor: HashMap<PublicKey, Descriptor>,
152 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
153 fn _check_usize_is_32_or_64() {
154 // See below, less than 32 bit pointers may be unsafe here!
155 unsafe { mem::transmute::<*const usize, [u8; 4]>(panic!()); }
158 /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
159 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
160 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
161 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
162 /// issues such as overly long function definitions.
163 pub type SimpleArcPeerManager<SD, M> = Arc<PeerManager<SD, SimpleArcChannelManager<M>>>;
165 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
166 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
167 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
168 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
169 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
170 /// helps with issues such as long function definitions.
171 pub type SimpleRefPeerManager<'a, SD, M> = PeerManager<SD, SimpleRefChannelManager<'a, M>>;
173 /// A PeerManager manages a set of peers, described by their SocketDescriptor and marshalls socket
174 /// events into messages which it passes on to its MessageHandlers.
176 /// Rather than using a plain PeerManager, it is preferable to use either a SimpleArcPeerManager
177 /// a SimpleRefPeerManager, for conciseness. See their documentation for more details, but
178 /// essentially you should default to using a SimpleRefPeerManager, and use a
179 /// SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when
180 /// you're using lightning-net-tokio.
181 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref> where CM::Target: msgs::ChannelMessageHandler {
182 message_handler: MessageHandler<CM>,
183 peers: Mutex<PeerHolder<Descriptor>>,
184 our_node_secret: SecretKey,
185 ephemeral_key_midstate: Sha256Engine,
187 // Usize needs to be at least 32 bits to avoid overflowing both low and high. If usize is 64
188 // bits we will never realistically count into high:
189 peer_counter_low: AtomicUsize,
190 peer_counter_high: AtomicUsize,
195 struct VecWriter(Vec<u8>);
196 impl Writer for VecWriter {
197 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
198 self.0.extend_from_slice(buf);
201 fn size_hint(&mut self, size: usize) {
202 self.0.reserve_exact(size);
206 macro_rules! encode_msg {
208 let mut buffer = VecWriter(Vec::new());
209 wire::write($msg, &mut buffer).unwrap();
214 /// Manages and reacts to connection events. You probably want to use file descriptors as PeerIds.
215 /// PeerIds may repeat, but only after disconnect_event() has been called.
216 impl<Descriptor: SocketDescriptor, CM: Deref> PeerManager<Descriptor, CM> where CM::Target: msgs::ChannelMessageHandler {
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: Arc<Logger>) -> PeerManager<Descriptor, CM> {
221 let mut ephemeral_key_midstate = Sha256::engine();
222 ephemeral_key_midstate.input(ephemeral_random_data);
225 message_handler: message_handler,
226 peers: Mutex::new(PeerHolder {
227 peers: HashMap::new(),
228 peers_needing_send: HashSet::new(),
229 node_id_to_descriptor: HashMap::new()
231 our_node_secret: our_node_secret,
232 ephemeral_key_midstate,
233 peer_counter_low: AtomicUsize::new(0),
234 peer_counter_high: AtomicUsize::new(0),
239 /// Get the list of node ids for peers which have completed the initial handshake.
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() {
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)
260 self.peer_counter_high.load(Ordering::Acquire)
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!")
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 disconnect_event for the new
269 /// descriptor but must disconnect the connection immediately.
271 /// Returns a small number of bytes to send to the remote node (currently always 50).
273 /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
274 /// disconnect_event.
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
280 let mut peers = self.peers.lock().unwrap();
281 if peers.peers.insert(descriptor, Peer {
282 channel_encryptor: peer_encryptor,
285 their_features: None,
287 pending_outbound_buffer: LinkedList::new(),
288 pending_outbound_buffer_first_msg_offset: 0,
289 awaiting_write_event: false,
291 pending_read_buffer: pending_read_buffer,
292 pending_read_buffer_pos: 0,
293 pending_read_is_header: false,
295 sync_status: InitSyncTracker::NoSyncRequested,
297 awaiting_pong: false,
299 panic!("PeerManager driver duplicated descriptors!");
304 /// Indicates a new inbound connection has been established.
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 disconnect_event for the new descriptor but must disconnect the connection
311 /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
312 /// disconnect_event.
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
317 let mut peers = self.peers.lock().unwrap();
318 if peers.peers.insert(descriptor, Peer {
319 channel_encryptor: peer_encryptor,
322 their_features: None,
324 pending_outbound_buffer: LinkedList::new(),
325 pending_outbound_buffer_first_msg_offset: 0,
326 awaiting_write_event: false,
328 pending_read_buffer: pending_read_buffer,
329 pending_read_buffer_pos: 0,
330 pending_read_is_header: false,
332 sync_status: InitSyncTracker::NoSyncRequested,
334 awaiting_pong: false,
336 panic!("PeerManager driver duplicated descriptors!");
341 fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer) {
342 macro_rules! encode_and_send_msg {
345 log_trace!(self, "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)[..]));
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(0, steps);
358 for &(ref announce, ref update_a, ref update_b) in all_messages.iter() {
359 encode_and_send_msg!(announce);
360 encode_and_send_msg!(update_a);
361 encode_and_send_msg!(update_b);
362 peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
364 if all_messages.is_empty() || all_messages.len() != steps as usize {
365 peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
368 InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
369 let steps = (MSG_BUFF_SIZE - peer.pending_outbound_buffer.len()) as u8;
370 let all_messages = self.message_handler.route_handler.get_next_node_announcements(None, steps);
371 for msg in all_messages.iter() {
372 encode_and_send_msg!(msg);
373 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
375 if all_messages.is_empty() || all_messages.len() != steps as usize {
376 peer.sync_status = InitSyncTracker::NoSyncRequested;
379 InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
380 InitSyncTracker::NodesSyncing(key) => {
381 let steps = (MSG_BUFF_SIZE - peer.pending_outbound_buffer.len()) as u8;
382 let all_messages = self.message_handler.route_handler.get_next_node_announcements(Some(&key), steps);
383 for msg in all_messages.iter() {
384 encode_and_send_msg!(msg);
385 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
387 if all_messages.is_empty() || all_messages.len() != steps as usize {
388 peer.sync_status = InitSyncTracker::NoSyncRequested;
395 let next_buff = match peer.pending_outbound_buffer.front() {
400 let should_be_reading = peer.pending_outbound_buffer.len() < MSG_BUFF_SIZE;
401 let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
402 let data_sent = descriptor.send_data(pending, should_be_reading);
403 peer.pending_outbound_buffer_first_msg_offset += data_sent;
404 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() { true } else { false }
406 peer.pending_outbound_buffer_first_msg_offset = 0;
407 peer.pending_outbound_buffer.pop_front();
409 peer.awaiting_write_event = true;
414 /// Indicates that there is room to write data to the given socket descriptor.
416 /// May return an Err to indicate that the connection should be closed.
418 /// Will most likely call send_data on the descriptor passed in (or the descriptor handed into
419 /// new_*\_connection) before returning. Thus, be very careful with reentrancy issues! The
420 /// invariants around calling write_event in case a write did not fully complete must still
421 /// hold - be ready to call write_event again if a write call generated here isn't sufficient!
422 /// Panics if the descriptor was not previously registered in a new_\*_connection event.
423 pub fn write_event(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
424 let mut peers = self.peers.lock().unwrap();
425 match peers.peers.get_mut(descriptor) {
426 None => panic!("Descriptor for write_event is not already known to PeerManager"),
428 peer.awaiting_write_event = false;
429 self.do_attempt_write_data(descriptor, peer);
435 /// Indicates that data was read from the given socket descriptor.
437 /// May return an Err to indicate that the connection should be closed.
439 /// Will *not* call back into send_data on any descriptors to avoid reentrancy complexity.
440 /// Thus, however, you almost certainly want to call process_events() after any read_event to
441 /// generate send_data calls to handle responses.
443 /// If Ok(true) is returned, further read_events should not be triggered until a write_event on
444 /// this file descriptor has resume_read set (preventing DoS issues in the send buffer).
446 /// Panics if the descriptor was not previously registered in a new_*_connection event.
447 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
448 match self.do_read_event(peer_descriptor, data) {
451 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
457 fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
459 let mut peers_lock = self.peers.lock().unwrap();
460 let peers = &mut *peers_lock;
461 let pause_read = match peers.peers.get_mut(peer_descriptor) {
462 None => panic!("Descriptor for read_event is not already known to PeerManager"),
464 assert!(peer.pending_read_buffer.len() > 0);
465 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
467 let mut read_pos = 0;
468 while read_pos < data.len() {
470 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
471 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]);
472 read_pos += data_to_copy;
473 peer.pending_read_buffer_pos += data_to_copy;
476 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
477 peer.pending_read_buffer_pos = 0;
479 macro_rules! encode_and_send_msg {
482 log_trace!(self, "Encoding and sending message of type {} to {}", $msg.type_id(), log_pubkey!(peer.their_node_id.unwrap()));
483 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(&$msg)[..]));
484 peers.peers_needing_send.insert(peer_descriptor.clone());
489 macro_rules! try_potential_handleerror {
495 msgs::ErrorAction::DisconnectPeer { msg: _ } => {
496 //TODO: Try to push msg
497 log_trace!(self, "Got Err handling message, disconnecting peer because {}", e.err);
498 return Err(PeerHandleError{ no_connection_possible: false });
500 msgs::ErrorAction::IgnoreError => {
501 log_trace!(self, "Got Err handling message, ignoring because {}", e.err);
504 msgs::ErrorAction::SendErrorMessage { msg } => {
505 log_trace!(self, "Got Err handling message, sending Error message because {}", e.err);
506 encode_and_send_msg!(msg);
515 macro_rules! try_potential_decodeerror {
521 msgs::DecodeError::UnknownVersion => return Err(PeerHandleError{ no_connection_possible: false }),
522 msgs::DecodeError::UnknownRequiredFeature => {
523 log_debug!(self, "Got a channel/node announcement with an known required feature flag, you may want to update!");
526 msgs::DecodeError::InvalidValue => {
527 log_debug!(self, "Got an invalid value while deserializing message");
528 return Err(PeerHandleError{ no_connection_possible: false });
530 msgs::DecodeError::ShortRead => {
531 log_debug!(self, "Deserialization failed due to shortness of message");
532 return Err(PeerHandleError{ no_connection_possible: false });
534 msgs::DecodeError::ExtraAddressesPerType => {
535 log_debug!(self, "Error decoding message, ignoring due to lnd spec incompatibility. See https://github.com/lightningnetwork/lnd/issues/1407");
538 msgs::DecodeError::BadLengthDescriptor => return Err(PeerHandleError{ no_connection_possible: false }),
539 msgs::DecodeError::Io(_) => return Err(PeerHandleError{ no_connection_possible: false }),
546 macro_rules! insert_node_id {
548 match peers.node_id_to_descriptor.entry(peer.their_node_id.unwrap()) {
549 hash_map::Entry::Occupied(_) => {
550 log_trace!(self, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap()));
551 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
552 return Err(PeerHandleError{ no_connection_possible: false })
554 hash_map::Entry::Vacant(entry) => {
555 log_trace!(self, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap()));
556 entry.insert(peer_descriptor.clone())
562 let next_step = peer.channel_encryptor.get_noise_step();
564 NextNoiseStep::ActOne => {
565 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();
566 peer.pending_outbound_buffer.push_back(act_two);
567 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
569 NextNoiseStep::ActTwo => {
570 let (act_three, their_node_id) = try_potential_handleerror!(peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], &self.our_node_secret));
571 peer.pending_outbound_buffer.push_back(act_three.to_vec());
572 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
573 peer.pending_read_is_header = true;
575 peer.their_node_id = Some(their_node_id);
577 let mut features = InitFeatures::supported();
578 if self.message_handler.route_handler.should_request_full_sync(&peer.their_node_id.unwrap()) {
579 features.set_initial_routing_sync();
582 let resp = msgs::Init { features };
583 encode_and_send_msg!(resp);
585 NextNoiseStep::ActThree => {
586 let their_node_id = try_potential_handleerror!(peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
587 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
588 peer.pending_read_is_header = true;
589 peer.their_node_id = Some(their_node_id);
592 NextNoiseStep::NoiseComplete => {
593 if peer.pending_read_is_header {
594 let msg_len = try_potential_handleerror!(peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
595 peer.pending_read_buffer = Vec::with_capacity(msg_len as usize + 16);
596 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
597 if msg_len < 2 { // Need at least the message type tag
598 return Err(PeerHandleError{ no_connection_possible: false });
600 peer.pending_read_is_header = false;
602 let msg_data = try_potential_handleerror!(peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
603 assert!(msg_data.len() >= 2);
606 peer.pending_read_buffer = [0; 18].to_vec();
607 peer.pending_read_is_header = true;
609 let mut reader = ::std::io::Cursor::new(&msg_data[..]);
610 let message = try_potential_decodeerror!(wire::read(&mut reader));
611 log_trace!(self, "Received message of type {} from {}", message.type_id(), log_pubkey!(peer.their_node_id.unwrap()));
613 // Need an Init as first message
614 if let wire::Message::Init(_) = message {
615 } else if peer.their_features.is_none() {
616 log_trace!(self, "Peer {} sent non-Init first message", log_pubkey!(peer.their_node_id.unwrap()));
617 return Err(PeerHandleError{ no_connection_possible: false });
621 // Setup and Control messages:
622 wire::Message::Init(msg) => {
623 if msg.features.requires_unknown_bits() {
624 log_info!(self, "Peer global features required unknown version bits");
625 return Err(PeerHandleError{ no_connection_possible: true });
627 if msg.features.requires_unknown_bits() {
628 log_info!(self, "Peer local features required unknown version bits");
629 return Err(PeerHandleError{ no_connection_possible: true });
631 if peer.their_features.is_some() {
632 return Err(PeerHandleError{ no_connection_possible: false });
635 log_info!(self, "Received peer Init message: data_loss_protect: {}, initial_routing_sync: {}, upfront_shutdown_script: {}, unkown local flags: {}, unknown global flags: {}",
636 if msg.features.supports_data_loss_protect() { "supported" } else { "not supported"},
637 if msg.features.initial_routing_sync() { "requested" } else { "not requested" },
638 if msg.features.supports_upfront_shutdown_script() { "supported" } else { "not supported"},
639 if msg.features.supports_unknown_bits() { "present" } else { "none" },
640 if msg.features.supports_unknown_bits() { "present" } else { "none" });
642 if msg.features.initial_routing_sync() {
643 peer.sync_status = InitSyncTracker::ChannelsSyncing(0);
644 peers.peers_needing_send.insert(peer_descriptor.clone());
648 let mut features = InitFeatures::supported();
649 if self.message_handler.route_handler.should_request_full_sync(&peer.their_node_id.unwrap()) {
650 features.set_initial_routing_sync();
653 let resp = msgs::Init { features };
654 encode_and_send_msg!(resp);
657 self.message_handler.chan_handler.peer_connected(&peer.their_node_id.unwrap(), &msg);
658 peer.their_features = Some(msg.features);
660 wire::Message::Error(msg) => {
661 let mut data_is_printable = true;
662 for b in msg.data.bytes() {
663 if b < 32 || b > 126 {
664 data_is_printable = false;
669 if data_is_printable {
670 log_debug!(self, "Got Err message from {}: {}", log_pubkey!(peer.their_node_id.unwrap()), msg.data);
672 log_debug!(self, "Got Err message from {} with non-ASCII error message", log_pubkey!(peer.their_node_id.unwrap()));
674 self.message_handler.chan_handler.handle_error(&peer.their_node_id.unwrap(), &msg);
675 if msg.channel_id == [0; 32] {
676 return Err(PeerHandleError{ no_connection_possible: true });
680 wire::Message::Ping(msg) => {
681 if msg.ponglen < 65532 {
682 let resp = msgs::Pong { byteslen: msg.ponglen };
683 encode_and_send_msg!(resp);
686 wire::Message::Pong(_msg) => {
687 peer.awaiting_pong = false;
691 wire::Message::OpenChannel(msg) => {
692 self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg);
694 wire::Message::AcceptChannel(msg) => {
695 self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg);
698 wire::Message::FundingCreated(msg) => {
699 self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg);
701 wire::Message::FundingSigned(msg) => {
702 self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg);
704 wire::Message::FundingLocked(msg) => {
705 self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg);
708 wire::Message::Shutdown(msg) => {
709 self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), &msg);
711 wire::Message::ClosingSigned(msg) => {
712 self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg);
715 // Commitment messages:
716 wire::Message::UpdateAddHTLC(msg) => {
717 self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg);
719 wire::Message::UpdateFulfillHTLC(msg) => {
720 self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg);
722 wire::Message::UpdateFailHTLC(msg) => {
723 self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg);
725 wire::Message::UpdateFailMalformedHTLC(msg) => {
726 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg);
729 wire::Message::CommitmentSigned(msg) => {
730 self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg);
732 wire::Message::RevokeAndACK(msg) => {
733 self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg);
735 wire::Message::UpdateFee(msg) => {
736 self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg);
738 wire::Message::ChannelReestablish(msg) => {
739 self.message_handler.chan_handler.handle_channel_reestablish(&peer.their_node_id.unwrap(), &msg);
743 wire::Message::AnnouncementSignatures(msg) => {
744 self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg);
746 wire::Message::ChannelAnnouncement(msg) => {
747 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_announcement(&msg));
750 // TODO: forward msg along to all our other peers!
753 wire::Message::NodeAnnouncement(msg) => {
754 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_node_announcement(&msg));
757 // TODO: forward msg along to all our other peers!
760 wire::Message::ChannelUpdate(msg) => {
761 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_update(&msg));
764 // TODO: forward msg along to all our other peers!
769 wire::Message::Unknown(msg_type) if msg_type.is_even() => {
770 // Fail the channel if message is an even, unknown type as per BOLT #1.
771 return Err(PeerHandleError{ no_connection_possible: true });
773 wire::Message::Unknown(_) => {},
781 self.do_attempt_write_data(peer_descriptor, peer);
783 peer.pending_outbound_buffer.len() > 10 // pause_read
793 /// Checks for any events generated by our handlers and processes them. Includes sending most
794 /// response messages as well as messages generated by calls to handler functions directly (eg
795 /// functions like ChannelManager::process_pending_htlc_forward or send_payment).
796 pub fn process_events(&self) {
798 // TODO: There are some DoS attacks here where you can flood someone's outbound send
799 // buffer by doing things like announcing channels on another node. We should be willing to
800 // drop optional-ish messages when send buffers get full!
802 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
803 let mut peers_lock = self.peers.lock().unwrap();
804 let peers = &mut *peers_lock;
805 for event in events_generated.drain(..) {
806 macro_rules! get_peer_for_forwarding {
807 ($node_id: expr, $handle_no_such_peer: block) => {
809 let descriptor = match peers.node_id_to_descriptor.get($node_id) {
810 Some(descriptor) => descriptor.clone(),
812 $handle_no_such_peer;
816 match peers.peers.get_mut(&descriptor) {
818 if peer.their_features.is_none() {
819 $handle_no_such_peer;
824 None => panic!("Inconsistent peers set state!"),
830 MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
831 log_trace!(self, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
832 log_pubkey!(node_id),
833 log_bytes!(msg.temporary_channel_id));
834 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
835 //TODO: Drop the pending channel? (or just let it timeout, but that sucks)
837 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
838 self.do_attempt_write_data(&mut descriptor, peer);
840 MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
841 log_trace!(self, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
842 log_pubkey!(node_id),
843 log_bytes!(msg.temporary_channel_id));
844 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
845 //TODO: Drop the pending channel? (or just let it timeout, but that sucks)
847 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
848 self.do_attempt_write_data(&mut descriptor, peer);
850 MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
851 log_trace!(self, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
852 log_pubkey!(node_id),
853 log_bytes!(msg.temporary_channel_id),
854 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
855 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
856 //TODO: generate a DiscardFunding event indicating to the wallet that
857 //they should just throw away this funding transaction
859 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
860 self.do_attempt_write_data(&mut descriptor, peer);
862 MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
863 log_trace!(self, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
864 log_pubkey!(node_id),
865 log_bytes!(msg.channel_id));
866 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
867 //TODO: generate a DiscardFunding event indicating to the wallet that
868 //they should just throw away this funding transaction
870 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
871 self.do_attempt_write_data(&mut descriptor, peer);
873 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
874 log_trace!(self, "Handling SendFundingLocked event in peer_handler for node {} for channel {}",
875 log_pubkey!(node_id),
876 log_bytes!(msg.channel_id));
877 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
878 //TODO: Do whatever we're gonna do for handling dropped messages
880 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
881 self.do_attempt_write_data(&mut descriptor, peer);
883 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
884 log_trace!(self, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
885 log_pubkey!(node_id),
886 log_bytes!(msg.channel_id));
887 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
888 //TODO: generate a DiscardFunding event indicating to the wallet that
889 //they should just throw away this funding transaction
891 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
892 self.do_attempt_write_data(&mut descriptor, peer);
894 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 } } => {
895 log_trace!(self, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
896 log_pubkey!(node_id),
897 update_add_htlcs.len(),
898 update_fulfill_htlcs.len(),
899 update_fail_htlcs.len(),
900 log_bytes!(commitment_signed.channel_id));
901 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
902 //TODO: Do whatever we're gonna do for handling dropped messages
904 for msg in update_add_htlcs {
905 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
907 for msg in update_fulfill_htlcs {
908 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
910 for msg in update_fail_htlcs {
911 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
913 for msg in update_fail_malformed_htlcs {
914 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
916 if let &Some(ref msg) = update_fee {
917 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
919 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_signed)));
920 self.do_attempt_write_data(&mut descriptor, peer);
922 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
923 log_trace!(self, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
924 log_pubkey!(node_id),
925 log_bytes!(msg.channel_id));
926 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
927 //TODO: Do whatever we're gonna do for handling dropped messages
929 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
930 self.do_attempt_write_data(&mut descriptor, peer);
932 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
933 log_trace!(self, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
934 log_pubkey!(node_id),
935 log_bytes!(msg.channel_id));
936 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
937 //TODO: Do whatever we're gonna do for handling dropped messages
939 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
940 self.do_attempt_write_data(&mut descriptor, peer);
942 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
943 log_trace!(self, "Handling Shutdown event in peer_handler for node {} for channel {}",
944 log_pubkey!(node_id),
945 log_bytes!(msg.channel_id));
946 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
947 //TODO: Do whatever we're gonna do for handling dropped messages
949 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
950 self.do_attempt_write_data(&mut descriptor, peer);
952 MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
953 log_trace!(self, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
954 log_pubkey!(node_id),
955 log_bytes!(msg.channel_id));
956 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
957 //TODO: Do whatever we're gonna do for handling dropped messages
959 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
960 self.do_attempt_write_data(&mut descriptor, peer);
962 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
963 log_trace!(self, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
964 if self.message_handler.route_handler.handle_channel_announcement(msg).is_ok() && self.message_handler.route_handler.handle_channel_update(update_msg).is_ok() {
965 let encoded_msg = encode_msg!(msg);
966 let encoded_update_msg = encode_msg!(update_msg);
968 for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
969 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
970 !peer.should_forward_channel(msg.contents.short_channel_id) {
973 match peer.their_node_id {
975 Some(their_node_id) => {
976 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
981 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
982 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_update_msg[..]));
983 self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
987 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
988 log_trace!(self, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
989 if self.message_handler.route_handler.handle_channel_update(msg).is_ok() {
990 let encoded_msg = encode_msg!(msg);
992 for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
993 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
994 !peer.should_forward_channel(msg.contents.short_channel_id) {
997 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
998 self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
1002 MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
1003 self.message_handler.route_handler.handle_htlc_fail_channel_update(update);
1005 MessageSendEvent::HandleError { ref node_id, ref action } => {
1007 msgs::ErrorAction::DisconnectPeer { ref msg } => {
1008 if let Some(mut descriptor) = peers.node_id_to_descriptor.remove(node_id) {
1009 peers.peers_needing_send.remove(&descriptor);
1010 if let Some(mut peer) = peers.peers.remove(&descriptor) {
1011 if let Some(ref msg) = *msg {
1012 log_trace!(self, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
1013 log_pubkey!(node_id),
1015 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1016 // This isn't guaranteed to work, but if there is enough free
1017 // room in the send buffer, put the error message there...
1018 self.do_attempt_write_data(&mut descriptor, &mut peer);
1020 log_trace!(self, "Handling DisconnectPeer HandleError event in peer_handler for node {} with no message", log_pubkey!(node_id));
1023 descriptor.disconnect_socket();
1024 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1027 msgs::ErrorAction::IgnoreError => {},
1028 msgs::ErrorAction::SendErrorMessage { ref msg } => {
1029 log_trace!(self, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
1030 log_pubkey!(node_id),
1032 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
1033 //TODO: Do whatever we're gonna do for handling dropped messages
1035 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1036 self.do_attempt_write_data(&mut descriptor, peer);
1043 for mut descriptor in peers.peers_needing_send.drain() {
1044 match peers.peers.get_mut(&descriptor) {
1045 Some(peer) => self.do_attempt_write_data(&mut descriptor, peer),
1046 None => panic!("Inconsistent peers set state!"),
1052 /// Indicates that the given socket descriptor's connection is now closed.
1054 /// This must be called even if a PeerHandleError was given for a read_event or write_event,
1055 /// but must NOT be called if a PeerHandleError was provided out of a new_\*\_connection event!
1057 /// Panics if the descriptor was not previously registered in a successful new_*_connection event.
1058 pub fn disconnect_event(&self, descriptor: &Descriptor) {
1059 self.disconnect_event_internal(descriptor, false);
1062 fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
1063 let mut peers = self.peers.lock().unwrap();
1064 peers.peers_needing_send.remove(descriptor);
1065 let peer_option = peers.peers.remove(descriptor);
1067 None => panic!("Descriptor for disconnect_event is not already known to PeerManager"),
1069 match peer.their_node_id {
1071 peers.node_id_to_descriptor.remove(&node_id);
1072 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1080 /// This function should be called roughly once every 30 seconds.
1081 /// It will send pings to each peer and disconnect those which did not respond to the last round of pings.
1083 /// Will most likely call send_data on all of the registered descriptors, thus, be very careful with reentrancy issues!
1084 pub fn timer_tick_occured(&self) {
1085 let mut peers_lock = self.peers.lock().unwrap();
1087 let peers = &mut *peers_lock;
1088 let peers_needing_send = &mut peers.peers_needing_send;
1089 let node_id_to_descriptor = &mut peers.node_id_to_descriptor;
1090 let peers = &mut peers.peers;
1092 peers.retain(|descriptor, peer| {
1093 if peer.awaiting_pong == true {
1094 peers_needing_send.remove(descriptor);
1095 match peer.their_node_id {
1097 node_id_to_descriptor.remove(&node_id);
1098 self.message_handler.chan_handler.peer_disconnected(&node_id, true);
1104 let ping = msgs::Ping {
1108 peer.pending_outbound_buffer.push_back(encode_msg!(&ping));
1109 let mut descriptor_clone = descriptor.clone();
1110 self.do_attempt_write_data(&mut descriptor_clone, peer);
1112 if peer.awaiting_pong {
1113 false // Drop the peer
1115 peer.awaiting_pong = true;
1125 use ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor};
1128 use util::test_utils;
1129 use util::logger::Logger;
1131 use secp256k1::Secp256k1;
1132 use secp256k1::key::{SecretKey, PublicKey};
1134 use rand::{thread_rng, Rng};
1136 use std::sync::{Arc};
1138 #[derive(PartialEq, Eq, Clone, Hash)]
1139 struct FileDescriptor {
1143 impl SocketDescriptor for FileDescriptor {
1144 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
1148 fn disconnect_socket(&mut self) {}
1151 fn create_chan_handlers(peer_count: usize) -> Vec<test_utils::TestChannelMessageHandler> {
1152 let mut chan_handlers = Vec::new();
1153 for _ in 0..peer_count {
1154 let chan_handler = test_utils::TestChannelMessageHandler::new();
1155 chan_handlers.push(chan_handler);
1161 fn create_network<'a>(peer_count: usize, chan_handlers: &'a Vec<test_utils::TestChannelMessageHandler>) -> Vec<PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler>> {
1162 let mut peers = Vec::new();
1163 let mut rng = thread_rng();
1164 let logger : Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1165 let mut ephemeral_bytes = [0; 32];
1166 rng.fill_bytes(&mut ephemeral_bytes);
1168 for i in 0..peer_count {
1169 let router = test_utils::TestRoutingMessageHandler::new();
1171 let mut key_slice = [0;32];
1172 rng.fill_bytes(&mut key_slice);
1173 SecretKey::from_slice(&key_slice).unwrap()
1175 let msg_handler = MessageHandler { chan_handler: &chan_handlers[i], route_handler: Arc::new(router) };
1176 let peer = PeerManager::new(msg_handler, node_id, &ephemeral_bytes, Arc::clone(&logger));
1183 fn establish_connection<'a>(peer_a: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler>, peer_b: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler>) {
1184 let secp_ctx = Secp256k1::new();
1185 let their_id = PublicKey::from_secret_key(&secp_ctx, &peer_b.our_node_secret);
1186 let fd = FileDescriptor { fd: 1};
1187 peer_a.new_inbound_connection(fd.clone()).unwrap();
1188 peer_a.peers.lock().unwrap().node_id_to_descriptor.insert(their_id, fd.clone());
1192 fn test_disconnect_peer() {
1193 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
1194 // push a DisconnectPeer event to remove the node flagged by id
1195 let chan_handlers = create_chan_handlers(2);
1196 let chan_handler = test_utils::TestChannelMessageHandler::new();
1197 let mut peers = create_network(2, &chan_handlers);
1198 establish_connection(&peers[0], &peers[1]);
1199 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1201 let secp_ctx = Secp256k1::new();
1202 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
1204 chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
1206 action: msgs::ErrorAction::DisconnectPeer { msg: None },
1208 assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1);
1209 peers[0].message_handler.chan_handler = &chan_handler;
1211 peers[0].process_events();
1212 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);
1215 fn test_timer_tick_occured(){
1216 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
1217 let chan_handlers = create_chan_handlers(2);
1218 let peers = create_network(2, &chan_handlers);
1219 establish_connection(&peers[0], &peers[1]);
1220 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1222 // peers[0] awaiting_pong is set to true, but the Peer is still connected
1223 peers[0].timer_tick_occured();
1224 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1226 // Since timer_tick_occured() is called again when awaiting_pong is true, all Peers are disconnected
1227 peers[0].timer_tick_occured();
1228 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);