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 util::ser::VecWriter;
16 use ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
20 use util::events::{MessageSendEvent, MessageSendEventsProvider};
21 use util::logger::Logger;
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 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.
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.
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!
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);
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,
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")
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")
98 impl error::Error for PeerHandleError {
99 fn description(&self) -> &str {
100 "Peer Sent Invalid Data"
104 enum InitSyncTracker{
106 ChannelsSyncing(u64),
107 NodesSyncing(PublicKey),
111 channel_encryptor: PeerChannelEncryptor,
113 their_node_id: Option<PublicKey>,
114 their_features: Option<InitFeatures>,
116 pending_outbound_buffer: LinkedList<Vec<u8>>,
117 pending_outbound_buffer_first_msg_offset: usize,
118 awaiting_write_event: bool,
120 pending_read_buffer: Vec<u8>,
121 pending_read_buffer_pos: usize,
122 pending_read_is_header: bool,
124 sync_status: InitSyncTracker,
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(&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,
145 struct PeerHolder<Descriptor: SocketDescriptor> {
146 peers: HashMap<Descriptor, Peer>,
147 /// Added to by do_read_event for cases where we pushed a message onto the send buffer but
148 /// didn't call do_attempt_write_data to avoid reentrancy. Cleared in process_events()
149 peers_needing_send: HashSet<Descriptor>,
150 /// Only add to this set when noise completes:
151 node_id_to_descriptor: HashMap<PublicKey, Descriptor>,
154 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
155 fn _check_usize_is_32_or_64() {
156 // See below, less than 32 bit pointers may be unsafe here!
157 unsafe { mem::transmute::<*const usize, [u8; 4]>(panic!()); }
160 /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
161 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
162 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
163 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
164 /// issues such as overly long function definitions.
165 pub type SimpleArcPeerManager<SD, M, T> = Arc<PeerManager<SD, SimpleArcChannelManager<M, T>>>;
167 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
168 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
169 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
170 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
171 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
172 /// helps with issues such as long function definitions.
173 pub type SimpleRefPeerManager<'a, 'b, SD, M, T> = PeerManager<SD, SimpleRefChannelManager<'a, 'b, M, T>>;
175 /// A PeerManager manages a set of peers, described by their SocketDescriptor and marshalls socket
176 /// events into messages which it passes on to its MessageHandlers.
178 /// Rather than using a plain PeerManager, it is preferable to use either a SimpleArcPeerManager
179 /// a SimpleRefPeerManager, for conciseness. See their documentation for more details, but
180 /// essentially you should default to using a SimpleRefPeerManager, and use a
181 /// SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when
182 /// you're using lightning-net-tokio.
183 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref> where CM::Target: msgs::ChannelMessageHandler {
184 message_handler: MessageHandler<CM>,
185 peers: Mutex<PeerHolder<Descriptor>>,
186 our_node_secret: SecretKey,
187 ephemeral_key_midstate: Sha256Engine,
189 // Usize needs to be at least 32 bits to avoid overflowing both low and high. If usize is 64
190 // bits we will never realistically count into high:
191 peer_counter_low: AtomicUsize,
192 peer_counter_high: AtomicUsize,
197 macro_rules! encode_msg {
199 let mut buffer = VecWriter(Vec::new());
200 wire::write($msg, &mut buffer).unwrap();
205 /// Manages and reacts to connection events. You probably want to use file descriptors as PeerIds.
206 /// PeerIds may repeat, but only after socket_disconnected() has been called.
207 impl<Descriptor: SocketDescriptor, CM: Deref> PeerManager<Descriptor, CM> where CM::Target: msgs::ChannelMessageHandler {
208 /// Constructs a new PeerManager with the given message handlers and node_id secret key
209 /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
210 /// cryptographically secure random bytes.
211 pub fn new(message_handler: MessageHandler<CM>, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: Arc<Logger>) -> PeerManager<Descriptor, CM> {
212 let mut ephemeral_key_midstate = Sha256::engine();
213 ephemeral_key_midstate.input(ephemeral_random_data);
216 message_handler: message_handler,
217 peers: Mutex::new(PeerHolder {
218 peers: HashMap::new(),
219 peers_needing_send: HashSet::new(),
220 node_id_to_descriptor: HashMap::new()
222 our_node_secret: our_node_secret,
223 ephemeral_key_midstate,
224 peer_counter_low: AtomicUsize::new(0),
225 peer_counter_high: AtomicUsize::new(0),
230 /// Get the list of node ids for peers which have completed the initial handshake.
232 /// For outbound connections, this will be the same as the their_node_id parameter passed in to
233 /// new_outbound_connection, however entries will only appear once the initial handshake has
234 /// completed and we are sure the remote peer has the private key for the given node_id.
235 pub fn get_peer_node_ids(&self) -> Vec<PublicKey> {
236 let peers = self.peers.lock().unwrap();
237 peers.peers.values().filter_map(|p| {
238 if !p.channel_encryptor.is_ready_for_encryption() || p.their_features.is_none() {
245 fn get_ephemeral_key(&self) -> SecretKey {
246 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
247 let low = self.peer_counter_low.fetch_add(1, Ordering::AcqRel);
248 let high = if low == 0 {
249 self.peer_counter_high.fetch_add(1, Ordering::AcqRel)
251 self.peer_counter_high.load(Ordering::Acquire)
253 ephemeral_hash.input(&byte_utils::le64_to_array(low as u64));
254 ephemeral_hash.input(&byte_utils::le64_to_array(high as u64));
255 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!")
258 /// Indicates a new outbound connection has been established to a node with the given node_id.
259 /// Note that if an Err is returned here you MUST NOT call socket_disconnected for the new
260 /// descriptor but must disconnect the connection immediately.
262 /// Returns a small number of bytes to send to the remote node (currently always 50).
264 /// Panics if descriptor is duplicative with some other descriptor which has not yet had a
265 /// socket_disconnected().
266 pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor) -> Result<Vec<u8>, PeerHandleError> {
267 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
268 let res = peer_encryptor.get_act_one().to_vec();
269 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
271 let mut peers = self.peers.lock().unwrap();
272 if peers.peers.insert(descriptor, Peer {
273 channel_encryptor: peer_encryptor,
276 their_features: None,
278 pending_outbound_buffer: LinkedList::new(),
279 pending_outbound_buffer_first_msg_offset: 0,
280 awaiting_write_event: false,
282 pending_read_buffer: pending_read_buffer,
283 pending_read_buffer_pos: 0,
284 pending_read_is_header: false,
286 sync_status: InitSyncTracker::NoSyncRequested,
288 awaiting_pong: false,
290 panic!("PeerManager driver duplicated descriptors!");
295 /// Indicates a new inbound connection has been established.
297 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
298 /// (outbound connector always speaks first). Note that if an Err is returned here you MUST NOT
299 /// call socket_disconnected for the new descriptor but must disconnect the connection
302 /// Panics if descriptor is duplicative with some other descriptor which has not yet had
303 /// socket_disconnected called.
304 pub fn new_inbound_connection(&self, descriptor: Descriptor) -> Result<(), PeerHandleError> {
305 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret);
306 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
308 let mut peers = self.peers.lock().unwrap();
309 if peers.peers.insert(descriptor, Peer {
310 channel_encryptor: peer_encryptor,
313 their_features: None,
315 pending_outbound_buffer: LinkedList::new(),
316 pending_outbound_buffer_first_msg_offset: 0,
317 awaiting_write_event: false,
319 pending_read_buffer: pending_read_buffer,
320 pending_read_buffer_pos: 0,
321 pending_read_is_header: false,
323 sync_status: InitSyncTracker::NoSyncRequested,
325 awaiting_pong: false,
327 panic!("PeerManager driver duplicated descriptors!");
332 fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer) {
333 macro_rules! encode_and_send_msg {
336 log_trace!(self, "Encoding and sending sync update message of type {} to {}", $msg.type_id(), log_pubkey!(peer.their_node_id.unwrap()));
337 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!($msg)[..]));
341 const MSG_BUFF_SIZE: usize = 10;
342 while !peer.awaiting_write_event {
343 if peer.pending_outbound_buffer.len() < MSG_BUFF_SIZE {
344 match peer.sync_status {
345 InitSyncTracker::NoSyncRequested => {},
346 InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
347 let steps = ((MSG_BUFF_SIZE - peer.pending_outbound_buffer.len() + 2) / 3) as u8;
348 let all_messages = self.message_handler.route_handler.get_next_channel_announcements(0, steps);
349 for &(ref announce, ref update_a, ref update_b) in all_messages.iter() {
350 encode_and_send_msg!(announce);
351 encode_and_send_msg!(update_a);
352 encode_and_send_msg!(update_b);
353 peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
355 if all_messages.is_empty() || all_messages.len() != steps as usize {
356 peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
359 InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
360 let steps = (MSG_BUFF_SIZE - peer.pending_outbound_buffer.len()) as u8;
361 let all_messages = self.message_handler.route_handler.get_next_node_announcements(None, steps);
362 for msg in all_messages.iter() {
363 encode_and_send_msg!(msg);
364 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
366 if all_messages.is_empty() || all_messages.len() != steps as usize {
367 peer.sync_status = InitSyncTracker::NoSyncRequested;
370 InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
371 InitSyncTracker::NodesSyncing(key) => {
372 let steps = (MSG_BUFF_SIZE - peer.pending_outbound_buffer.len()) as u8;
373 let all_messages = self.message_handler.route_handler.get_next_node_announcements(Some(&key), steps);
374 for msg in all_messages.iter() {
375 encode_and_send_msg!(msg);
376 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
378 if all_messages.is_empty() || all_messages.len() != steps as usize {
379 peer.sync_status = InitSyncTracker::NoSyncRequested;
386 let next_buff = match peer.pending_outbound_buffer.front() {
391 let should_be_reading = peer.pending_outbound_buffer.len() < MSG_BUFF_SIZE;
392 let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
393 let data_sent = descriptor.send_data(pending, should_be_reading);
394 peer.pending_outbound_buffer_first_msg_offset += data_sent;
395 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() { true } else { false }
397 peer.pending_outbound_buffer_first_msg_offset = 0;
398 peer.pending_outbound_buffer.pop_front();
400 peer.awaiting_write_event = true;
405 /// Indicates that there is room to write data to the given socket descriptor.
407 /// May return an Err to indicate that the connection should be closed.
409 /// Will most likely call send_data on the descriptor passed in (or the descriptor handed into
410 /// new_*\_connection) before returning. Thus, be very careful with reentrancy issues! The
411 /// invariants around calling write_buffer_space_avail in case a write did not fully complete
412 /// must still hold - be ready to call write_buffer_space_avail again if a write call generated
413 /// here isn't sufficient! Panics if the descriptor was not previously registered in a
414 /// new_\*_connection event.
415 pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
416 let mut peers = self.peers.lock().unwrap();
417 match peers.peers.get_mut(descriptor) {
418 None => panic!("Descriptor for write_event is not already known to PeerManager"),
420 peer.awaiting_write_event = false;
421 self.do_attempt_write_data(descriptor, peer);
427 /// Indicates that data was read from the given socket descriptor.
429 /// May return an Err to indicate that the connection should be closed.
431 /// Will *not* call back into send_data on any descriptors to avoid reentrancy complexity.
432 /// Thus, however, you almost certainly want to call process_events() after any read_event to
433 /// generate send_data calls to handle responses.
435 /// If Ok(true) is returned, further read_events should not be triggered until a send_data call
436 /// on this file descriptor has resume_read set (preventing DoS issues in the send buffer).
438 /// Panics if the descriptor was not previously registered in a new_*_connection event.
439 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
440 match self.do_read_event(peer_descriptor, data) {
443 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
449 fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
451 let mut peers_lock = self.peers.lock().unwrap();
452 let peers = &mut *peers_lock;
453 let pause_read = match peers.peers.get_mut(peer_descriptor) {
454 None => panic!("Descriptor for read_event is not already known to PeerManager"),
456 assert!(peer.pending_read_buffer.len() > 0);
457 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
459 let mut read_pos = 0;
460 while read_pos < data.len() {
462 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
463 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]);
464 read_pos += data_to_copy;
465 peer.pending_read_buffer_pos += data_to_copy;
468 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
469 peer.pending_read_buffer_pos = 0;
471 macro_rules! encode_and_send_msg {
474 log_trace!(self, "Encoding and sending message of type {} to {}", $msg.type_id(), log_pubkey!(peer.their_node_id.unwrap()));
475 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(&$msg)[..]));
476 peers.peers_needing_send.insert(peer_descriptor.clone());
481 macro_rules! try_potential_handleerror {
487 msgs::ErrorAction::DisconnectPeer { msg: _ } => {
488 //TODO: Try to push msg
489 log_trace!(self, "Got Err handling message, disconnecting peer because {}", e.err);
490 return Err(PeerHandleError{ no_connection_possible: false });
492 msgs::ErrorAction::IgnoreError => {
493 log_trace!(self, "Got Err handling message, ignoring because {}", e.err);
496 msgs::ErrorAction::SendErrorMessage { msg } => {
497 log_trace!(self, "Got Err handling message, sending Error message because {}", e.err);
498 encode_and_send_msg!(msg);
507 macro_rules! insert_node_id {
509 match peers.node_id_to_descriptor.entry(peer.their_node_id.unwrap()) {
510 hash_map::Entry::Occupied(_) => {
511 log_trace!(self, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap()));
512 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
513 return Err(PeerHandleError{ no_connection_possible: false })
515 hash_map::Entry::Vacant(entry) => {
516 log_trace!(self, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap()));
517 entry.insert(peer_descriptor.clone())
523 let next_step = peer.channel_encryptor.get_noise_step();
525 NextNoiseStep::ActOne => {
526 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();
527 peer.pending_outbound_buffer.push_back(act_two);
528 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
530 NextNoiseStep::ActTwo => {
531 let (act_three, their_node_id) = try_potential_handleerror!(peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], &self.our_node_secret));
532 peer.pending_outbound_buffer.push_back(act_three.to_vec());
533 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
534 peer.pending_read_is_header = true;
536 peer.their_node_id = Some(their_node_id);
538 let mut features = InitFeatures::supported();
539 if self.message_handler.route_handler.should_request_full_sync(&peer.their_node_id.unwrap()) {
540 features.set_initial_routing_sync();
543 let resp = msgs::Init { features };
544 encode_and_send_msg!(resp);
546 NextNoiseStep::ActThree => {
547 let their_node_id = try_potential_handleerror!(peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
548 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
549 peer.pending_read_is_header = true;
550 peer.their_node_id = Some(their_node_id);
553 NextNoiseStep::NoiseComplete => {
554 if peer.pending_read_is_header {
555 let msg_len = try_potential_handleerror!(peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
556 peer.pending_read_buffer = Vec::with_capacity(msg_len as usize + 16);
557 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
558 if msg_len < 2 { // Need at least the message type tag
559 return Err(PeerHandleError{ no_connection_possible: false });
561 peer.pending_read_is_header = false;
563 let msg_data = try_potential_handleerror!(peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
564 assert!(msg_data.len() >= 2);
567 peer.pending_read_buffer = [0; 18].to_vec();
568 peer.pending_read_is_header = true;
570 let mut reader = ::std::io::Cursor::new(&msg_data[..]);
571 let message_result = wire::read(&mut reader);
572 let message = match message_result {
576 msgs::DecodeError::UnknownVersion => return Err(PeerHandleError { no_connection_possible: false }),
577 msgs::DecodeError::UnknownRequiredFeature => {
578 log_debug!(self, "Got a channel/node announcement with an known required feature flag, you may want to update!");
581 msgs::DecodeError::InvalidValue => {
582 log_debug!(self, "Got an invalid value while deserializing message");
583 return Err(PeerHandleError { no_connection_possible: false });
585 msgs::DecodeError::ShortRead => {
586 log_debug!(self, "Deserialization failed due to shortness of message");
587 return Err(PeerHandleError { no_connection_possible: false });
589 msgs::DecodeError::ExtraAddressesPerType => {
590 log_debug!(self, "Error decoding message, ignoring due to lnd spec incompatibility. See https://github.com/lightningnetwork/lnd/issues/1407");
593 msgs::DecodeError::BadLengthDescriptor => return Err(PeerHandleError { no_connection_possible: false }),
594 msgs::DecodeError::Io(_) => return Err(PeerHandleError { no_connection_possible: false }),
599 log_trace!(self, "Received message of type {} from {}", message.type_id(), log_pubkey!(peer.their_node_id.unwrap()));
601 // Need an Init as first message
602 if let wire::Message::Init(_) = message {
603 } else if peer.their_features.is_none() {
604 log_trace!(self, "Peer {} sent non-Init first message", log_pubkey!(peer.their_node_id.unwrap()));
605 return Err(PeerHandleError{ no_connection_possible: false });
609 // Setup and Control messages:
610 wire::Message::Init(msg) => {
611 if msg.features.requires_unknown_bits() {
612 log_info!(self, "Peer global features required unknown version bits");
613 return Err(PeerHandleError{ no_connection_possible: true });
615 if msg.features.requires_unknown_bits() {
616 log_info!(self, "Peer local features required unknown version bits");
617 return Err(PeerHandleError{ no_connection_possible: true });
619 if peer.their_features.is_some() {
620 return Err(PeerHandleError{ no_connection_possible: false });
623 log_info!(self, "Received peer Init message: data_loss_protect: {}, initial_routing_sync: {}, upfront_shutdown_script: {}, unkown local flags: {}, unknown global flags: {}",
624 if msg.features.supports_data_loss_protect() { "supported" } else { "not supported"},
625 if msg.features.initial_routing_sync() { "requested" } else { "not requested" },
626 if msg.features.supports_upfront_shutdown_script() { "supported" } else { "not supported"},
627 if msg.features.supports_unknown_bits() { "present" } else { "none" },
628 if msg.features.supports_unknown_bits() { "present" } else { "none" });
630 if msg.features.initial_routing_sync() {
631 peer.sync_status = InitSyncTracker::ChannelsSyncing(0);
632 peers.peers_needing_send.insert(peer_descriptor.clone());
636 let mut features = InitFeatures::supported();
637 if self.message_handler.route_handler.should_request_full_sync(&peer.their_node_id.unwrap()) {
638 features.set_initial_routing_sync();
641 let resp = msgs::Init { features };
642 encode_and_send_msg!(resp);
645 self.message_handler.chan_handler.peer_connected(&peer.their_node_id.unwrap(), &msg);
646 peer.their_features = Some(msg.features);
648 wire::Message::Error(msg) => {
649 let mut data_is_printable = true;
650 for b in msg.data.bytes() {
651 if b < 32 || b > 126 {
652 data_is_printable = false;
657 if data_is_printable {
658 log_debug!(self, "Got Err message from {}: {}", log_pubkey!(peer.their_node_id.unwrap()), msg.data);
660 log_debug!(self, "Got Err message from {} with non-ASCII error message", log_pubkey!(peer.their_node_id.unwrap()));
662 self.message_handler.chan_handler.handle_error(&peer.their_node_id.unwrap(), &msg);
663 if msg.channel_id == [0; 32] {
664 return Err(PeerHandleError{ no_connection_possible: true });
668 wire::Message::Ping(msg) => {
669 if msg.ponglen < 65532 {
670 let resp = msgs::Pong { byteslen: msg.ponglen };
671 encode_and_send_msg!(resp);
674 wire::Message::Pong(_msg) => {
675 peer.awaiting_pong = false;
679 wire::Message::OpenChannel(msg) => {
680 self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg);
682 wire::Message::AcceptChannel(msg) => {
683 self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg);
686 wire::Message::FundingCreated(msg) => {
687 self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg);
689 wire::Message::FundingSigned(msg) => {
690 self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg);
692 wire::Message::FundingLocked(msg) => {
693 self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg);
696 wire::Message::Shutdown(msg) => {
697 self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), &msg);
699 wire::Message::ClosingSigned(msg) => {
700 self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg);
703 // Commitment messages:
704 wire::Message::UpdateAddHTLC(msg) => {
705 self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg);
707 wire::Message::UpdateFulfillHTLC(msg) => {
708 self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg);
710 wire::Message::UpdateFailHTLC(msg) => {
711 self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg);
713 wire::Message::UpdateFailMalformedHTLC(msg) => {
714 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg);
717 wire::Message::CommitmentSigned(msg) => {
718 self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg);
720 wire::Message::RevokeAndACK(msg) => {
721 self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg);
723 wire::Message::UpdateFee(msg) => {
724 self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg);
726 wire::Message::ChannelReestablish(msg) => {
727 self.message_handler.chan_handler.handle_channel_reestablish(&peer.their_node_id.unwrap(), &msg);
731 wire::Message::AnnouncementSignatures(msg) => {
732 self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg);
734 wire::Message::ChannelAnnouncement(msg) => {
735 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_announcement(&msg));
738 // TODO: forward msg along to all our other peers!
741 wire::Message::NodeAnnouncement(msg) => {
742 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_node_announcement(&msg));
745 // TODO: forward msg along to all our other peers!
748 wire::Message::ChannelUpdate(msg) => {
749 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_update(&msg));
752 // TODO: forward msg along to all our other peers!
757 wire::Message::Unknown(msg_type) if msg_type.is_even() => {
758 // Fail the channel if message is an even, unknown type as per BOLT #1.
759 return Err(PeerHandleError{ no_connection_possible: true });
761 wire::Message::Unknown(_) => {},
769 self.do_attempt_write_data(peer_descriptor, peer);
771 peer.pending_outbound_buffer.len() > 10 // pause_read
781 /// Checks for any events generated by our handlers and processes them. Includes sending most
782 /// response messages as well as messages generated by calls to handler functions directly (eg
783 /// functions like ChannelManager::process_pending_htlc_forward or send_payment).
784 pub fn process_events(&self) {
786 // TODO: There are some DoS attacks here where you can flood someone's outbound send
787 // buffer by doing things like announcing channels on another node. We should be willing to
788 // drop optional-ish messages when send buffers get full!
790 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
791 let mut peers_lock = self.peers.lock().unwrap();
792 let peers = &mut *peers_lock;
793 for event in events_generated.drain(..) {
794 macro_rules! get_peer_for_forwarding {
795 ($node_id: expr, $handle_no_such_peer: block) => {
797 let descriptor = match peers.node_id_to_descriptor.get($node_id) {
798 Some(descriptor) => descriptor.clone(),
800 $handle_no_such_peer;
804 match peers.peers.get_mut(&descriptor) {
806 if peer.their_features.is_none() {
807 $handle_no_such_peer;
812 None => panic!("Inconsistent peers set state!"),
818 MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
819 log_trace!(self, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
820 log_pubkey!(node_id),
821 log_bytes!(msg.temporary_channel_id));
822 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
823 //TODO: Drop the pending channel? (or just let it timeout, but that sucks)
825 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
826 self.do_attempt_write_data(&mut descriptor, peer);
828 MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
829 log_trace!(self, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
830 log_pubkey!(node_id),
831 log_bytes!(msg.temporary_channel_id));
832 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
833 //TODO: Drop the pending channel? (or just let it timeout, but that sucks)
835 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
836 self.do_attempt_write_data(&mut descriptor, peer);
838 MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
839 log_trace!(self, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
840 log_pubkey!(node_id),
841 log_bytes!(msg.temporary_channel_id),
842 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
843 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
844 //TODO: generate a DiscardFunding event indicating to the wallet that
845 //they should just throw away this funding transaction
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::SendFundingSigned { ref node_id, ref msg } => {
851 log_trace!(self, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
852 log_pubkey!(node_id),
853 log_bytes!(msg.channel_id));
854 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
855 //TODO: generate a DiscardFunding event indicating to the wallet that
856 //they should just throw away this funding transaction
858 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
859 self.do_attempt_write_data(&mut descriptor, peer);
861 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
862 log_trace!(self, "Handling SendFundingLocked event in peer_handler for node {} for channel {}",
863 log_pubkey!(node_id),
864 log_bytes!(msg.channel_id));
865 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
866 //TODO: Do whatever we're gonna do for handling dropped messages
868 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
869 self.do_attempt_write_data(&mut descriptor, peer);
871 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
872 log_trace!(self, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
873 log_pubkey!(node_id),
874 log_bytes!(msg.channel_id));
875 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
876 //TODO: generate a DiscardFunding event indicating to the wallet that
877 //they should just throw away this funding transaction
879 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
880 self.do_attempt_write_data(&mut descriptor, peer);
882 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 } } => {
883 log_trace!(self, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
884 log_pubkey!(node_id),
885 update_add_htlcs.len(),
886 update_fulfill_htlcs.len(),
887 update_fail_htlcs.len(),
888 log_bytes!(commitment_signed.channel_id));
889 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
890 //TODO: Do whatever we're gonna do for handling dropped messages
892 for msg in update_add_htlcs {
893 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
895 for msg in update_fulfill_htlcs {
896 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
898 for msg in update_fail_htlcs {
899 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
901 for msg in update_fail_malformed_htlcs {
902 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
904 if let &Some(ref msg) = update_fee {
905 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
907 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_signed)));
908 self.do_attempt_write_data(&mut descriptor, peer);
910 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
911 log_trace!(self, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
912 log_pubkey!(node_id),
913 log_bytes!(msg.channel_id));
914 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
915 //TODO: Do whatever we're gonna do for handling dropped messages
917 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
918 self.do_attempt_write_data(&mut descriptor, peer);
920 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
921 log_trace!(self, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
922 log_pubkey!(node_id),
923 log_bytes!(msg.channel_id));
924 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
925 //TODO: Do whatever we're gonna do for handling dropped messages
927 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
928 self.do_attempt_write_data(&mut descriptor, peer);
930 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
931 log_trace!(self, "Handling Shutdown event in peer_handler for node {} for channel {}",
932 log_pubkey!(node_id),
933 log_bytes!(msg.channel_id));
934 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
935 //TODO: Do whatever we're gonna do for handling dropped messages
937 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
938 self.do_attempt_write_data(&mut descriptor, peer);
940 MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
941 log_trace!(self, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
942 log_pubkey!(node_id),
943 log_bytes!(msg.channel_id));
944 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
945 //TODO: Do whatever we're gonna do for handling dropped messages
947 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
948 self.do_attempt_write_data(&mut descriptor, peer);
950 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
951 log_trace!(self, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
952 if self.message_handler.route_handler.handle_channel_announcement(msg).is_ok() && self.message_handler.route_handler.handle_channel_update(update_msg).is_ok() {
953 let encoded_msg = encode_msg!(msg);
954 let encoded_update_msg = encode_msg!(update_msg);
956 for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
957 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
958 !peer.should_forward_channel(msg.contents.short_channel_id) {
961 match peer.their_node_id {
963 Some(their_node_id) => {
964 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
969 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
970 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_update_msg[..]));
971 self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
975 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
976 log_trace!(self, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
977 if self.message_handler.route_handler.handle_channel_update(msg).is_ok() {
978 let encoded_msg = encode_msg!(msg);
980 for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
981 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
982 !peer.should_forward_channel(msg.contents.short_channel_id) {
985 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
986 self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
990 MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
991 self.message_handler.route_handler.handle_htlc_fail_channel_update(update);
993 MessageSendEvent::HandleError { ref node_id, ref action } => {
995 msgs::ErrorAction::DisconnectPeer { ref msg } => {
996 if let Some(mut descriptor) = peers.node_id_to_descriptor.remove(node_id) {
997 peers.peers_needing_send.remove(&descriptor);
998 if let Some(mut peer) = peers.peers.remove(&descriptor) {
999 if let Some(ref msg) = *msg {
1000 log_trace!(self, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
1001 log_pubkey!(node_id),
1003 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1004 // This isn't guaranteed to work, but if there is enough free
1005 // room in the send buffer, put the error message there...
1006 self.do_attempt_write_data(&mut descriptor, &mut peer);
1008 log_trace!(self, "Handling DisconnectPeer HandleError event in peer_handler for node {} with no message", log_pubkey!(node_id));
1011 descriptor.disconnect_socket();
1012 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1015 msgs::ErrorAction::IgnoreError => {},
1016 msgs::ErrorAction::SendErrorMessage { ref msg } => {
1017 log_trace!(self, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
1018 log_pubkey!(node_id),
1020 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
1021 //TODO: Do whatever we're gonna do for handling dropped messages
1023 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
1024 self.do_attempt_write_data(&mut descriptor, peer);
1031 for mut descriptor in peers.peers_needing_send.drain() {
1032 match peers.peers.get_mut(&descriptor) {
1033 Some(peer) => self.do_attempt_write_data(&mut descriptor, peer),
1034 None => panic!("Inconsistent peers set state!"),
1040 /// Indicates that the given socket descriptor's connection is now closed.
1042 /// This must only be called if the socket has been disconnected by the peer or your own
1043 /// decision to disconnect it and must NOT be called in any case where other parts of this
1044 /// library (eg PeerHandleError, explicit disconnect_socket calls) instruct you to disconnect
1047 /// Panics if the descriptor was not previously registered in a successful new_*_connection event.
1048 pub fn socket_disconnected(&self, descriptor: &Descriptor) {
1049 self.disconnect_event_internal(descriptor, false);
1052 fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
1053 let mut peers = self.peers.lock().unwrap();
1054 peers.peers_needing_send.remove(descriptor);
1055 let peer_option = peers.peers.remove(descriptor);
1057 None => panic!("Descriptor for disconnect_event is not already known to PeerManager"),
1059 match peer.their_node_id {
1061 peers.node_id_to_descriptor.remove(&node_id);
1062 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1070 /// This function should be called roughly once every 30 seconds.
1071 /// It will send pings to each peer and disconnect those which did not respond to the last round of pings.
1073 /// Will most likely call send_data on all of the registered descriptors, thus, be very careful with reentrancy issues!
1074 pub fn timer_tick_occured(&self) {
1075 let mut peers_lock = self.peers.lock().unwrap();
1077 let peers = &mut *peers_lock;
1078 let peers_needing_send = &mut peers.peers_needing_send;
1079 let node_id_to_descriptor = &mut peers.node_id_to_descriptor;
1080 let peers = &mut peers.peers;
1081 let mut descriptors_needing_disconnect = Vec::new();
1083 peers.retain(|descriptor, peer| {
1084 if peer.awaiting_pong {
1085 peers_needing_send.remove(descriptor);
1086 descriptors_needing_disconnect.push(descriptor.clone());
1087 match peer.their_node_id {
1089 node_id_to_descriptor.remove(&node_id);
1090 self.message_handler.chan_handler.peer_disconnected(&node_id, true);
1097 if !peer.channel_encryptor.is_ready_for_encryption() {
1098 // The peer needs to complete its handshake before we can exchange messages
1102 let ping = msgs::Ping {
1106 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(&ping)));
1108 let mut descriptor_clone = descriptor.clone();
1109 self.do_attempt_write_data(&mut descriptor_clone, peer);
1111 peer.awaiting_pong = true;
1115 for mut descriptor in descriptors_needing_disconnect.drain(..) {
1116 descriptor.disconnect_socket();
1124 use ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor};
1127 use util::test_utils;
1128 use util::logger::Logger;
1130 use secp256k1::Secp256k1;
1131 use secp256k1::key::{SecretKey, PublicKey};
1133 use rand::{thread_rng, Rng};
1136 use std::sync::{Arc, Mutex};
1139 struct FileDescriptor {
1141 outbound_data: Arc<Mutex<Vec<u8>>>,
1143 impl PartialEq for FileDescriptor {
1144 fn eq(&self, other: &Self) -> bool {
1148 impl Eq for FileDescriptor { }
1149 impl std::hash::Hash for FileDescriptor {
1150 fn hash<H: std::hash::Hasher>(&self, hasher: &mut H) {
1151 self.fd.hash(hasher)
1155 impl SocketDescriptor for FileDescriptor {
1156 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
1157 self.outbound_data.lock().unwrap().extend_from_slice(data);
1161 fn disconnect_socket(&mut self) {}
1164 fn create_chan_handlers(peer_count: usize) -> Vec<test_utils::TestChannelMessageHandler> {
1165 let mut chan_handlers = Vec::new();
1166 for _ in 0..peer_count {
1167 let chan_handler = test_utils::TestChannelMessageHandler::new();
1168 chan_handlers.push(chan_handler);
1174 fn create_network<'a>(peer_count: usize, chan_handlers: &'a Vec<test_utils::TestChannelMessageHandler>) -> Vec<PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler>> {
1175 let mut peers = Vec::new();
1176 let mut rng = thread_rng();
1177 let logger : Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1178 let mut ephemeral_bytes = [0; 32];
1179 rng.fill_bytes(&mut ephemeral_bytes);
1181 for i in 0..peer_count {
1182 let router = test_utils::TestRoutingMessageHandler::new();
1184 let mut key_slice = [0;32];
1185 rng.fill_bytes(&mut key_slice);
1186 SecretKey::from_slice(&key_slice).unwrap()
1188 let msg_handler = MessageHandler { chan_handler: &chan_handlers[i], route_handler: Arc::new(router) };
1189 let peer = PeerManager::new(msg_handler, node_id, &ephemeral_bytes, Arc::clone(&logger));
1196 fn establish_connection<'a>(peer_a: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler>, peer_b: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler>) {
1197 let secp_ctx = Secp256k1::new();
1198 let a_id = PublicKey::from_secret_key(&secp_ctx, &peer_a.our_node_secret);
1199 let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1200 let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1201 let initial_data = peer_b.new_outbound_connection(a_id, fd_b.clone()).unwrap();
1202 peer_a.new_inbound_connection(fd_a.clone()).unwrap();
1203 assert_eq!(peer_a.read_event(&mut fd_a, initial_data).unwrap(), false);
1204 assert_eq!(peer_b.read_event(&mut fd_b, fd_a.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
1205 assert_eq!(peer_a.read_event(&mut fd_a, fd_b.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
1209 fn test_disconnect_peer() {
1210 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
1211 // push a DisconnectPeer event to remove the node flagged by id
1212 let chan_handlers = create_chan_handlers(2);
1213 let chan_handler = test_utils::TestChannelMessageHandler::new();
1214 let mut peers = create_network(2, &chan_handlers);
1215 establish_connection(&peers[0], &peers[1]);
1216 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1218 let secp_ctx = Secp256k1::new();
1219 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
1221 chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
1223 action: msgs::ErrorAction::DisconnectPeer { msg: None },
1225 assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1);
1226 peers[0].message_handler.chan_handler = &chan_handler;
1228 peers[0].process_events();
1229 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);
1232 fn test_timer_tick_occured(){
1233 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
1234 let chan_handlers = create_chan_handlers(2);
1235 let peers = create_network(2, &chan_handlers);
1236 establish_connection(&peers[0], &peers[1]);
1237 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1239 // peers[0] awaiting_pong is set to true, but the Peer is still connected
1240 peers[0].timer_tick_occured();
1241 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1243 // Since timer_tick_occured() is called again when awaiting_pong is true, all Peers are disconnected
1244 peers[0].timer_tick_occured();
1245 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);