X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning%2Fsrc%2Fln%2Fpeer_handler.rs;h=2559acfc2dd5370b93d59d1cdb47a591c80a1c56;hb=38a544eafd51f0446b1bb460a42107d35c740388;hp=e75c2c96e98c9e28dc24170f379c58bb42b6c4ac;hpb=dbdef7fac193b9e6921d40d6b5a373ac2ac3405b;p=rust-lightning diff --git a/lightning/src/ln/peer_handler.rs b/lightning/src/ln/peer_handler.rs index e75c2c96..2559acfc 100644 --- a/lightning/src/ln/peer_handler.rs +++ b/lightning/src/ln/peer_handler.rs @@ -1,3 +1,12 @@ +// This file is Copyright its original authors, visible in version control +// history. +// +// This file is licensed under the Apache License, Version 2.0 or the MIT license +// , at your option. +// You may not use this file except in accordance with one or both of these +// licenses. + //! Top level peer message handling and socket handling logic lives here. //! //! Instead of actually servicing sockets ourselves we require that you implement the @@ -10,7 +19,7 @@ use bitcoin::secp256k1::key::{SecretKey,PublicKey}; use ln::features::InitFeatures; use ln::msgs; -use ln::msgs::ChannelMessageHandler; +use ln::msgs::{ChannelMessageHandler, LightningError, RoutingMessageHandler}; use ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager}; use util::ser::{VecWriter, Writeable}; use ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep}; @@ -19,25 +28,141 @@ use ln::wire::Encode; use util::byte_utils; use util::events::{MessageSendEvent, MessageSendEventsProvider}; use util::logger::Logger; +use routing::network_graph::NetGraphMsgHandler; use std::collections::{HashMap,hash_map,HashSet,LinkedList}; use std::sync::{Arc, Mutex}; use std::sync::atomic::{AtomicUsize, Ordering}; -use std::{cmp,error,hash,fmt}; +use std::{cmp, error, hash, fmt, mem}; use std::ops::Deref; use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::sha256::HashEngine as Sha256Engine; use bitcoin::hashes::{HashEngine, Hash}; +/// A dummy struct which implements `RoutingMessageHandler` without storing any routing information +/// or doing any processing. You can provide one of these as the route_handler in a MessageHandler. +pub struct IgnoringMessageHandler{} +impl MessageSendEventsProvider for IgnoringMessageHandler { + fn get_and_clear_pending_msg_events(&self) -> Vec { Vec::new() } +} +impl RoutingMessageHandler for IgnoringMessageHandler { + fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result { Ok(false) } + fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result { Ok(false) } + fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result { Ok(false) } + fn handle_htlc_fail_channel_update(&self, _update: &msgs::HTLCFailChannelUpdate) {} + fn get_next_channel_announcements(&self, _starting_point: u64, _batch_amount: u8) -> + Vec<(msgs::ChannelAnnouncement, Option, Option)> { Vec::new() } + fn get_next_node_announcements(&self, _starting_point: Option<&PublicKey>, _batch_amount: u8) -> Vec { Vec::new() } + fn sync_routing_table(&self, _their_node_id: &PublicKey, _init: &msgs::Init) {} + fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), LightningError> { Ok(()) } + fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), LightningError> { Ok(()) } + fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), LightningError> { Ok(()) } + fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), LightningError> { Ok(()) } +} +impl Deref for IgnoringMessageHandler { + type Target = IgnoringMessageHandler; + fn deref(&self) -> &Self { self } +} + +/// A dummy struct which implements `ChannelMessageHandler` without having any channels. +/// You can provide one of these as the route_handler in a MessageHandler. +pub struct ErroringMessageHandler { + message_queue: Mutex> +} +impl ErroringMessageHandler { + /// Constructs a new ErroringMessageHandler + pub fn new() -> Self { + Self { message_queue: Mutex::new(Vec::new()) } + } + fn push_error(&self, node_id: &PublicKey, channel_id: [u8; 32]) { + self.message_queue.lock().unwrap().push(MessageSendEvent::HandleError { + action: msgs::ErrorAction::SendErrorMessage { + msg: msgs::ErrorMessage { channel_id, data: "We do not support channel messages, sorry.".to_owned() }, + }, + node_id: node_id.clone(), + }); + } +} +impl MessageSendEventsProvider for ErroringMessageHandler { + fn get_and_clear_pending_msg_events(&self) -> Vec { + let mut res = Vec::new(); + mem::swap(&mut res, &mut self.message_queue.lock().unwrap()); + res + } +} +impl ChannelMessageHandler for ErroringMessageHandler { + // Any messages which are related to a specific channel generate an error message to let the + // peer know we don't care about channels. + fn handle_open_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::OpenChannel) { + ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id); + } + fn handle_accept_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::AcceptChannel) { + ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id); + } + fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) { + ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id); + } + fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) { + ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id); + } + fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) { + ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id); + } + fn handle_shutdown(&self, their_node_id: &PublicKey, _their_features: &InitFeatures, msg: &msgs::Shutdown) { + ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id); + } + fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) { + ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id); + } + fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) { + ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id); + } + fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) { + ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id); + } + fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) { + ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id); + } + fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) { + ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id); + } + fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) { + ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id); + } + fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) { + ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id); + } + fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) { + ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id); + } + fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) { + ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id); + } + fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) { + ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id); + } + // msgs::ChannelUpdate does not contain the channel_id field, so we just drop them. + fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {} + fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {} + fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) {} + fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {} +} +impl Deref for ErroringMessageHandler { + type Target = ErroringMessageHandler; + fn deref(&self) -> &Self { self } +} + /// Provides references to trait impls which handle different types of messages. -pub struct MessageHandler where CM::Target: msgs::ChannelMessageHandler { +pub struct MessageHandler where + CM::Target: ChannelMessageHandler, + RM::Target: RoutingMessageHandler { /// A message handler which handles messages specific to channels. Usually this is just a - /// ChannelManager object. + /// ChannelManager object or a ErroringMessageHandler. pub chan_handler: CM, /// A message handler which handles messages updating our knowledge of the network channel - /// graph. Usually this is just a NetGraphMsgHandlerMonitor object. - pub route_handler: Arc, + /// graph. Usually this is just a NetGraphMsgHandlerMonitor object or an IgnoringMessageHandler. + pub route_handler: RM, } /// Provides an object which can be used to send data to and which uniquely identifies a connection @@ -76,14 +201,13 @@ pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone { } /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and -/// generate no further read_event/write_buffer_space_avail calls for the descriptor, only -/// triggering a single socket_disconnected call (unless it was provided in response to a -/// new_*_connection event, in which case no such socket_disconnected() must be called and the -/// socket silently disconencted). +/// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the +/// descriptor. +#[derive(Clone)] pub struct PeerHandleError { /// Used to indicate that we probably can't make any future connections to this peer, implying /// we should go ahead and force-close any channels we have with it. - no_connection_possible: bool, + pub no_connection_possible: bool, } impl fmt::Debug for PeerHandleError { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { @@ -109,7 +233,6 @@ enum InitSyncTracker{ struct Peer { channel_encryptor: PeerChannelEncryptor, - outbound: bool, their_node_id: Option, their_features: Option, @@ -171,7 +294,7 @@ fn _check_usize_is_32_or_64() { /// lifetimes). Other times you can afford a reference, which is more efficient, in which case /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents /// issues such as overly long function definitions. -pub type SimpleArcPeerManager = Arc, Arc>>; +pub type SimpleArcPeerManager = PeerManager>, Arc, Arc>>, Arc>; /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't @@ -179,7 +302,7 @@ pub type SimpleArcPeerManager = Arc = PeerManager, &'e L>; +pub type SimpleRefPeerManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, SD, M, T, F, C, L> = PeerManager, &'e NetGraphMsgHandler<&'g C, &'f L>, &'f L>; /// A PeerManager manages a set of peers, described by their SocketDescriptor and marshalls socket /// events into messages which it passes on to its MessageHandlers. @@ -189,8 +312,11 @@ pub type SimpleRefPeerManager<'a, 'b, 'c, 'd, 'e, SD, M, T, F, L> = PeerManager< /// essentially you should default to using a SimpleRefPeerManager, and use a /// SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when /// you're using lightning-net-tokio. -pub struct PeerManager where CM::Target: msgs::ChannelMessageHandler, L::Target: Logger { - message_handler: MessageHandler, +pub struct PeerManager where + CM::Target: ChannelMessageHandler, + RM::Target: RoutingMessageHandler, + L::Target: Logger { + message_handler: MessageHandler, peers: Mutex>, our_node_secret: SecretKey, ephemeral_key_midstate: Sha256Engine, @@ -203,6 +329,23 @@ pub struct PeerManager where logger: L, } +enum MessageHandlingError { + PeerHandleError(PeerHandleError), + LightningError(LightningError), +} + +impl From for MessageHandlingError { + fn from(error: PeerHandleError) -> Self { + MessageHandlingError::PeerHandleError(error) + } +} + +impl From for MessageHandlingError { + fn from(error: LightningError) -> Self { + MessageHandlingError::LightningError(error) + } +} + macro_rules! encode_msg { ($msg: expr) => {{ let mut buffer = VecWriter(Vec::new()); @@ -211,13 +354,54 @@ macro_rules! encode_msg { }} } +impl PeerManager where + CM::Target: ChannelMessageHandler, + L::Target: Logger { + /// Constructs a new PeerManager with the given ChannelMessageHandler. No routing message + /// handler is used and network graph messages are ignored. + /// + /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be + /// cryptographically secure random bytes. + /// + /// (C-not exported) as we can't export a PeerManager with a dummy route handler + pub fn new_channel_only(channel_message_handler: CM, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self { + Self::new(MessageHandler { + chan_handler: channel_message_handler, + route_handler: IgnoringMessageHandler{}, + }, our_node_secret, ephemeral_random_data, logger) + } +} + +impl PeerManager where + RM::Target: RoutingMessageHandler, + L::Target: Logger { + /// Constructs a new PeerManager with the given RoutingMessageHandler. No channel message + /// handler is used and messages related to channels will be ignored (or generate error + /// messages). Note that some other lightning implementations time-out connections after some + /// time if no channel is built with the peer. + /// + /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be + /// cryptographically secure random bytes. + /// + /// (C-not exported) as we can't export a PeerManager with a dummy channel handler + pub fn new_routing_only(routing_message_handler: RM, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self { + Self::new(MessageHandler { + chan_handler: ErroringMessageHandler::new(), + route_handler: routing_message_handler, + }, our_node_secret, ephemeral_random_data, logger) + } +} + /// Manages and reacts to connection events. You probably want to use file descriptors as PeerIds. /// PeerIds may repeat, but only after socket_disconnected() has been called. -impl PeerManager where CM::Target: msgs::ChannelMessageHandler, L::Target: Logger { +impl PeerManager where + CM::Target: ChannelMessageHandler, + RM::Target: RoutingMessageHandler, + L::Target: Logger { /// Constructs a new PeerManager with the given message handlers and node_id secret key /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be /// cryptographically secure random bytes. - pub fn new(message_handler: MessageHandler, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> PeerManager { + pub fn new(message_handler: MessageHandler, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self { let mut ephemeral_key_midstate = Sha256::engine(); ephemeral_key_midstate.input(ephemeral_random_data); @@ -280,7 +464,6 @@ impl PeerManager PeerManager PeerManager PeerManager PeerManager PeerManager { if peer.pending_read_is_header { @@ -606,177 +787,13 @@ impl PeerManager { - if msg.features.requires_unknown_bits() { - log_info!(self.logger, "Peer global features required unknown version bits"); - return Err(PeerHandleError{ no_connection_possible: true }); - } - if msg.features.requires_unknown_bits() { - log_info!(self.logger, "Peer local features required unknown version bits"); - return Err(PeerHandleError{ no_connection_possible: true }); - } - if peer.their_features.is_some() { - return Err(PeerHandleError{ no_connection_possible: false }); - } - - log_info!(self.logger, "Received peer Init message: data_loss_protect: {}, initial_routing_sync: {}, upfront_shutdown_script: {}, static_remote_key: {}, unkown local flags: {}, unknown global flags: {}", - if msg.features.supports_data_loss_protect() { "supported" } else { "not supported"}, - if msg.features.initial_routing_sync() { "requested" } else { "not requested" }, - if msg.features.supports_upfront_shutdown_script() { "supported" } else { "not supported"}, - if msg.features.supports_static_remote_key() { "supported" } else { "not supported"}, - if msg.features.supports_unknown_bits() { "present" } else { "none" }, - if msg.features.supports_unknown_bits() { "present" } else { "none" }); - - if msg.features.initial_routing_sync() { - peer.sync_status = InitSyncTracker::ChannelsSyncing(0); - peers.peers_needing_send.insert(peer_descriptor.clone()); - } - if !msg.features.supports_static_remote_key() { - log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting with no_connection_possible", log_pubkey!(peer.their_node_id.unwrap())); - return Err(PeerHandleError{ no_connection_possible: true }); - } - - if !peer.outbound { - let mut features = InitFeatures::known(); - if !self.message_handler.route_handler.should_request_full_sync(&peer.their_node_id.unwrap()) { - features.clear_initial_routing_sync(); - } - - let resp = msgs::Init { features }; - self.enqueue_message(&mut peers.peers_needing_send, peer, peer_descriptor.clone(), &resp); - } - - self.message_handler.chan_handler.peer_connected(&peer.their_node_id.unwrap(), &msg); - peer.their_features = Some(msg.features); - }, - wire::Message::Error(msg) => { - let mut data_is_printable = true; - for b in msg.data.bytes() { - if b < 32 || b > 126 { - data_is_printable = false; - break; - } - } - - if data_is_printable { - log_debug!(self.logger, "Got Err message from {}: {}", log_pubkey!(peer.their_node_id.unwrap()), msg.data); - } else { - log_debug!(self.logger, "Got Err message from {} with non-ASCII error message", log_pubkey!(peer.their_node_id.unwrap())); - } - self.message_handler.chan_handler.handle_error(&peer.their_node_id.unwrap(), &msg); - if msg.channel_id == [0; 32] { - return Err(PeerHandleError{ no_connection_possible: true }); - } - }, - - wire::Message::Ping(msg) => { - if msg.ponglen < 65532 { - let resp = msgs::Pong { byteslen: msg.ponglen }; - self.enqueue_message(&mut peers.peers_needing_send, peer, peer_descriptor.clone(), &resp); - } - }, - wire::Message::Pong(_msg) => { - peer.awaiting_pong = false; - }, - - // Channel messages: - wire::Message::OpenChannel(msg) => { - self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg); - }, - wire::Message::AcceptChannel(msg) => { - self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg); - }, - - wire::Message::FundingCreated(msg) => { - self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg); - }, - wire::Message::FundingSigned(msg) => { - self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg); - }, - wire::Message::FundingLocked(msg) => { - self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg); - }, - - wire::Message::Shutdown(msg) => { - self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), &msg); - }, - wire::Message::ClosingSigned(msg) => { - self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg); - }, - - // Commitment messages: - wire::Message::UpdateAddHTLC(msg) => { - self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg); - }, - wire::Message::UpdateFulfillHTLC(msg) => { - self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg); - }, - wire::Message::UpdateFailHTLC(msg) => { - self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg); - }, - wire::Message::UpdateFailMalformedHTLC(msg) => { - self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg); - }, - - wire::Message::CommitmentSigned(msg) => { - self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg); - }, - wire::Message::RevokeAndACK(msg) => { - self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg); - }, - wire::Message::UpdateFee(msg) => { - self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg); - }, - wire::Message::ChannelReestablish(msg) => { - self.message_handler.chan_handler.handle_channel_reestablish(&peer.their_node_id.unwrap(), &msg); - }, - - // Routing messages: - wire::Message::AnnouncementSignatures(msg) => { - self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg); - }, - wire::Message::ChannelAnnouncement(msg) => { - let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_announcement(&msg)); - - if should_forward { - // TODO: forward msg along to all our other peers! - } - }, - wire::Message::NodeAnnouncement(msg) => { - let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_node_announcement(&msg)); - - if should_forward { - // TODO: forward msg along to all our other peers! - } - }, - wire::Message::ChannelUpdate(msg) => { - let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_update(&msg)); - - if should_forward { - // TODO: forward msg along to all our other peers! - } - }, - - // Unknown messages: - wire::Message::Unknown(msg_type) if msg_type.is_even() => { - log_debug!(self.logger, "Received unknown even message of type {}, disconnecting peer!", msg_type); - // Fail the channel if message is an even, unknown type as per BOLT #1. - return Err(PeerHandleError{ no_connection_possible: true }); - }, - wire::Message::Unknown(msg_type) => { - log_trace!(self.logger, "Received unknown odd message of type {}, ignoring", msg_type); - }, + if let Err(handling_error) = self.handle_message(&mut peers.peers_needing_send, peer, peer_descriptor.clone(), message){ + match handling_error { + MessageHandlingError::PeerHandleError(e) => { return Err(e) }, + MessageHandlingError::LightningError(e) => { + try_potential_handleerror!(Err(e)); + }, + } } } } @@ -796,6 +813,198 @@ impl PeerManager, peer: &mut Peer, peer_descriptor: Descriptor, message: wire::Message) -> Result<(), MessageHandlingError> { + log_trace!(self.logger, "Received message of type {} from {}", message.type_id(), log_pubkey!(peer.their_node_id.unwrap())); + + // Need an Init as first message + if let wire::Message::Init(_) = message { + } else if peer.their_features.is_none() { + log_trace!(self.logger, "Peer {} sent non-Init first message", log_pubkey!(peer.their_node_id.unwrap())); + return Err(PeerHandleError{ no_connection_possible: false }.into()); + } + + match message { + // Setup and Control messages: + wire::Message::Init(msg) => { + if msg.features.requires_unknown_bits() { + log_info!(self.logger, "Peer features required unknown version bits"); + return Err(PeerHandleError{ no_connection_possible: true }.into()); + } + if peer.their_features.is_some() { + return Err(PeerHandleError{ no_connection_possible: false }.into()); + } + + log_info!( + self.logger, "Received peer Init message: data_loss_protect: {}, initial_routing_sync: {}, upfront_shutdown_script: {}, gossip_queries: {}, static_remote_key: {}, unknown flags (local and global): {}", + if msg.features.supports_data_loss_protect() { "supported" } else { "not supported"}, + if msg.features.initial_routing_sync() { "requested" } else { "not requested" }, + if msg.features.supports_upfront_shutdown_script() { "supported" } else { "not supported"}, + if msg.features.supports_gossip_queries() { "supported" } else { "not supported" }, + if msg.features.supports_static_remote_key() { "supported" } else { "not supported"}, + if msg.features.supports_unknown_bits() { "present" } else { "none" } + ); + + if msg.features.initial_routing_sync() { + peer.sync_status = InitSyncTracker::ChannelsSyncing(0); + peers_needing_send.insert(peer_descriptor.clone()); + } + if !msg.features.supports_static_remote_key() { + log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting with no_connection_possible", log_pubkey!(peer.their_node_id.unwrap())); + return Err(PeerHandleError{ no_connection_possible: true }.into()); + } + + self.message_handler.route_handler.sync_routing_table(&peer.their_node_id.unwrap(), &msg); + + self.message_handler.chan_handler.peer_connected(&peer.their_node_id.unwrap(), &msg); + peer.their_features = Some(msg.features); + }, + wire::Message::Error(msg) => { + let mut data_is_printable = true; + for b in msg.data.bytes() { + if b < 32 || b > 126 { + data_is_printable = false; + break; + } + } + + if data_is_printable { + log_debug!(self.logger, "Got Err message from {}: {}", log_pubkey!(peer.their_node_id.unwrap()), msg.data); + } else { + log_debug!(self.logger, "Got Err message from {} with non-ASCII error message", log_pubkey!(peer.their_node_id.unwrap())); + } + self.message_handler.chan_handler.handle_error(&peer.their_node_id.unwrap(), &msg); + if msg.channel_id == [0; 32] { + return Err(PeerHandleError{ no_connection_possible: true }.into()); + } + }, + + wire::Message::Ping(msg) => { + if msg.ponglen < 65532 { + let resp = msgs::Pong { byteslen: msg.ponglen }; + self.enqueue_message(peers_needing_send, peer, peer_descriptor.clone(), &resp); + } + }, + wire::Message::Pong(_msg) => { + peer.awaiting_pong = false; + }, + + // Channel messages: + wire::Message::OpenChannel(msg) => { + self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg); + }, + wire::Message::AcceptChannel(msg) => { + self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg); + }, + + wire::Message::FundingCreated(msg) => { + self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg); + }, + wire::Message::FundingSigned(msg) => { + self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg); + }, + wire::Message::FundingLocked(msg) => { + self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg); + }, + + wire::Message::Shutdown(msg) => { + self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), peer.their_features.as_ref().unwrap(), &msg); + }, + wire::Message::ClosingSigned(msg) => { + self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg); + }, + + // Commitment messages: + wire::Message::UpdateAddHTLC(msg) => { + self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg); + }, + wire::Message::UpdateFulfillHTLC(msg) => { + self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg); + }, + wire::Message::UpdateFailHTLC(msg) => { + self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg); + }, + wire::Message::UpdateFailMalformedHTLC(msg) => { + self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg); + }, + + wire::Message::CommitmentSigned(msg) => { + self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg); + }, + wire::Message::RevokeAndACK(msg) => { + self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg); + }, + wire::Message::UpdateFee(msg) => { + self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg); + }, + wire::Message::ChannelReestablish(msg) => { + self.message_handler.chan_handler.handle_channel_reestablish(&peer.their_node_id.unwrap(), &msg); + }, + + // Routing messages: + wire::Message::AnnouncementSignatures(msg) => { + self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg); + }, + wire::Message::ChannelAnnouncement(msg) => { + let should_forward = match self.message_handler.route_handler.handle_channel_announcement(&msg) { + Ok(v) => v, + Err(e) => { return Err(e.into()); }, + }; + + if should_forward { + // TODO: forward msg along to all our other peers! + } + }, + wire::Message::NodeAnnouncement(msg) => { + let should_forward = match self.message_handler.route_handler.handle_node_announcement(&msg) { + Ok(v) => v, + Err(e) => { return Err(e.into()); }, + }; + + if should_forward { + // TODO: forward msg along to all our other peers! + } + }, + wire::Message::ChannelUpdate(msg) => { + self.message_handler.chan_handler.handle_channel_update(&peer.their_node_id.unwrap(), &msg); + let should_forward = match self.message_handler.route_handler.handle_channel_update(&msg) { + Ok(v) => v, + Err(e) => { return Err(e.into()); }, + }; + + if should_forward { + // TODO: forward msg along to all our other peers! + } + }, + wire::Message::QueryShortChannelIds(msg) => { + self.message_handler.route_handler.handle_query_short_channel_ids(&peer.their_node_id.unwrap(), msg)?; + }, + wire::Message::ReplyShortChannelIdsEnd(msg) => { + self.message_handler.route_handler.handle_reply_short_channel_ids_end(&peer.their_node_id.unwrap(), msg)?; + }, + wire::Message::QueryChannelRange(msg) => { + self.message_handler.route_handler.handle_query_channel_range(&peer.their_node_id.unwrap(), msg)?; + }, + wire::Message::ReplyChannelRange(msg) => { + self.message_handler.route_handler.handle_reply_channel_range(&peer.their_node_id.unwrap(), msg)?; + }, + wire::Message::GossipTimestampFilter(_msg) => { + // TODO: handle message + }, + + // Unknown messages: + wire::Message::Unknown(msg_type) if msg_type.is_even() => { + log_debug!(self.logger, "Received unknown even message of type {}, disconnecting peer!", msg_type); + // Fail the channel if message is an even, unknown type as per BOLT #1. + return Err(PeerHandleError{ no_connection_possible: true }.into()); + }, + wire::Message::Unknown(msg_type) => { + log_trace!(self.logger, "Received unknown odd message of type {}, ignoring", msg_type); + } + }; + Ok(()) + } + /// Checks for any events generated by our handlers and processes them. Includes sending most /// response messages as well as messages generated by calls to handler functions directly (eg /// functions like ChannelManager::process_pending_htlc_forward or send_payment). @@ -805,8 +1014,9 @@ impl PeerManager PeerManager { + let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {}); + peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg))); + self.do_attempt_write_data(&mut descriptor, peer); + }, + MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => { + let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {}); + peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg))); + self.do_attempt_write_data(&mut descriptor, peer); + } + MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => { + log_trace!(self.logger, "Handling SendReplyChannelRange event in peer_handler for node {} with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}", + log_pubkey!(node_id), + msg.short_channel_ids.len(), + msg.first_blocknum, + msg.number_of_blocks, + msg.sync_complete); + let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {}); + peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg))); + self.do_attempt_write_data(&mut descriptor, peer); } } } @@ -1100,11 +1331,29 @@ impl PeerManager PeerManager Vec { let mut cfgs = Vec::new(); for _ in 0..peer_count { - let chan_handler = test_utils::TestChannelMessageHandler::new(); - let logger = test_utils::TestLogger::new(); cfgs.push( PeerManagerCfg{ - chan_handler, - logger, + chan_handler: test_utils::TestChannelMessageHandler::new(), + logger: test_utils::TestLogger::new(), + routing_handler: test_utils::TestRoutingMessageHandler::new(), } ); } @@ -1226,30 +1467,20 @@ mod tests { cfgs } - fn create_network<'a>(peer_count: usize, cfgs: &'a Vec, routing_handlers: Option<&'a Vec>>) -> Vec> { + fn create_network<'a>(peer_count: usize, cfgs: &'a Vec) -> Vec> { let mut peers = Vec::new(); - let mut rng = thread_rng(); - let mut ephemeral_bytes = [0; 32]; - rng.fill_bytes(&mut ephemeral_bytes); - for i in 0..peer_count { - let router = if let Some(routers) = routing_handlers { routers[i].clone() } else { - Arc::new(test_utils::TestRoutingMessageHandler::new()) - }; - let node_id = { - let mut key_slice = [0;32]; - rng.fill_bytes(&mut key_slice); - SecretKey::from_slice(&key_slice).unwrap() - }; - let msg_handler = MessageHandler { chan_handler: &cfgs[i].chan_handler, route_handler: router }; - let peer = PeerManager::new(msg_handler, node_id, &ephemeral_bytes, &cfgs[i].logger); + let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap(); + let ephemeral_bytes = [i as u8; 32]; + let msg_handler = MessageHandler { chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler }; + let peer = PeerManager::new(msg_handler, node_secret, &ephemeral_bytes, &cfgs[i].logger); peers.push(peer); } peers } - fn establish_connection<'a>(peer_a: &PeerManager, peer_b: &PeerManager) -> (FileDescriptor, FileDescriptor) { + fn establish_connection<'a>(peer_a: &PeerManager, peer_b: &PeerManager) -> (FileDescriptor, FileDescriptor) { let secp_ctx = Secp256k1::new(); let a_id = PublicKey::from_secret_key(&secp_ctx, &peer_a.our_node_secret); let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) }; @@ -1262,20 +1493,13 @@ mod tests { (fd_a.clone(), fd_b.clone()) } - fn establish_connection_and_read_events<'a>(peer_a: &PeerManager, peer_b: &PeerManager) -> (FileDescriptor, FileDescriptor) { - let (mut fd_a, mut fd_b) = establish_connection(peer_a, peer_b); - assert_eq!(peer_b.read_event(&mut fd_b, &fd_a.outbound_data.lock().unwrap().split_off(0)).unwrap(), false); - assert_eq!(peer_a.read_event(&mut fd_a, &fd_b.outbound_data.lock().unwrap().split_off(0)).unwrap(), false); - (fd_a.clone(), fd_b.clone()) - } - #[test] fn test_disconnect_peer() { // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and // push a DisconnectPeer event to remove the node flagged by id let cfgs = create_peermgr_cfgs(2); let chan_handler = test_utils::TestChannelMessageHandler::new(); - let mut peers = create_network(2, &cfgs, None); + let mut peers = create_network(2, &cfgs); establish_connection(&peers[0], &peers[1]); assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1); @@ -1297,132 +1521,26 @@ mod tests { fn test_timer_tick_occurred() { // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer. let cfgs = create_peermgr_cfgs(2); - let peers = create_network(2, &cfgs, None); + let peers = create_network(2, &cfgs); establish_connection(&peers[0], &peers[1]); assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1); // peers[0] awaiting_pong is set to true, but the Peer is still connected - peers[0].timer_tick_occured(); + peers[0].timer_tick_occurred(); assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1); - // Since timer_tick_occured() is called again when awaiting_pong is true, all Peers are disconnected - peers[0].timer_tick_occured(); + // Since timer_tick_occurred() is called again when awaiting_pong is true, all Peers are disconnected + peers[0].timer_tick_occurred(); assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0); } - pub struct TestRoutingMessageHandler { - pub chan_upds_recvd: AtomicUsize, - pub chan_anns_recvd: AtomicUsize, - pub chan_anns_sent: AtomicUsize, - } - - impl TestRoutingMessageHandler { - pub fn new() -> Self { - TestRoutingMessageHandler { - chan_upds_recvd: AtomicUsize::new(0), - chan_anns_recvd: AtomicUsize::new(0), - chan_anns_sent: AtomicUsize::new(0), - } - } - - } - impl msgs::RoutingMessageHandler for TestRoutingMessageHandler { - fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result { - Err(msgs::LightningError { err: "", action: msgs::ErrorAction::IgnoreError }) - } - fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result { - self.chan_anns_recvd.fetch_add(1, Ordering::AcqRel); - Err(msgs::LightningError { err: "", action: msgs::ErrorAction::IgnoreError }) - } - fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result { - self.chan_upds_recvd.fetch_add(1, Ordering::AcqRel); - Err(msgs::LightningError { err: "", action: msgs::ErrorAction::IgnoreError }) - } - fn handle_htlc_fail_channel_update(&self, _update: &msgs::HTLCFailChannelUpdate) {} - fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option, Option)> { - let mut chan_anns = Vec::new(); - const TOTAL_UPDS: u64 = 100; - let end: u64 = min(starting_point + batch_amount as u64, TOTAL_UPDS - self.chan_anns_sent.load(Ordering::Acquire) as u64); - for i in starting_point..end { - let chan_upd_1 = get_dummy_channel_update(i); - let chan_upd_2 = get_dummy_channel_update(i); - let chan_ann = get_dummy_channel_announcement(i); - - chan_anns.push((chan_ann, Some(chan_upd_1), Some(chan_upd_2))); - } - - self.chan_anns_sent.fetch_add(chan_anns.len(), Ordering::AcqRel); - chan_anns - } - - fn get_next_node_announcements(&self, _starting_point: Option<&PublicKey>, _batch_amount: u8) -> Vec { - Vec::new() - } - - fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool { - true - } - } - - fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnouncement { - use bitcoin::secp256k1::ffi::Signature as FFISignature; - let secp_ctx = Secp256k1::new(); - let network = Network::Testnet; - let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap(); - let node_2_privkey = SecretKey::from_slice(&[41; 32]).unwrap(); - let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap(); - let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap(); - let unsigned_ann = msgs::UnsignedChannelAnnouncement { - features: ChannelFeatures::known(), - chain_hash: genesis_block(network).header.bitcoin_hash(), - short_channel_id: short_chan_id, - node_id_1: PublicKey::from_secret_key(&secp_ctx, &node_1_privkey), - node_id_2: PublicKey::from_secret_key(&secp_ctx, &node_2_privkey), - bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, &node_1_btckey), - bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, &node_2_btckey), - excess_data: Vec::new(), - }; - - msgs::ChannelAnnouncement { - node_signature_1: Signature::from(FFISignature::new()), - node_signature_2: Signature::from(FFISignature::new()), - bitcoin_signature_1: Signature::from(FFISignature::new()), - bitcoin_signature_2: Signature::from(FFISignature::new()), - contents: unsigned_ann, - } - } - - fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate { - use bitcoin::secp256k1::ffi::Signature as FFISignature; - let network = Network::Testnet; - msgs::ChannelUpdate { - signature: Signature::from(FFISignature::new()), - contents: msgs::UnsignedChannelUpdate { - chain_hash: genesis_block(network).header.bitcoin_hash(), - short_channel_id: short_chan_id, - timestamp: 0, - flags: 0, - cltv_expiry_delta: 0, - htlc_minimum_msat: 0, - fee_base_msat: 0, - fee_proportional_millionths: 0, - excess_data: vec![], - } - } - } - #[test] fn test_do_attempt_write_data() { // Create 2 peers with custom TestRoutingMessageHandlers and connect them. let cfgs = create_peermgr_cfgs(2); - let mut routing_handlers: Vec> = Vec::new(); - let mut routing_handlers_concrete: Vec> = Vec::new(); - for _ in 0..2 { - let routing_handler = Arc::new(TestRoutingMessageHandler::new()); - routing_handlers.push(routing_handler.clone()); - routing_handlers_concrete.push(routing_handler.clone()); - } - let peers = create_network(2, &cfgs, Some(&routing_handlers)); + cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release); + cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release); + let peers = create_network(2, &cfgs); // By calling establish_connect, we trigger do_attempt_write_data between // the peers. Previously this function would mistakenly enter an infinite loop @@ -1438,52 +1556,9 @@ mod tests { // Check that each peer has received the expected number of channel updates and channel // announcements. - assert_eq!(routing_handlers_concrete[0].clone().chan_upds_recvd.load(Ordering::Acquire), 100); - assert_eq!(routing_handlers_concrete[0].clone().chan_anns_recvd.load(Ordering::Acquire), 50); - assert_eq!(routing_handlers_concrete[1].clone().chan_upds_recvd.load(Ordering::Acquire), 100); - assert_eq!(routing_handlers_concrete[1].clone().chan_anns_recvd.load(Ordering::Acquire), 50); - } - - #[test] - fn limit_initial_routing_sync_requests() { - // Inbound peer 0 requests initial_routing_sync, but outbound peer 1 does not. - { - let cfgs = create_peermgr_cfgs(2); - let routing_handlers: Vec> = vec![ - Arc::new(test_utils::TestRoutingMessageHandler::new().set_request_full_sync()), - Arc::new(test_utils::TestRoutingMessageHandler::new()), - ]; - let peers = create_network(2, &cfgs, Some(&routing_handlers)); - let (fd_0_to_1, fd_1_to_0) = establish_connection_and_read_events(&peers[0], &peers[1]); - - let peer_0 = peers[0].peers.lock().unwrap(); - let peer_1 = peers[1].peers.lock().unwrap(); - - let peer_0_features = peer_1.peers.get(&fd_1_to_0).unwrap().their_features.as_ref(); - let peer_1_features = peer_0.peers.get(&fd_0_to_1).unwrap().their_features.as_ref(); - - assert!(peer_0_features.unwrap().initial_routing_sync()); - assert!(!peer_1_features.unwrap().initial_routing_sync()); - } - - // Outbound peer 1 requests initial_routing_sync, but inbound peer 0 does not. - { - let cfgs = create_peermgr_cfgs(2); - let routing_handlers: Vec> = vec![ - Arc::new(test_utils::TestRoutingMessageHandler::new()), - Arc::new(test_utils::TestRoutingMessageHandler::new().set_request_full_sync()), - ]; - let peers = create_network(2, &cfgs, Some(&routing_handlers)); - let (fd_0_to_1, fd_1_to_0) = establish_connection_and_read_events(&peers[0], &peers[1]); - - let peer_0 = peers[0].peers.lock().unwrap(); - let peer_1 = peers[1].peers.lock().unwrap(); - - let peer_0_features = peer_1.peers.get(&fd_1_to_0).unwrap().their_features.as_ref(); - let peer_1_features = peer_0.peers.get(&fd_0_to_1).unwrap().their_features.as_ref(); - - assert!(!peer_0_features.unwrap().initial_routing_sync()); - assert!(peer_1_features.unwrap().initial_routing_sync()); - } + assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 100); + assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 50); + assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 100); + assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 50); } }