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::sync::atomic::{AtomicUsize, Ordering};
12 use std::{cmp,error,mem,hash,fmt};
14 pub struct MessageHandler {
15 pub chan_handler: Arc<msgs::ChannelMessageHandler>,
16 pub route_handler: Arc<msgs::RoutingMessageHandler>,
19 /// Provides an object which can be used to send data to and which uniquely identifies a connection
20 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
21 /// implement Hash to meet the PeerManager API.
22 /// For efficiency, Clone should be relatively cheap for this type.
23 /// You probably want to just extend an int and put a file descriptor in a struct and implement
24 /// send_data. Note that if you are using a higher-level net library that may close() itself, be
25 /// careful to ensure you don't have races whereby you might register a new connection with an fd
26 /// the same as a yet-to-be-disconnect_event()-ed.
27 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
28 /// Attempts to send some data from the given Vec starting at the given offset to the peer.
29 /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
30 /// Note that in the disconnected case, a disconnect_event must still fire and further write
31 /// attempts may occur until that time.
32 /// If the returned size is smaller than data.len() - write_offset, a write_available event must
33 /// trigger the next time more data can be written. Additionally, until the a send_data event
34 /// completes fully, no further read_events should trigger on the same peer!
35 /// If a read_event on this descriptor had previously returned true (indicating that read
36 /// events should be paused to prevent DoS in the send buffer), resume_read may be set
37 /// indicating that read events on this descriptor should resume. A resume_read of false does
38 /// *not* imply that further read events should be paused.
39 fn send_data(&mut self, data: &Vec<u8>, write_offset: usize, resume_read: bool) -> usize;
42 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
43 /// generate no further read/write_events for the descriptor, only triggering a single
44 /// disconnect_event (unless it was provided in response to a new_*_connection event, in which case
45 /// no such disconnect_event must be generated and the socket be silently disconencted).
46 pub struct PeerHandleError {
47 no_connection_possible: bool,
49 impl fmt::Debug for PeerHandleError {
50 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
51 formatter.write_str("Peer Sent Invalid Data")
54 impl fmt::Display for PeerHandleError {
55 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
56 formatter.write_str("Peer Sent Invalid Data")
59 impl error::Error for PeerHandleError {
60 fn description(&self) -> &str {
61 "Peer Sent Invalid Data"
66 channel_encryptor: PeerChannelEncryptor,
68 their_node_id: Option<PublicKey>,
69 their_global_features: Option<msgs::GlobalFeatures>,
70 their_local_features: Option<msgs::LocalFeatures>,
72 pending_outbound_buffer: LinkedList<Vec<u8>>,
73 pending_outbound_buffer_first_msg_offset: usize,
74 awaiting_write_event: bool,
76 pending_read_buffer: Vec<u8>,
77 pending_read_buffer_pos: usize,
78 pending_read_is_header: bool,
81 struct PeerHolder<Descriptor: SocketDescriptor> {
82 peers: HashMap<Descriptor, Peer>,
83 /// Only add to this set when noise completes:
84 node_id_to_descriptor: HashMap<PublicKey, Descriptor>,
87 pub struct PeerManager<Descriptor: SocketDescriptor> {
88 message_handler: MessageHandler,
89 peers: Mutex<PeerHolder<Descriptor>>,
90 pending_events: Mutex<Vec<Event>>,
91 our_node_secret: SecretKey,
92 initial_syncs_sent: AtomicUsize,
96 macro_rules! encode_msg {
97 ($msg: expr, $msg_code: expr) => {
99 let just_msg = $msg.encode();
100 let mut encoded_msg = Vec::with_capacity(just_msg.len() + 2);
101 encoded_msg.extend_from_slice(&byte_utils::be16_to_array($msg_code));
102 encoded_msg.extend_from_slice(&just_msg[..]);
108 //TODO: Really should do something smarter for this
109 const INITIAL_SYNCS_TO_SEND: usize = 5;
111 /// Manages and reacts to connection events. You probably want to use file descriptors as PeerIds.
112 /// PeerIds may repeat, but only after disconnect_event() has been called.
113 impl<Descriptor: SocketDescriptor> PeerManager<Descriptor> {
114 pub fn new(message_handler: MessageHandler, our_node_secret: SecretKey) -> PeerManager<Descriptor> {
116 message_handler: message_handler,
117 peers: Mutex::new(PeerHolder { peers: HashMap::new(), node_id_to_descriptor: HashMap::new() }),
118 pending_events: Mutex::new(Vec::new()),
119 our_node_secret: our_node_secret,
120 initial_syncs_sent: AtomicUsize::new(0),
124 /// Get the list of node ids for peers which have completed the initial handshake.
125 /// For outbound connections, this will be the same as the their_node_id parameter passed in to
126 /// new_outbound_connection, however entries will only appear once the initial handshake has
127 /// completed and we are sure the remote peer has the private key for the given node_id.
128 pub fn get_peer_node_ids(&self) -> Vec<PublicKey> {
129 let peers = self.peers.lock().unwrap();
130 peers.peers.values().filter_map(|p| p.their_node_id).collect()
133 /// Indicates a new outbound connection has been established to a node with the given node_id.
134 /// Note that if an Err is returned here you MUST NOT call disconnect_event for the new
135 /// descriptor but must disconnect the connection immediately.
136 /// Returns some bytes to send to the remote node.
137 /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
138 /// disconnect_event.
139 pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor) -> Result<Vec<u8>, PeerHandleError> {
140 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone());
141 let res = peer_encryptor.get_act_one().to_vec();
142 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
144 let mut peers = self.peers.lock().unwrap();
145 if peers.peers.insert(descriptor, Peer {
146 channel_encryptor: peer_encryptor,
148 their_node_id: Some(their_node_id),
149 their_global_features: None,
150 their_local_features: None,
152 pending_outbound_buffer: LinkedList::new(),
153 pending_outbound_buffer_first_msg_offset: 0,
154 awaiting_write_event: false,
156 pending_read_buffer: pending_read_buffer,
157 pending_read_buffer_pos: 0,
158 pending_read_is_header: false,
160 panic!("PeerManager driver duplicated descriptors!");
165 /// Indicates a new inbound connection has been established.
166 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
167 /// (outbound connector always speaks first). Note that if an Err is returned here you MUST NOT
168 /// call disconnect_event for the new descriptor but must disconnect the connection
170 /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
171 /// disconnect_event.
172 pub fn new_inbound_connection(&self, descriptor: Descriptor) -> Result<(), PeerHandleError> {
173 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret);
174 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
176 let mut peers = self.peers.lock().unwrap();
177 if peers.peers.insert(descriptor, Peer {
178 channel_encryptor: peer_encryptor,
181 their_global_features: None,
182 their_local_features: None,
184 pending_outbound_buffer: LinkedList::new(),
185 pending_outbound_buffer_first_msg_offset: 0,
186 awaiting_write_event: false,
188 pending_read_buffer: pending_read_buffer,
189 pending_read_buffer_pos: 0,
190 pending_read_is_header: false,
192 panic!("PeerManager driver duplicated descriptors!");
197 fn do_attempt_write_data(descriptor: &mut Descriptor, peer: &mut Peer) {
198 while !peer.awaiting_write_event {
200 let next_buff = match peer.pending_outbound_buffer.front() {
204 let should_be_reading = peer.pending_outbound_buffer.len() < 10;
206 let data_sent = descriptor.send_data(next_buff, peer.pending_outbound_buffer_first_msg_offset, should_be_reading);
207 peer.pending_outbound_buffer_first_msg_offset += data_sent;
208 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() { true } else { false }
210 peer.pending_outbound_buffer_first_msg_offset = 0;
211 peer.pending_outbound_buffer.pop_front();
213 peer.awaiting_write_event = true;
218 /// Indicates that there is room to write data to the given socket descriptor.
219 /// May return an Err to indicate that the connection should be closed.
220 /// Will most likely call send_data on the descriptor passed in (or the descriptor handed into
221 /// new_*_connection) before returning. Thus, be very careful with reentrancy issues! The
222 /// invariants around calling write_event in case a write did not fully complete must still
223 /// hold - be ready to call write_event again if a write call generated here isn't sufficient!
224 /// Panics if the descriptor was not previously registered in a new_*_connection event.
225 pub fn write_event(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
226 let mut peers = self.peers.lock().unwrap();
227 match peers.peers.get_mut(descriptor) {
228 None => panic!("Descriptor for write_event is not already known to PeerManager"),
230 peer.awaiting_write_event = false;
231 Self::do_attempt_write_data(descriptor, peer);
237 /// Indicates that data was read from the given socket descriptor.
238 /// May return an Err to indicate that the connection should be closed.
239 /// Will very likely call send_data on the descriptor passed in (or a descriptor handed into
240 /// new_*_connection) before returning. Thus, be very careful with reentrancy issues! The
241 /// invariants around calling write_event in case a write did not fully complete must still
242 /// hold. Note that this function will often call send_data on many peers before returning, not
244 /// If Ok(true) is returned, further read_events should not be triggered until a write_event on
245 /// this file descriptor has resume_read set (preventing DoS issues in the send buffer). Note
246 /// that this must be true even if a send_data call with resume_read=true was made during the
247 /// course of this function!
248 /// Panics if the descriptor was not previously registered in a new_*_connection event.
249 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
250 match self.do_read_event(peer_descriptor, data) {
253 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
259 fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
261 let mut peers = self.peers.lock().unwrap();
262 let (should_insert_node_id, pause_read) = match peers.peers.get_mut(peer_descriptor) {
263 None => panic!("Descriptor for read_event is not already known to PeerManager"),
265 assert!(peer.pending_read_buffer.len() > 0);
266 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
268 let mut insert_node_id = None;
269 let mut read_pos = 0;
270 while read_pos < data.len() {
272 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
273 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]);
274 read_pos += data_to_copy;
275 peer.pending_read_buffer_pos += data_to_copy;
278 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
279 peer.pending_read_buffer_pos = 0;
281 macro_rules! encode_and_send_msg {
282 ($msg: expr, $msg_code: expr) => {
283 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!($msg, $msg_code)[..]));
287 macro_rules! try_potential_handleerror {
292 println!("Got error handling message: {}!", e.err);
293 if let Some(action) = e.action {
295 msgs::ErrorAction::UpdateFailHTLC { msg } => {
296 encode_and_send_msg!(msg, 131);
299 msgs::ErrorAction::DisconnectPeer => {
300 return Err(PeerHandleError{ no_connection_possible: false });
302 msgs::ErrorAction::IgnoreError => {
307 return Err(PeerHandleError{ no_connection_possible: false });
314 macro_rules! try_potential_decodeerror {
319 println!("Error decoding message");
321 return Err(PeerHandleError{ no_connection_possible: false });
327 macro_rules! try_ignore_potential_decodeerror {
332 println!("Error decoding message, ignoring due to lnd spec incompatibility. See https://github.com/lightningnetwork/lnd/issues/1407");
339 let next_step = peer.channel_encryptor.get_noise_step();
341 NextNoiseStep::ActOne => {
342 let act_two = try_potential_handleerror!(peer.channel_encryptor.process_act_one_with_key(&peer.pending_read_buffer[..], &self.our_node_secret)).to_vec();
343 peer.pending_outbound_buffer.push_back(act_two);
344 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
346 NextNoiseStep::ActTwo => {
347 let act_three = try_potential_handleerror!(peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], &self.our_node_secret)).to_vec();
348 peer.pending_outbound_buffer.push_back(act_three);
349 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
350 peer.pending_read_is_header = true;
352 insert_node_id = Some(peer.their_node_id.unwrap());
353 let mut local_features = msgs::LocalFeatures::new();
354 if self.initial_syncs_sent.load(Ordering::Acquire) < INITIAL_SYNCS_TO_SEND {
355 self.initial_syncs_sent.fetch_add(1, Ordering::AcqRel);
356 local_features.set_initial_routing_sync();
358 encode_and_send_msg!(msgs::Init {
359 global_features: msgs::GlobalFeatures::new(),
363 NextNoiseStep::ActThree => {
364 let their_node_id = try_potential_handleerror!(peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
365 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
366 peer.pending_read_is_header = true;
367 peer.their_node_id = Some(their_node_id);
368 insert_node_id = Some(peer.their_node_id.unwrap());
370 NextNoiseStep::NoiseComplete => {
371 if peer.pending_read_is_header {
372 let msg_len = try_potential_handleerror!(peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
373 peer.pending_read_buffer = Vec::with_capacity(msg_len as usize + 16);
374 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
375 if msg_len < 2 { // Need at least the message type tag
376 return Err(PeerHandleError{ no_connection_possible: false });
378 peer.pending_read_is_header = false;
380 let msg_data = try_potential_handleerror!(peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
381 assert!(msg_data.len() >= 2);
384 peer.pending_read_buffer = [0; 18].to_vec();
385 peer.pending_read_is_header = true;
387 let msg_type = byte_utils::slice_to_be16(&msg_data[0..2]);
388 if msg_type != 16 && peer.their_global_features.is_none() {
389 // Need an init message as first message
390 return Err(PeerHandleError{ no_connection_possible: false });
393 // Connection control:
395 let msg = try_potential_decodeerror!(msgs::Init::decode(&msg_data[2..]));
396 if msg.global_features.requires_unknown_bits() {
397 return Err(PeerHandleError{ no_connection_possible: true });
399 if msg.local_features.requires_unknown_bits() {
400 return Err(PeerHandleError{ no_connection_possible: true });
402 peer.their_global_features = Some(msg.global_features);
403 peer.their_local_features = Some(msg.local_features);
406 let mut local_features = msgs::LocalFeatures::new();
407 if self.initial_syncs_sent.load(Ordering::Acquire) < INITIAL_SYNCS_TO_SEND {
408 self.initial_syncs_sent.fetch_add(1, Ordering::AcqRel);
409 local_features.set_initial_routing_sync();
411 encode_and_send_msg!(msgs::Init {
412 global_features: msgs::GlobalFeatures::new(),
422 let msg = try_potential_decodeerror!(msgs::Ping::decode(&msg_data[2..]));
423 if msg.ponglen < 65532 {
424 let resp = msgs::Pong { byteslen: msg.ponglen };
425 encode_and_send_msg!(resp, 19);
429 try_potential_decodeerror!(msgs::Pong::decode(&msg_data[2..]));
434 let msg = try_potential_decodeerror!(msgs::OpenChannel::decode(&msg_data[2..]));
435 let resp = try_potential_handleerror!(self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), &msg));
436 encode_and_send_msg!(resp, 33);
439 let msg = try_potential_decodeerror!(msgs::AcceptChannel::decode(&msg_data[2..]));
440 try_potential_handleerror!(self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), &msg));
444 let msg = try_potential_decodeerror!(msgs::FundingCreated::decode(&msg_data[2..]));
445 let resp = try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg));
446 encode_and_send_msg!(resp, 35);
449 let msg = try_potential_decodeerror!(msgs::FundingSigned::decode(&msg_data[2..]));
450 try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg));
453 let msg = try_potential_decodeerror!(msgs::FundingLocked::decode(&msg_data[2..]));
454 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg));
456 Some(resp) => encode_and_send_msg!(resp, 259),
462 let msg = try_potential_decodeerror!(msgs::Shutdown::decode(&msg_data[2..]));
463 let resp_options = try_potential_handleerror!(self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), &msg));
464 if let Some(resp) = resp_options.0 {
465 encode_and_send_msg!(resp, 38);
467 if let Some(resp) = resp_options.1 {
468 encode_and_send_msg!(resp, 39);
472 let msg = try_potential_decodeerror!(msgs::ClosingSigned::decode(&msg_data[2..]));
473 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg));
474 if let Some(resp) = resp_option {
475 encode_and_send_msg!(resp, 39);
480 let msg = try_potential_decodeerror!(msgs::UpdateAddHTLC::decode(&msg_data[2..]));
481 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg));
484 let msg = try_potential_decodeerror!(msgs::UpdateFulfillHTLC::decode(&msg_data[2..]));
485 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg));
488 let msg = try_potential_decodeerror!(msgs::UpdateFailHTLC::decode(&msg_data[2..]));
489 let chan_update = try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg));
490 if let Some(update) = chan_update {
491 self.message_handler.route_handler.handle_htlc_fail_channel_update(&update);
495 let msg = try_potential_decodeerror!(msgs::UpdateFailMalformedHTLC::decode(&msg_data[2..]));
496 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg));
500 let msg = try_potential_decodeerror!(msgs::CommitmentSigned::decode(&msg_data[2..]));
501 let resps = try_potential_handleerror!(self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg));
502 encode_and_send_msg!(resps.0, 133);
503 if let Some(resp) = resps.1 {
504 encode_and_send_msg!(resp, 132);
508 let msg = try_potential_decodeerror!(msgs::RevokeAndACK::decode(&msg_data[2..]));
509 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg));
512 for resp in resps.update_add_htlcs {
513 encode_and_send_msg!(resp, 128);
515 for resp in resps.update_fulfill_htlcs {
516 encode_and_send_msg!(resp, 130);
518 for resp in resps.update_fail_htlcs {
519 encode_and_send_msg!(resp, 131);
521 encode_and_send_msg!(resps.commitment_signed, 132);
527 let msg = try_potential_decodeerror!(msgs::UpdateFee::decode(&msg_data[2..]));
528 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg));
530 136 => { }, // TODO: channel_reestablish
534 let msg = try_potential_decodeerror!(msgs::AnnouncementSignatures::decode(&msg_data[2..]));
535 try_potential_handleerror!(self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg));
538 let msg = try_potential_decodeerror!(msgs::ChannelAnnouncement::decode(&msg_data[2..]));
539 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_announcement(&msg));
542 // TODO: forward msg along to all our other peers!
546 let msg = try_ignore_potential_decodeerror!(msgs::NodeAnnouncement::decode(&msg_data[2..]));
547 try_potential_handleerror!(self.message_handler.route_handler.handle_node_announcement(&msg));
550 let msg = try_potential_decodeerror!(msgs::ChannelUpdate::decode(&msg_data[2..]));
551 try_potential_handleerror!(self.message_handler.route_handler.handle_channel_update(&msg));
554 if (msg_type & 1) == 0 {
555 return Err(PeerHandleError{ no_connection_possible: true });
565 Self::do_attempt_write_data(peer_descriptor, peer);
567 (insert_node_id /* should_insert_node_id */, peer.pending_outbound_buffer.len() > 10) // pause_read
571 match should_insert_node_id {
572 Some(node_id) => { peers.node_id_to_descriptor.insert(node_id, peer_descriptor.clone()); },
579 self.process_events();
584 /// Checks for any events generated by our handlers and processes them. May be needed after eg
585 /// calls to ChannelManager::process_pending_htlc_forward.
586 pub fn process_events(&self) {
587 let mut upstream_events = Vec::new();
589 // TODO: There are some DoS attacks here where you can flood someone's outbound send
590 // buffer by doing things like announcing channels on another node. We should be willing to
591 // drop optional-ish messages when send buffers get full!
593 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_events();
594 let mut peers = self.peers.lock().unwrap();
595 for event in events_generated.drain(..) {
596 macro_rules! get_peer_for_forwarding {
597 ($node_id: expr, $handle_no_such_peer: block) => {
599 let descriptor = match peers.node_id_to_descriptor.get($node_id) {
600 Some(descriptor) => descriptor.clone(),
602 $handle_no_such_peer;
606 match peers.peers.get_mut(&descriptor) {
610 None => panic!("Inconsistent peers set state!"),
616 Event::FundingGenerationReady {..} => { /* Hand upstream */ },
617 Event::FundingBroadcastSafe {..} => { /* Hand upstream */ },
618 Event::PaymentReceived {..} => { /* Hand upstream */ },
619 Event::PaymentSent {..} => { /* Hand upstream */ },
620 Event::PaymentFailed {..} => { /* Hand upstream */ },
622 Event::PendingHTLCsForwardable {..} => {
623 //TODO: Handle upstream in some confused form so that upstream just knows
624 //to call us somehow?
626 Event::SendOpenChannel { ref node_id, ref msg } => {
627 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
628 //TODO: Drop the pending channel? (or just let it timeout, but that sucks)
630 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 32)));
631 Self::do_attempt_write_data(&mut descriptor, peer);
634 Event::SendFundingCreated { ref node_id, ref msg } => {
635 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
636 //TODO: generate a DiscardFunding event indicating to the wallet that
637 //they should just throw away this funding transaction
639 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 34)));
640 Self::do_attempt_write_data(&mut descriptor, peer);
643 Event::SendFundingLocked { ref node_id, ref msg, ref announcement_sigs } => {
644 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
645 //TODO: Do whatever we're gonna do for handling dropped messages
647 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 36)));
648 match announcement_sigs {
649 &Some(ref announce_msg) => peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(announce_msg, 259))),
652 Self::do_attempt_write_data(&mut descriptor, peer);
655 Event::SendHTLCs { ref node_id, ref msgs, ref commitment_msg } => {
656 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
657 //TODO: Do whatever we're gonna do for handling dropped messages
660 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 128)));
662 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_msg, 132)));
663 Self::do_attempt_write_data(&mut descriptor, peer);
666 Event::SendFulfillHTLC { ref node_id, ref msg, ref commitment_msg } => {
667 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
668 //TODO: Do whatever we're gonna do for handling dropped messages
670 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 130)));
671 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_msg, 132)));
672 Self::do_attempt_write_data(&mut descriptor, peer);
675 Event::SendFailHTLC { ref node_id, ref msg, ref commitment_msg } => {
676 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
677 //TODO: Do whatever we're gonna do for handling dropped messages
679 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 131)));
680 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_msg, 132)));
681 Self::do_attempt_write_data(&mut descriptor, peer);
684 Event::SendShutdown { ref node_id, ref msg } => {
685 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
686 //TODO: Do whatever we're gonna do for handling dropped messages
688 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 38)));
689 Self::do_attempt_write_data(&mut descriptor, peer);
692 Event::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
693 if self.message_handler.route_handler.handle_channel_announcement(msg).is_ok() && self.message_handler.route_handler.handle_channel_update(update_msg).is_ok() {
694 let encoded_msg = encode_msg!(msg, 256);
695 let encoded_update_msg = encode_msg!(update_msg, 258);
697 for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
698 if !peer.channel_encryptor.is_ready_for_encryption() {
701 match peer.their_node_id {
703 Some(their_node_id) => {
704 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
709 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
710 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_update_msg[..]));
711 Self::do_attempt_write_data(&mut (*descriptor).clone(), peer);
716 Event::BroadcastChannelUpdate { ref msg } => {
717 if self.message_handler.route_handler.handle_channel_update(msg).is_ok() {
718 let encoded_msg = encode_msg!(msg, 258);
720 for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
721 if !peer.channel_encryptor.is_ready_for_encryption() {
724 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
725 Self::do_attempt_write_data(&mut (*descriptor).clone(), peer);
732 upstream_events.push(event);
736 let mut pending_events = self.pending_events.lock().unwrap();
737 for event in upstream_events.drain(..) {
738 pending_events.push(event);
742 /// Indicates that the given socket descriptor's connection is now closed.
743 /// This must be called even if a PeerHandleError was given for a read_event or write_event,
744 /// but must NOT be called if a PeerHandleError was provided out of a new_*_connection event!
745 /// Panics if the descriptor was not previously registered in a successful new_*_connection event.
746 pub fn disconnect_event(&self, descriptor: &Descriptor) {
747 self.disconnect_event_internal(descriptor, false);
750 fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
751 let mut peers = self.peers.lock().unwrap();
752 let peer_option = peers.peers.remove(descriptor);
754 None => panic!("Descriptor for disconnect_event is not already known to PeerManager"),
756 match peer.their_node_id {
758 peers.node_id_to_descriptor.remove(&node_id);
759 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
768 impl<Descriptor: SocketDescriptor> EventsProvider for PeerManager<Descriptor> {
769 fn get_and_clear_pending_events(&self) -> Vec<Event> {
770 let mut pending_events = self.pending_events.lock().unwrap();
771 let mut ret = Vec::new();
772 mem::swap(&mut ret, &mut *pending_events);