From 05e2a7dc48f11a7f258f59acd769e4874c022a87 Mon Sep 17 00:00:00 2001 From: Matt Corallo Date: Sat, 16 Jun 2018 19:39:21 -0400 Subject: [PATCH] Support responding to Ping messages in peer_handler --- src/ln/msgs.rs | 57 ++++++++++++++++++++++++++++++++++++++++++ src/ln/peer_handler.rs | 11 ++++++-- 2 files changed, 66 insertions(+), 2 deletions(-) diff --git a/src/ln/msgs.rs b/src/ln/msgs.rs index f0f1d4890..869b5115f 100644 --- a/src/ln/msgs.rs +++ b/src/ln/msgs.rs @@ -132,6 +132,15 @@ pub struct Init { pub local_features: LocalFeatures, } +pub struct Ping { + pub ponglen: u16, + pub byteslen: u16, +} + +pub struct Pong { + pub byteslen: u16, +} + pub struct OpenChannel { pub chain_hash: Sha256dHash, pub temporary_channel_id: Uint256, @@ -572,6 +581,54 @@ impl MsgEncodable for Init { } } +impl MsgDecodable for Ping { + fn decode(v: &[u8]) -> Result { + if v.len() < 4 { + return Err(DecodeError::WrongLength); + } + let ponglen = byte_utils::slice_to_be16(&v[0..2]); + let byteslen = byte_utils::slice_to_be16(&v[2..4]); + if v.len() < 4 + byteslen as usize { + return Err(DecodeError::WrongLength); + } + Ok(Self { + ponglen, + byteslen, + }) + } +} +impl MsgEncodable for Ping { + fn encode(&self) -> Vec { + let mut res = Vec::with_capacity(self.byteslen as usize + 2); + res.extend_from_slice(&byte_utils::be16_to_array(self.byteslen)); + res.resize(2 + self.byteslen as usize, 0); + res + } +} + +impl MsgDecodable for Pong { + fn decode(v: &[u8]) -> Result { + if v.len() < 2 { + return Err(DecodeError::WrongLength); + } + let byteslen = byte_utils::slice_to_be16(&v[0..2]); + if v.len() < 2 + byteslen as usize { + return Err(DecodeError::WrongLength); + } + Ok(Self { + byteslen + }) + } +} +impl MsgEncodable for Pong { + fn encode(&self) -> Vec { + let mut res = Vec::with_capacity(self.byteslen as usize + 2); + res.extend_from_slice(&byte_utils::be16_to_array(self.byteslen)); + res.resize(2 + self.byteslen as usize, 0); + res + } +} + impl MsgDecodable for OpenChannel { fn decode(v: &[u8]) -> Result { if v.len() < 2*32+6*8+4+2*2+6*33+1 { diff --git a/src/ln/peer_handler.rs b/src/ln/peer_handler.rs index 3c4196519..30900cab4 100644 --- a/src/ln/peer_handler.rs +++ b/src/ln/peer_handler.rs @@ -390,8 +390,15 @@ impl PeerManager { 17 => { // Error msg }, - 18 => { }, // ping - 19 => { }, // pong + + 18 => { + let msg = try_potential_decodeerror!(msgs::Ping::decode(&msg_data[2..])); + let resp = msgs::Pong { byteslen: msg.ponglen }; + encode_and_send_msg!(resp, 19); + }, + 19 => { + try_potential_decodeerror!(msgs::Pong::decode(&msg_data[2..])); + }, // Channel control: 32 => { -- 2.39.5