Skip to main content

avalanche_types/message/
get.rs

1use std::io::{self, Error, ErrorKind};
2
3use crate::{ids, message, proto::pb::p2p};
4use prost::Message as ProstMessage;
5
6#[derive(Debug, PartialEq, Clone)]
7pub struct Message {
8    pub msg: p2p::Get,
9    pub gzip_compress: bool,
10}
11
12impl Default for Message {
13    fn default() -> Self {
14        Message {
15            msg: p2p::Get {
16                chain_id: prost::bytes::Bytes::new(),
17                request_id: 0,
18                deadline: 0,
19                container_id: prost::bytes::Bytes::new(),
20                engine_type: p2p::EngineType::Unspecified.into(),
21            },
22            gzip_compress: false,
23        }
24    }
25}
26
27impl Message {
28    #[must_use]
29    pub fn chain_id(mut self, chain_id: ids::Id) -> Self {
30        self.msg.chain_id = prost::bytes::Bytes::from(chain_id.to_vec());
31        self
32    }
33
34    #[must_use]
35    pub fn request_id(mut self, request_id: u32) -> Self {
36        self.msg.request_id = request_id;
37        self
38    }
39
40    #[must_use]
41    pub fn deadline(mut self, deadline: u64) -> Self {
42        self.msg.deadline = deadline;
43        self
44    }
45
46    #[must_use]
47    pub fn container_id(mut self, container_id: ids::Id) -> Self {
48        self.msg.container_id = prost::bytes::Bytes::from(container_id.to_vec());
49        self
50    }
51
52    #[must_use]
53    pub fn gzip_compress(mut self, gzip_compress: bool) -> Self {
54        self.gzip_compress = gzip_compress;
55        self
56    }
57
58    pub fn serialize(&self) -> io::Result<Vec<u8>> {
59        let msg = p2p::Message {
60            message: Some(p2p::message::Message::Get(self.msg.clone())),
61        };
62        let encoded = ProstMessage::encode_to_vec(&msg);
63        if !self.gzip_compress {
64            return Ok(encoded);
65        }
66
67        let uncompressed_len = encoded.len();
68        let compressed = message::compress::pack_gzip(&encoded)?;
69        let msg = p2p::Message {
70            message: Some(p2p::message::Message::CompressedGzip(
71                prost::bytes::Bytes::from(compressed),
72            )),
73        };
74
75        let compressed_len = msg.encoded_len();
76        if uncompressed_len > compressed_len {
77            log::debug!(
78                "get compression saved {} bytes",
79                uncompressed_len - compressed_len
80            );
81        } else {
82            log::debug!(
83                "get compression added {} byte(s)",
84                compressed_len - uncompressed_len
85            );
86        }
87
88        Ok(ProstMessage::encode_to_vec(&msg))
89    }
90
91    pub fn deserialize(d: impl AsRef<[u8]>) -> io::Result<Self> {
92        let buf = bytes::Bytes::from(d.as_ref().to_vec());
93        let p2p_msg: p2p::Message = ProstMessage::decode(buf).map_err(|e| {
94            Error::new(
95                ErrorKind::InvalidData,
96                format!("failed prost::Message::decode '{}'", e),
97            )
98        })?;
99
100        match p2p_msg.message.unwrap() {
101            // was not compressed
102            p2p::message::Message::Get(msg) => Ok(Message {
103                msg,
104                gzip_compress: false,
105            }),
106
107            // was compressed, so need decompress first
108            p2p::message::Message::CompressedGzip(msg) => {
109                let decompressed = message::compress::unpack_gzip(msg.as_ref())?;
110                let decompressed_msg: p2p::Message =
111                    ProstMessage::decode(prost::bytes::Bytes::from(decompressed)).map_err(|e| {
112                        Error::new(
113                            ErrorKind::InvalidData,
114                            format!("failed prost::Message::decode '{}'", e),
115                        )
116                    })?;
117                match decompressed_msg.message.unwrap() {
118                    p2p::message::Message::Get(msg) => Ok(Message {
119                        msg,
120                        gzip_compress: false,
121                    }),
122                    _ => Err(Error::new(
123                        ErrorKind::InvalidInput,
124                        "unknown message type after decompress",
125                    )),
126                }
127            }
128
129            // unknown message enum
130            _ => Err(Error::new(ErrorKind::InvalidInput, "unknown message type")),
131        }
132    }
133}
134
135/// RUST_LOG=debug cargo test --package avalanche-types --lib -- message::get::test_message --exact --show-output
136#[test]
137fn test_message() {
138    let _ = env_logger::builder()
139        .filter_level(log::LevelFilter::Debug)
140        .is_test(true)
141        .try_init();
142
143    let msg1_with_no_compression = Message::default()
144        .chain_id(ids::Id::from_slice(
145            &random_manager::secure_bytes(32).unwrap(),
146        ))
147        .request_id(random_manager::u32())
148        .deadline(random_manager::u64())
149        .container_id(ids::Id::from_slice(
150            &random_manager::secure_bytes(32).unwrap(),
151        ));
152
153    let data1 = msg1_with_no_compression.serialize().unwrap();
154    let msg1_with_no_compression_deserialized = Message::deserialize(data1).unwrap();
155    assert_eq!(
156        msg1_with_no_compression,
157        msg1_with_no_compression_deserialized
158    );
159
160    let msg2_with_compression = msg1_with_no_compression.clone().gzip_compress(true);
161    assert_ne!(msg1_with_no_compression, msg2_with_compression);
162
163    let data2 = msg2_with_compression.serialize().unwrap();
164    let msg2_with_compression_deserialized = Message::deserialize(data2).unwrap();
165    assert_eq!(msg1_with_no_compression, msg2_with_compression_deserialized);
166}