Skip to content

Commit

Permalink
Switch to protobuf version 3
Browse files Browse the repository at this point in the history
  • Loading branch information
umgefahren committed Jun 14, 2024
1 parent 4fac6da commit ff806a3
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 84 deletions.
2 changes: 1 addition & 1 deletion protocols/autonat/src/v2/generated/structs.proto
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
syntax = "proto2";
syntax = "proto3";

package structs;

Expand Down
72 changes: 36 additions & 36 deletions protocols/autonat/src/v2/generated/structs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ impl Default for OneOfmsg {
#[derive(Debug, Default, PartialEq, Clone)]
pub struct DialRequest {
pub addrs: Vec<Vec<u8>>,
pub nonce: Option<u64>,
pub nonce: u64,
}

impl<'a> MessageRead<'a> for DialRequest {
Expand All @@ -129,7 +129,7 @@ impl<'a> MessageRead<'a> for DialRequest {
while !r.is_eof() {
match r.next_tag(bytes) {
Ok(10) => msg.addrs.push(r.read_bytes(bytes)?.to_owned()),
Ok(17) => msg.nonce = Some(r.read_fixed64(bytes)?),
Ok(17) => msg.nonce = r.read_fixed64(bytes)?,
Ok(t) => { r.read_unknown(bytes, t)?; }
Err(e) => return Err(e),
}
Expand All @@ -142,30 +142,30 @@ impl MessageWrite for DialRequest {
fn get_size(&self) -> usize {
0
+ self.addrs.iter().map(|s| 1 + sizeof_len((s).len())).sum::<usize>()
+ self.nonce.as_ref().map_or(0, |_| 1 + 8)
+ if self.nonce == 0u64 { 0 } else { 1 + 8 }
}

fn write_message<W: WriterBackend>(&self, w: &mut Writer<W>) -> Result<()> {
for s in &self.addrs { w.write_with_tag(10, |w| w.write_bytes(&**s))?; }
if let Some(ref s) = self.nonce { w.write_with_tag(17, |w| w.write_fixed64(*s))?; }
if self.nonce != 0u64 { w.write_with_tag(17, |w| w.write_fixed64(*&self.nonce))?; }
Ok(())
}
}

#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Debug, Default, PartialEq, Clone)]
pub struct DialDataRequest {
pub addrIdx: Option<u32>,
pub numBytes: Option<u64>,
pub addrIdx: u32,
pub numBytes: u64,
}

impl<'a> MessageRead<'a> for DialDataRequest {
fn from_reader(r: &mut BytesReader, bytes: &'a [u8]) -> Result<Self> {
let mut msg = Self::default();
while !r.is_eof() {
match r.next_tag(bytes) {
Ok(8) => msg.addrIdx = Some(r.read_uint32(bytes)?),
Ok(16) => msg.numBytes = Some(r.read_uint64(bytes)?),
Ok(8) => msg.addrIdx = r.read_uint32(bytes)?,
Ok(16) => msg.numBytes = r.read_uint64(bytes)?,
Ok(t) => { r.read_unknown(bytes, t)?; }
Err(e) => return Err(e),
}
Expand All @@ -177,33 +177,33 @@ impl<'a> MessageRead<'a> for DialDataRequest {
impl MessageWrite for DialDataRequest {
fn get_size(&self) -> usize {
0
+ self.addrIdx.as_ref().map_or(0, |m| 1 + sizeof_varint(*(m) as u64))
+ self.numBytes.as_ref().map_or(0, |m| 1 + sizeof_varint(*(m) as u64))
+ if self.addrIdx == 0u32 { 0 } else { 1 + sizeof_varint(*(&self.addrIdx) as u64) }
+ if self.numBytes == 0u64 { 0 } else { 1 + sizeof_varint(*(&self.numBytes) as u64) }
}

fn write_message<W: WriterBackend>(&self, w: &mut Writer<W>) -> Result<()> {
if let Some(ref s) = self.addrIdx { w.write_with_tag(8, |w| w.write_uint32(*s))?; }
if let Some(ref s) = self.numBytes { w.write_with_tag(16, |w| w.write_uint64(*s))?; }
if self.addrIdx != 0u32 { w.write_with_tag(8, |w| w.write_uint32(*&self.addrIdx))?; }
if self.numBytes != 0u64 { w.write_with_tag(16, |w| w.write_uint64(*&self.numBytes))?; }
Ok(())
}
}

#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Debug, Default, PartialEq, Clone)]
pub struct DialResponse {
pub status: Option<structs::mod_DialResponse::ResponseStatus>,
pub addrIdx: Option<u32>,
pub dialStatus: Option<structs::DialStatus>,
pub status: structs::mod_DialResponse::ResponseStatus,
pub addrIdx: u32,
pub dialStatus: structs::DialStatus,
}

impl<'a> MessageRead<'a> for DialResponse {
fn from_reader(r: &mut BytesReader, bytes: &'a [u8]) -> Result<Self> {
let mut msg = Self::default();
while !r.is_eof() {
match r.next_tag(bytes) {
Ok(8) => msg.status = Some(r.read_enum(bytes)?),
Ok(16) => msg.addrIdx = Some(r.read_uint32(bytes)?),
Ok(24) => msg.dialStatus = Some(r.read_enum(bytes)?),
Ok(8) => msg.status = r.read_enum(bytes)?,
Ok(16) => msg.addrIdx = r.read_uint32(bytes)?,
Ok(24) => msg.dialStatus = r.read_enum(bytes)?,
Ok(t) => { r.read_unknown(bytes, t)?; }
Err(e) => return Err(e),
}
Expand All @@ -215,15 +215,15 @@ impl<'a> MessageRead<'a> for DialResponse {
impl MessageWrite for DialResponse {
fn get_size(&self) -> usize {
0
+ self.status.as_ref().map_or(0, |m| 1 + sizeof_varint(*(m) as u64))
+ self.addrIdx.as_ref().map_or(0, |m| 1 + sizeof_varint(*(m) as u64))
+ self.dialStatus.as_ref().map_or(0, |m| 1 + sizeof_varint(*(m) as u64))
+ if self.status == structs::mod_DialResponse::ResponseStatus::E_INTERNAL_ERROR { 0 } else { 1 + sizeof_varint(*(&self.status) as u64) }
+ if self.addrIdx == 0u32 { 0 } else { 1 + sizeof_varint(*(&self.addrIdx) as u64) }
+ if self.dialStatus == structs::DialStatus::UNUSED { 0 } else { 1 + sizeof_varint(*(&self.dialStatus) as u64) }
}

fn write_message<W: WriterBackend>(&self, w: &mut Writer<W>) -> Result<()> {
if let Some(ref s) = self.status { w.write_with_tag(8, |w| w.write_enum(*s as i32))?; }
if let Some(ref s) = self.addrIdx { w.write_with_tag(16, |w| w.write_uint32(*s))?; }
if let Some(ref s) = self.dialStatus { w.write_with_tag(24, |w| w.write_enum(*s as i32))?; }
if self.status != structs::mod_DialResponse::ResponseStatus::E_INTERNAL_ERROR { w.write_with_tag(8, |w| w.write_enum(*&self.status as i32))?; }
if self.addrIdx != 0u32 { w.write_with_tag(16, |w| w.write_uint32(*&self.addrIdx))?; }
if self.dialStatus != structs::DialStatus::UNUSED { w.write_with_tag(24, |w| w.write_enum(*&self.dialStatus as i32))?; }
Ok(())
}
}
Expand Down Expand Up @@ -274,15 +274,15 @@ impl<'a> From<&'a str> for ResponseStatus {
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Debug, Default, PartialEq, Clone)]
pub struct DialDataResponse {
pub data: Option<Vec<u8>>,
pub data: Vec<u8>,
}

impl<'a> MessageRead<'a> for DialDataResponse {
fn from_reader(r: &mut BytesReader, bytes: &'a [u8]) -> Result<Self> {
let mut msg = Self::default();
while !r.is_eof() {
match r.next_tag(bytes) {
Ok(10) => msg.data = Some(r.read_bytes(bytes)?.to_owned()),
Ok(10) => msg.data = r.read_bytes(bytes)?.to_owned(),
Ok(t) => { r.read_unknown(bytes, t)?; }
Err(e) => return Err(e),
}
Expand All @@ -294,27 +294,27 @@ impl<'a> MessageRead<'a> for DialDataResponse {
impl MessageWrite for DialDataResponse {
fn get_size(&self) -> usize {
0
+ self.data.as_ref().map_or(0, |m| 1 + sizeof_len((m).len()))
+ if self.data.is_empty() { 0 } else { 1 + sizeof_len((&self.data).len()) }
}

fn write_message<W: WriterBackend>(&self, w: &mut Writer<W>) -> Result<()> {
if let Some(ref s) = self.data { w.write_with_tag(10, |w| w.write_bytes(&**s))?; }
if !self.data.is_empty() { w.write_with_tag(10, |w| w.write_bytes(&**&self.data))?; }
Ok(())
}
}

#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Debug, Default, PartialEq, Clone)]
pub struct DialBack {
pub nonce: Option<u64>,
pub nonce: u64,
}

impl<'a> MessageRead<'a> for DialBack {
fn from_reader(r: &mut BytesReader, bytes: &'a [u8]) -> Result<Self> {
let mut msg = Self::default();
while !r.is_eof() {
match r.next_tag(bytes) {
Ok(9) => msg.nonce = Some(r.read_fixed64(bytes)?),
Ok(9) => msg.nonce = r.read_fixed64(bytes)?,
Ok(t) => { r.read_unknown(bytes, t)?; }
Err(e) => return Err(e),
}
Expand All @@ -326,27 +326,27 @@ impl<'a> MessageRead<'a> for DialBack {
impl MessageWrite for DialBack {
fn get_size(&self) -> usize {
0
+ self.nonce.as_ref().map_or(0, |_| 1 + 8)
+ if self.nonce == 0u64 { 0 } else { 1 + 8 }
}

fn write_message<W: WriterBackend>(&self, w: &mut Writer<W>) -> Result<()> {
if let Some(ref s) = self.nonce { w.write_with_tag(9, |w| w.write_fixed64(*s))?; }
if self.nonce != 0u64 { w.write_with_tag(9, |w| w.write_fixed64(*&self.nonce))?; }
Ok(())
}
}

#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Debug, Default, PartialEq, Clone)]
pub struct DialBackResponse {
pub status: Option<structs::mod_DialBackResponse::DialBackStatus>,
pub status: structs::mod_DialBackResponse::DialBackStatus,
}

impl<'a> MessageRead<'a> for DialBackResponse {
fn from_reader(r: &mut BytesReader, bytes: &'a [u8]) -> Result<Self> {
let mut msg = Self::default();
while !r.is_eof() {
match r.next_tag(bytes) {
Ok(8) => msg.status = Some(r.read_enum(bytes)?),
Ok(8) => msg.status = r.read_enum(bytes)?,
Ok(t) => { r.read_unknown(bytes, t)?; }
Err(e) => return Err(e),
}
Expand All @@ -358,11 +358,11 @@ impl<'a> MessageRead<'a> for DialBackResponse {
impl MessageWrite for DialBackResponse {
fn get_size(&self) -> usize {
0
+ self.status.as_ref().map_or(0, |m| 1 + sizeof_varint(*(m) as u64))
+ if self.status == structs::mod_DialBackResponse::DialBackStatus::OK { 0 } else { 1 + sizeof_varint(*(&self.status) as u64) }
}

fn write_message<W: WriterBackend>(&self, w: &mut Writer<W>) -> Result<()> {
if let Some(ref s) = self.status { w.write_with_tag(8, |w| w.write_enum(*s as i32))?; }
if self.status != structs::mod_DialBackResponse::DialBackStatus::OK { w.write_with_tag(8, |w| w.write_enum(*&self.status as i32))?; }
Ok(())
}
}
Expand Down
70 changes: 23 additions & 47 deletions protocols/autonat/src/v2/protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,6 @@ fn new_io_invalid_data_err(msg: impl Into<String>) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, msg.into())
}

macro_rules! ok_or_invalid_data {
($field:ident) => {
$field.ok_or_else(|| new_io_invalid_data_err(concat!(stringify!($field), " is missing")))
};
}

pub(crate) struct Coder<I> {
inner: Framed<I, Codec<proto::Message>>,
}
Expand Down Expand Up @@ -93,7 +87,7 @@ pub(crate) enum Request {
impl From<DialRequest> for proto::Message {
fn from(val: DialRequest) -> Self {
let addrs = val.addrs.iter().map(|e| e.to_vec()).collect();
let nonce = Some(val.nonce);
let nonce = val.nonce;

proto::Message {
msg: proto::mod_Message::OneOfmsg::dialRequest(proto::DialRequest { addrs, nonce }),
Expand All @@ -109,7 +103,7 @@ impl From<DialDataResponse> for proto::Message {
);
proto::Message {
msg: proto::mod_Message::OneOfmsg::dialDataResponse(proto::DialDataResponse {
data: Some(vec![0; val.data_count]), // One could use Cow::Borrowed here, but it will require a modification of the generated code and that will fail the CI
data: vec![0; val.data_count], // One could use Cow::Borrowed here, but it will require a modification of the generated code and that will fail the CI
}),
}
}
Expand Down Expand Up @@ -155,11 +149,10 @@ impl TryFrom<proto::Message> for Request {
})
})
.collect::<Result<Vec<_>, io::Error>>()?;
let nonce = ok_or_invalid_data!(nonce)?;
Ok(Self::Dial(DialRequest { addrs, nonce }))
}
proto::mod_Message::OneOfmsg::dialDataResponse(proto::DialDataResponse { data }) => {
let data_count = ok_or_invalid_data!(data)?.len();
let data_count = data.len();
Ok(Self::Data(DialDataResponse { data_count }))
}
_ => Err(new_io_invalid_data_err(
Expand Down Expand Up @@ -197,27 +190,18 @@ impl TryFrom<proto::Message> for Response {
status,
addrIdx,
dialStatus,
}) => {
let status = ok_or_invalid_data!(status)?;
let addr_idx = ok_or_invalid_data!(addrIdx)? as usize;
let dial_status = ok_or_invalid_data!(dialStatus)?;
Ok(Response::Dial(DialResponse {
status,
addr_idx,
dial_status,
}))
}
}) => Ok(Response::Dial(DialResponse {
status,
addr_idx: addrIdx as usize,
dial_status: dialStatus,
})),
proto::mod_Message::OneOfmsg::dialDataRequest(proto::DialDataRequest {
addrIdx,
numBytes,
}) => {
let addr_idx = ok_or_invalid_data!(addrIdx)? as usize;
let num_bytes = ok_or_invalid_data!(numBytes)? as usize;
Ok(Self::Data(DialDataRequest {
addr_idx,
num_bytes,
}))
}
}) => Ok(Self::Data(DialDataRequest {
addr_idx: addrIdx as usize,
num_bytes: numBytes as usize,
})),
_ => Err(new_io_invalid_data_err(
"invalid message type, expected dialResponse or dialDataRequest",
)),
Expand All @@ -234,18 +218,18 @@ impl From<Response> for proto::Message {
dial_status,
}) => proto::Message {
msg: proto::mod_Message::OneOfmsg::dialResponse(proto::DialResponse {
status: Some(status),
addrIdx: Some(addr_idx as u32),
dialStatus: Some(dial_status),
status,
addrIdx: addr_idx as u32,
dialStatus: dial_status,
}),
},
Response::Data(DialDataRequest {
addr_idx,
num_bytes,
}) => proto::Message {
msg: proto::mod_Message::OneOfmsg::dialDataRequest(proto::DialDataRequest {
addrIdx: Some(addr_idx as u32),
numBytes: Some(num_bytes as u64),
addrIdx: addr_idx as u32,
numBytes: num_bytes as u64,
}),
},
}
Expand All @@ -265,7 +249,7 @@ impl DialDataRequest {
const DIAL_BACK_MAX_SIZE: usize = 10;

pub(crate) async fn dial_back(stream: impl AsyncWrite + Unpin, nonce: Nonce) -> io::Result<()> {
let msg = proto::DialBack { nonce: Some(nonce) };
let msg = proto::DialBack { nonce };
let mut framed = FramedWrite::new(stream, Codec::<proto::DialBack>::new(DIAL_BACK_MAX_SIZE));

framed
Expand All @@ -282,14 +266,12 @@ pub(crate) async fn recv_dial_back(stream: impl AsyncRead + Unpin) -> io::Result
.next()
.await
.ok_or(io::Error::from(io::ErrorKind::UnexpectedEof))??;
let nonce = ok_or_invalid_data!(nonce)?;

Ok(nonce)
}

pub(crate) async fn dial_back_response(stream: impl AsyncWrite + Unpin) -> io::Result<()> {
let msg = proto::DialBackResponse {
status: Some(proto::mod_DialBackResponse::DialBackStatus::OK),
status: proto::mod_DialBackResponse::DialBackStatus::OK,
};
let mut framed = FramedWrite::new(
stream,
Expand All @@ -315,7 +297,7 @@ pub(crate) async fn recv_dial_back_response(
.await
.ok_or(io::Error::from(io::ErrorKind::UnexpectedEof))??;

if let Some(proto::mod_DialBackResponse::DialBackStatus::OK) = status {
if proto::mod_DialBackResponse::DialBackStatus::OK == status {
Ok(())
} else {
Err(io::Error::new(
Expand All @@ -335,7 +317,7 @@ mod tests {
fn message_correct_max_size() {
let message_bytes = quick_protobuf::serialize_into_vec(&Message {
msg: OneOfmsg::dialDataResponse(GenDialDataResponse {
data: Some(vec![0; 4096]),
data: vec![0; 4096],
}),
})
.unwrap();
Expand All @@ -344,17 +326,11 @@ mod tests {

#[test]
fn dial_back_correct_size() {
let dial_back = super::proto::DialBack { nonce: Some(0) };
let dial_back = super::proto::DialBack { nonce: 0 };
let buf = quick_protobuf::serialize_into_vec(&dial_back).unwrap();
assert!(buf.len() <= super::DIAL_BACK_MAX_SIZE);

let dial_back_none = super::proto::DialBack { nonce: None };
let buf = quick_protobuf::serialize_into_vec(&dial_back_none).unwrap();
assert!(buf.len() <= super::DIAL_BACK_MAX_SIZE);

let dial_back_max_nonce = super::proto::DialBack {
nonce: Some(u64::MAX),
};
let dial_back_max_nonce = super::proto::DialBack { nonce: u64::MAX };
let buf = quick_protobuf::serialize_into_vec(&dial_back_max_nonce).unwrap();
assert!(buf.len() <= super::DIAL_BACK_MAX_SIZE);
}
Expand Down

0 comments on commit ff806a3

Please sign in to comment.