1 use secp256k1::key::{SecretKey,PublicKey};
4 use ln::msgs::{MsgEncodable,MsgDecodable};
5 use ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
7 use util::events::{EventsProvider,Event};
9 use std::collections::{HashMap,LinkedList};
10 use std::sync::{Arc, Mutex};
11 use std::{cmp,error,mem,hash,fmt};
13 pub struct MessageHandler {
14 pub chan_handler: Arc<msgs::ChannelMessageHandler>,
15 pub route_handler: Arc<msgs::RoutingMessageHandler>,
18 /// Provides an object which can be used to send data to and which uniquely identifies a connection
19 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
20 /// implement Hash to meet the PeerManager API.
21 /// For efficiency, Clone should be relatively cheap for this type.
22 /// You probably want to just extend an int and put a file descriptor in a struct and implement
24 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
25 /// Attempts to send some data from the given Vec starting at the given offset to the peer.
26 /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
27 /// Note that in the disconnected case, a disconnect_event must still fire and further write
28 /// attempts may occur until that time.
29 /// If the returned size is smaller than data.len() - write_offset, a write_available event must
30 /// trigger the next time more data can be written. Additionally, until the a send_data event
31 /// completes fully, no further read_events should trigger on the same peer!
32 /// If a read_event on this descriptor had previously returned true (indicating that read
33 /// events should be paused to prevent DoS in the send buffer), resume_read may be set
34 /// indicating that read events on this descriptor should resume. A resume_read of false does
35 /// *not* imply that further read events should be paused.
36 fn send_data(&mut self, data: &Vec<u8>, write_offset: usize, resume_read: bool) -> usize;
39 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
40 /// generate no further read/write_events for the descriptor, only triggering a single
41 /// disconnect_event (unless it was provided in response to a new_*_connection event, in which case
42 /// no such disconnect_event must be generated and the socket be silently disconencted).
43 pub struct PeerHandleError {
44 no_connection_possible: bool,
46 impl fmt::Debug for PeerHandleError {
47 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
48 formatter.write_str("Peer Sent Invalid Data")
51 impl fmt::Display for PeerHandleError {
52 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
53 formatter.write_str("Peer Sent Invalid Data")
56 impl error::Error for PeerHandleError {
57 fn description(&self) -> &str {
58 "Peer Sent Invalid Data"
63 channel_encryptor: PeerChannelEncryptor,
65 their_node_id: Option<PublicKey>,
66 their_global_features: Option<msgs::GlobalFeatures>,
67 their_local_features: Option<msgs::LocalFeatures>,
69 pending_outbound_buffer: LinkedList<Vec<u8>>,
70 pending_outbound_buffer_first_msg_offset: usize,
71 awaiting_write_event: bool,
73 pending_read_buffer: Vec<u8>,
74 pending_read_buffer_pos: usize,
75 pending_read_is_header: bool,
78 struct PeerHolder<Descriptor: SocketDescriptor> {
79 peers: HashMap<Descriptor, Peer>,
80 /// Only add to this set when noise completes:
81 node_id_to_descriptor: HashMap<PublicKey, Descriptor>,
84 pub struct PeerManager<Descriptor: SocketDescriptor> {
85 message_handler: MessageHandler,
86 peers: Mutex<PeerHolder<Descriptor>>,
87 pending_events: Mutex<Vec<Event>>,
88 our_node_secret: SecretKey,
92 macro_rules! encode_msg {
93 ($msg: expr, $msg_code: expr) => {
95 let just_msg = $msg.encode();
96 let mut encoded_msg = Vec::with_capacity(just_msg.len() + 2);
97 encoded_msg.extend_from_slice(&byte_utils::be16_to_array($msg_code));
98 encoded_msg.extend_from_slice(&just_msg[..]);
104 /// Manages and reacts to connection events. You probably want to use file descriptors as PeerIds.
105 /// PeerIds may repeat, but only after disconnect_event() has been called.
106 impl<Descriptor: SocketDescriptor> PeerManager<Descriptor> {
107 pub fn new(message_handler: MessageHandler, our_node_secret: SecretKey) -> PeerManager<Descriptor> {
109 message_handler: message_handler,
110 peers: Mutex::new(PeerHolder { peers: HashMap::new(), node_id_to_descriptor: HashMap::new() }),
111 pending_events: Mutex::new(Vec::new()),
112 our_node_secret: our_node_secret,
116 /// Indicates a new outbound connection has been established to a node with the given node_id.
117 /// Note that if an Err is returned here you MUST NOT call disconnect_event for the new
118 /// descriptor but must disconnect the connection immediately.
119 /// Returns some bytes to send to the remote node.
120 /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
121 /// disconnect_event.
122 pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor) -> Result<Vec<u8>, PeerHandleError> {
123 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone());
124 let res = peer_encryptor.get_act_one().to_vec();
125 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
127 let mut peers = self.peers.lock().unwrap();
128 if peers.peers.insert(descriptor, Peer {
129 channel_encryptor: peer_encryptor,
131 their_node_id: Some(their_node_id),
132 their_global_features: None,
133 their_local_features: None,
135 pending_outbound_buffer: LinkedList::new(),
136 pending_outbound_buffer_first_msg_offset: 0,
137 awaiting_write_event: false,
139 pending_read_buffer: pending_read_buffer,
140 pending_read_buffer_pos: 0,
141 pending_read_is_header: false,
143 panic!("PeerManager driver duplicated descriptors!");
148 /// Indicates a new inbound connection has been established.
149 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
150 /// (outbound connector always speaks first). Note that if an Err is returned here you MUST NOT
151 /// call disconnect_event for the new descriptor but must disconnect the connection
153 /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
154 /// disconnect_event.
155 pub fn new_inbound_connection(&self, descriptor: Descriptor) -> Result<(), PeerHandleError> {
156 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret);
157 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
159 let mut peers = self.peers.lock().unwrap();
160 if peers.peers.insert(descriptor, Peer {
161 channel_encryptor: peer_encryptor,
164 their_global_features: None,
165 their_local_features: None,
167 pending_outbound_buffer: LinkedList::new(),
168 pending_outbound_buffer_first_msg_offset: 0,
169 awaiting_write_event: false,
171 pending_read_buffer: pending_read_buffer,
172 pending_read_buffer_pos: 0,
173 pending_read_is_header: false,
175 panic!("PeerManager driver duplicated descriptors!");
180 fn do_attempt_write_data(descriptor: &mut Descriptor, peer: &mut Peer) {
181 while !peer.awaiting_write_event {
183 let next_buff = match peer.pending_outbound_buffer.front() {
187 let should_be_reading = peer.pending_outbound_buffer.len() < 10;
189 let data_sent = descriptor.send_data(next_buff, peer.pending_outbound_buffer_first_msg_offset, should_be_reading);
190 peer.pending_outbound_buffer_first_msg_offset += data_sent;
191 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() { true } else { false }
193 peer.pending_outbound_buffer_first_msg_offset = 0;
194 peer.pending_outbound_buffer.pop_front();
196 peer.awaiting_write_event = true;
201 /// Indicates that there is room to write data to the given socket descriptor.
202 /// May return an Err to indicate that the connection should be closed.
203 /// Will most likely call send_data on the descriptor passed in (or the descriptor handed into
204 /// new_*_connection) before returning. Thus, be very careful with reentrancy issues! The
205 /// invariants around calling write_event in case a write did not fully complete must still
206 /// hold - be ready to call write_event again if a write call generated here isn't sufficient!
207 /// Panics if the descriptor was not previously registered in a new_*_connection event.
208 pub fn write_event(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
209 let mut peers = self.peers.lock().unwrap();
210 match peers.peers.get_mut(descriptor) {
211 None => panic!("Descriptor for write_event is not already known to PeerManager"),
213 peer.awaiting_write_event = false;
214 Self::do_attempt_write_data(descriptor, peer);
220 /// Indicates that data was read from the given socket descriptor.
221 /// May return an Err to indicate that the connection should be closed.
222 /// Will very likely call send_data on the descriptor passed in (or a descriptor handed into
223 /// new_*_connection) before returning. Thus, be very careful with reentrancy issues! The
224 /// invariants around calling write_event in case a write did not fully complete must still
225 /// hold. Note that this function will often call send_data on many peers before returning, not
227 /// If Ok(true) is returned, further read_events should not be triggered until a write_event on
228 /// this file descriptor has resume_read set (preventing DoS issues in the send buffer). Note
229 /// that this must be true even if a send_data call with resume_read=true was made during the
230 /// course of this function!
231 /// Panics if the descriptor was not previously registered in a new_*_connection event.
232 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
233 match self.do_read_event(peer_descriptor, data) {
236 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
242 fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
244 let mut peers = self.peers.lock().unwrap();
245 let (should_insert_node_id, pause_read) = match peers.peers.get_mut(peer_descriptor) {
246 None => panic!("Descriptor for read_event is not already known to PeerManager"),
248 assert!(peer.pending_read_buffer.len() > 0);
249 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
251 let mut insert_node_id = None;
252 let mut read_pos = 0;
253 while read_pos < data.len() {
255 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
256 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]);
257 read_pos += data_to_copy;
258 peer.pending_read_buffer_pos += data_to_copy;
261 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
262 peer.pending_read_buffer_pos = 0;
264 macro_rules! encode_and_send_msg {
265 ($msg: expr, $msg_code: expr) => {
266 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!($msg, $msg_code)[..]));
270 macro_rules! try_potential_handleerror {
275 println!("Got error handling message: {}!", e.err);
276 if let Some(action) = e.msg {
278 msgs::ErrorAction::UpdateFailHTLC { msg } => {
279 encode_and_send_msg!(msg, 131);
282 msgs::ErrorAction::DisconnectPeer => {
283 return Err(PeerHandleError{ no_connection_possible: false });
285 msgs::ErrorAction::IgnoreError => {
290 return Err(PeerHandleError{ no_connection_possible: false });
297 macro_rules! try_potential_decodeerror {
302 println!("Error decoding message");
304 return Err(PeerHandleError{ no_connection_possible: false });
310 macro_rules! try_ignore_potential_decodeerror {
315 println!("Error decoding message, ignoring due to lnd spec incompatibility. See https://github.com/lightningnetwork/lnd/issues/1407");
322 let next_step = peer.channel_encryptor.get_noise_step();
324 NextNoiseStep::ActOne => {
325 let act_two = try_potential_handleerror!(peer.channel_encryptor.process_act_one_with_key(&peer.pending_read_buffer[..], &self.our_node_secret)).to_vec();
326 peer.pending_outbound_buffer.push_back(act_two);
327 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
329 NextNoiseStep::ActTwo => {
330 let act_three = try_potential_handleerror!(peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], &self.our_node_secret)).to_vec();
331 peer.pending_outbound_buffer.push_back(act_three);
332 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
333 peer.pending_read_is_header = true;
335 insert_node_id = Some(peer.their_node_id.unwrap());
336 encode_and_send_msg!(msgs::Init {
337 global_features: msgs::GlobalFeatures::new(),
338 local_features: msgs::LocalFeatures::new(),
341 NextNoiseStep::ActThree => {
342 let their_node_id = try_potential_handleerror!(peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
343 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
344 peer.pending_read_is_header = true;
345 peer.their_node_id = Some(their_node_id);
346 insert_node_id = Some(peer.their_node_id.unwrap());
348 NextNoiseStep::NoiseComplete => {
349 if peer.pending_read_is_header {
350 let msg_len = try_potential_handleerror!(peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
351 peer.pending_read_buffer = Vec::with_capacity(msg_len as usize + 16);
352 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
353 if msg_len < 2 { // Need at least the message type tag
354 return Err(PeerHandleError{ no_connection_possible: false });
356 peer.pending_read_is_header = false;
358 let msg_data = try_potential_handleerror!(peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
359 assert!(msg_data.len() >= 2);
362 peer.pending_read_buffer = [0; 18].to_vec();
363 peer.pending_read_is_header = true;
365 let msg_type = byte_utils::slice_to_be16(&msg_data[0..2]);
366 if msg_type != 16 && peer.their_global_features.is_none() {
367 // Need an init message as first message
368 return Err(PeerHandleError{ no_connection_possible: false });
371 // Connection control:
373 let msg = try_potential_decodeerror!(msgs::Init::decode(&msg_data[2..]));
374 if msg.global_features.requires_unknown_bits() {
375 return Err(PeerHandleError{ no_connection_possible: true });
377 if msg.local_features.requires_unknown_bits() {
378 return Err(PeerHandleError{ no_connection_possible: true });
380 peer.their_global_features = Some(msg.global_features);
381 peer.their_local_features = Some(msg.local_features);
384 encode_and_send_msg!(msgs::Init {
385 global_features: msgs::GlobalFeatures::new(),
386 local_features: msgs::LocalFeatures::new(),
398 let msg = try_potential_decodeerror!(msgs::OpenChannel::decode(&msg_data[2..]));
399 let resp = try_potential_handleerror!(self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), &msg));
400 encode_and_send_msg!(resp, 33);
403 let msg = try_potential_decodeerror!(msgs::AcceptChannel::decode(&msg_data[2..]));
404 try_potential_handleerror!(self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), &msg));
408 let msg = try_potential_decodeerror!(msgs::FundingCreated::decode(&msg_data[2..]));
409 let resp = try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg));
410 encode_and_send_msg!(resp, 35);
413 let msg = try_potential_decodeerror!(msgs::FundingSigned::decode(&msg_data[2..]));
414 try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg));
417 let msg = try_potential_decodeerror!(msgs::FundingLocked::decode(&msg_data[2..]));
418 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg));
420 Some(resp) => encode_and_send_msg!(resp, 259),
426 let msg = try_potential_decodeerror!(msgs::Shutdown::decode(&msg_data[2..]));
427 let resp_options = try_potential_handleerror!(self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), &msg));
428 if let Some(resp) = resp_options.0 {
429 encode_and_send_msg!(resp, 38);
431 if let Some(resp) = resp_options.1 {
432 encode_and_send_msg!(resp, 39);
436 let msg = try_potential_decodeerror!(msgs::ClosingSigned::decode(&msg_data[2..]));
437 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg));
438 if let Some(resp) = resp_option {
439 encode_and_send_msg!(resp, 39);
444 let msg = try_potential_decodeerror!(msgs::UpdateAddHTLC::decode(&msg_data[2..]));
445 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg));
448 let msg = try_potential_decodeerror!(msgs::UpdateFulfillHTLC::decode(&msg_data[2..]));
449 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg));
452 let msg = try_potential_decodeerror!(msgs::UpdateFailHTLC::decode(&msg_data[2..]));
453 let chan_update = try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg));
454 if let Some(update) = chan_update {
455 self.message_handler.route_handler.handle_htlc_fail_channel_update(&update);
459 let msg = try_potential_decodeerror!(msgs::UpdateFailMalformedHTLC::decode(&msg_data[2..]));
460 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg));
464 let msg = try_potential_decodeerror!(msgs::CommitmentSigned::decode(&msg_data[2..]));
465 let resps = try_potential_handleerror!(self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg));
466 encode_and_send_msg!(resps.0, 133);
467 if let Some(resp) = resps.1 {
468 encode_and_send_msg!(resp, 132);
472 let msg = try_potential_decodeerror!(msgs::RevokeAndACK::decode(&msg_data[2..]));
473 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg));
476 for resp in resps.update_add_htlcs {
477 encode_and_send_msg!(resp, 128);
479 for resp in resps.update_fulfill_htlcs {
480 encode_and_send_msg!(resp, 130);
482 for resp in resps.update_fail_htlcs {
483 encode_and_send_msg!(resp, 131);
485 encode_and_send_msg!(resps.commitment_signed, 132);
491 let msg = try_potential_decodeerror!(msgs::UpdateFee::decode(&msg_data[2..]));
492 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg));
494 136 => { }, // TODO: channel_reestablish
498 let msg = try_potential_decodeerror!(msgs::AnnouncementSignatures::decode(&msg_data[2..]));
499 try_potential_handleerror!(self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg));
502 let msg = try_potential_decodeerror!(msgs::ChannelAnnouncement::decode(&msg_data[2..]));
503 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_announcement(&msg));
506 // TODO: forward msg along to all our other peers!
510 let msg = try_ignore_potential_decodeerror!(msgs::NodeAnnouncement::decode(&msg_data[2..]));
511 try_potential_handleerror!(self.message_handler.route_handler.handle_node_announcement(&msg));
514 let msg = try_potential_decodeerror!(msgs::ChannelUpdate::decode(&msg_data[2..]));
515 try_potential_handleerror!(self.message_handler.route_handler.handle_channel_update(&msg));
518 if (msg_type & 1) == 0 {
519 return Err(PeerHandleError{ no_connection_possible: true });
529 Self::do_attempt_write_data(peer_descriptor, peer);
531 (insert_node_id /* should_insert_node_id */, peer.pending_outbound_buffer.len() > 10) // pause_read
535 match should_insert_node_id {
536 Some(node_id) => { peers.node_id_to_descriptor.insert(node_id, peer_descriptor.clone()); },
543 self.process_events();
548 /// Checks for any events generated by our handlers and processes them. May be needed after eg
549 /// calls to ChannelManager::process_pending_htlc_forward.
550 pub fn process_events(&self) {
551 let mut upstream_events = Vec::new();
553 // TODO: There are some DoS attacks here where you can flood someone's outbound send
554 // buffer by doing things like announcing channels on another node. We should be willing to
555 // drop optional-ish messages when send buffers get full!
557 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_events();
558 let mut peers = self.peers.lock().unwrap();
559 for event in events_generated.drain(..) {
560 macro_rules! get_peer_for_forwarding {
561 ($node_id: expr, $handle_no_such_peer: block) => {
563 let descriptor = match peers.node_id_to_descriptor.get($node_id) {
564 Some(descriptor) => descriptor.clone(),
566 $handle_no_such_peer;
570 match peers.peers.get_mut(&descriptor) {
574 None => panic!("Inconsistent peers set state!"),
580 Event::FundingGenerationReady {..} => { /* Hand upstream */ },
581 Event::FundingBroadcastSafe {..} => { /* Hand upstream */ },
582 Event::PaymentReceived {..} => { /* Hand upstream */ },
583 Event::PaymentSent {..} => { /* Hand upstream */ },
584 Event::PaymentFailed {..} => { /* Hand upstream */ },
586 Event::PendingHTLCsForwardable {..} => {
587 //TODO: Handle upstream in some confused form so that upstream just knows
588 //to call us somehow?
590 Event::SendFundingCreated { ref node_id, ref msg } => {
591 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
592 //TODO: generate a DiscardFunding event indicating to the wallet that
593 //they should just throw away this funding transaction
595 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 34)));
596 Self::do_attempt_write_data(&mut descriptor, peer);
599 Event::SendFundingLocked { ref node_id, ref msg, ref announcement_sigs } => {
600 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
601 //TODO: Do whatever we're gonna do for handling dropped messages
603 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 36)));
604 match announcement_sigs {
605 &Some(ref announce_msg) => peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(announce_msg, 259))),
608 Self::do_attempt_write_data(&mut descriptor, peer);
611 Event::SendHTLCs { ref node_id, ref msgs, ref commitment_msg } => {
612 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
613 //TODO: Do whatever we're gonna do for handling dropped messages
616 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 128)));
618 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_msg, 132)));
619 Self::do_attempt_write_data(&mut descriptor, peer);
622 Event::SendFulfillHTLC { ref node_id, ref msg, ref commitment_msg } => {
623 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
624 //TODO: Do whatever we're gonna do for handling dropped messages
626 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 130)));
627 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_msg, 132)));
628 Self::do_attempt_write_data(&mut descriptor, peer);
631 Event::SendFailHTLC { ref node_id, ref msg, ref commitment_msg } => {
632 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
633 //TODO: Do whatever we're gonna do for handling dropped messages
635 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 131)));
636 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_msg, 132)));
637 Self::do_attempt_write_data(&mut descriptor, peer);
640 Event::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
641 if self.message_handler.route_handler.handle_channel_announcement(msg).is_ok() && self.message_handler.route_handler.handle_channel_update(update_msg).is_ok() {
642 let encoded_msg = encode_msg!(msg, 256);
643 let encoded_update_msg = encode_msg!(update_msg, 258);
645 for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
646 if !peer.channel_encryptor.is_ready_for_encryption() {
649 match peer.their_node_id {
651 Some(their_node_id) => {
652 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
657 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
658 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_update_msg[..]));
659 Self::do_attempt_write_data(&mut (*descriptor).clone(), peer);
664 Event::BroadcastChannelUpdate { ref msg } => {
665 if self.message_handler.route_handler.handle_channel_update(msg).is_ok() {
666 let encoded_msg = encode_msg!(msg, 258);
668 for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
669 if !peer.channel_encryptor.is_ready_for_encryption() {
672 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
673 Self::do_attempt_write_data(&mut (*descriptor).clone(), peer);
680 upstream_events.push(event);
684 let mut pending_events = self.pending_events.lock().unwrap();
685 for event in upstream_events.drain(..) {
686 pending_events.push(event);
690 /// Indicates that the given socket descriptor's connection is now closed.
691 /// This must be called even if a PeerHandleError was given for a read_event or write_event,
692 /// but must NOT be called if a PeerHandleError was provided out of a new_*_connection event!
693 /// Panics if the descriptor was not previously registered in a successful new_*_connection event.
694 pub fn disconnect_event(&self, descriptor: &Descriptor) {
695 self.disconnect_event_internal(descriptor, false);
698 fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
699 let mut peers = self.peers.lock().unwrap();
700 let peer_option = peers.peers.remove(descriptor);
702 None => panic!("Descriptor for disconnect_event is not already known to PeerManager"),
704 match peer.their_node_id {
706 peers.node_id_to_descriptor.remove(&node_id);
707 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
716 impl<Descriptor: SocketDescriptor> EventsProvider for PeerManager<Descriptor> {
717 fn get_and_clear_pending_events(&self) -> Vec<Event> {
718 let mut pending_events = self.pending_events.lock().unwrap();
719 let mut ret = Vec::new();
720 mem::swap(&mut ret, &mut *pending_events);