Skip to main content

hopr_protocol_app/
v1.rs

1use std::{borrow::Cow, fmt::Formatter, ops::Range, str::FromStr};
2
3use hopr_crypto_packet::prelude::{HoprPacket, PacketSignals};
4use hopr_types::primitive::to_hex_shortened;
5use strum::IntoEnumIterator;
6
7use crate::errors::ApplicationLayerError;
8
9/// List of all reserved application tags for the protocol.
10#[repr(u64)]
11#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, strum::EnumIter)]
12pub enum ReservedTag {
13    /// Ping traffic for 0-hop detection.
14    Ping = 0,
15
16    /// Commands associated with session start protocol regarding session initiation.
17    SessionStart = 1,
18
19    /// Reserved tag for the Session protocol.
20    Session = 2,
21
22    /// Undefined catch all.
23    Undefined = 15,
24}
25
26impl ReservedTag {
27    /// The exclusive upper bound of the reserved tag range.
28    ///
29    /// Must be kept in sync with the highest variant discriminant.
30    pub const UPPER_BOUND: u64 = Self::Undefined as u64 + 1;
31
32    /// The range of reserved tags
33    pub fn range() -> Range<u64> {
34        0..Self::UPPER_BOUND
35    }
36}
37
38impl From<ReservedTag> for Tag {
39    fn from(tag: ReservedTag) -> Self {
40        (tag as u64).into()
41    }
42}
43
44/// Tags distinguishing different application-layer protocols.
45///
46/// Currently, 8 bytes represent tags (`u64`).
47///
48/// `u64` should offer enough space to avoid collisions and tag attacks.
49#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
50pub enum Tag {
51    Reserved(u64),
52    Application(u64),
53}
54
55impl Tag {
56    /// Application tag range for external usage
57    pub const APPLICATION_TAG_RANGE: Range<Self> =
58        (Self::Application(ReservedTag::Undefined as u64 + 1))..Self::Application(Self::MAX);
59    /// The maximum value of a tag.
60    ///
61    /// The maximum value is determined by the fact that the 3 most significant bits
62    /// must be set to 0 in version 1.
63    pub const MAX: u64 = 0x1fffffffffffffff_u64;
64    /// Size of a tag in bytes.
65    pub const SIZE: usize = size_of::<u64>();
66
67    pub fn from_be_bytes(bytes: [u8; Self::SIZE]) -> Self {
68        let tag = u64::from_be_bytes(bytes);
69        tag.into()
70    }
71
72    pub fn to_be_bytes(&self) -> [u8; Self::SIZE] {
73        match self {
74            Tag::Reserved(tag) | Tag::Application(tag) => tag.to_be_bytes(),
75        }
76    }
77
78    pub fn as_u64(&self) -> u64 {
79        match self {
80            Tag::Reserved(tag) | Tag::Application(tag) => (*tag) & Self::MAX,
81        }
82    }
83}
84
85impl<T: Into<u64>> From<T> for Tag {
86    fn from(tag: T) -> Self {
87        // In version 1, the 3 most significant bits are always 0.
88        let tag: u64 = tag.into() & Self::MAX;
89
90        if ReservedTag::range().contains(&tag) {
91            Tag::Reserved(
92                ReservedTag::iter()
93                    .find(|&t| t as u64 == tag)
94                    .unwrap_or(ReservedTag::Undefined) as u64,
95            )
96        } else {
97            Tag::Application(tag)
98        }
99    }
100}
101
102#[cfg(feature = "serde")]
103impl serde::Serialize for Tag {
104    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
105    where
106        S: serde::Serializer,
107    {
108        serializer.serialize_u64(self.as_u64())
109    }
110}
111
112#[cfg(feature = "serde")]
113impl<'a> serde::Deserialize<'a> for Tag {
114    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
115    where
116        D: serde::Deserializer<'a>,
117    {
118        Ok(u64::deserialize(deserializer)?.into())
119    }
120}
121
122impl std::fmt::Display for Tag {
123    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
124        write!(f, "{}", self.as_u64())
125    }
126}
127
128impl FromStr for Tag {
129    type Err = std::num::ParseIntError;
130
131    fn from_str(s: &str) -> Result<Self, Self::Err> {
132        u64::from_str(s).map(Tag::from)
133    }
134}
135
136/// Holds packet transient information when [`ApplicationData`] is passed from the HOPR protocol layer to the
137/// Application layer.
138///
139/// The HOPR protocol layer typically takes care of properly populating this structure
140/// as the packet arrives.
141#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
142pub struct IncomingPacketInfo {
143    /// Packet signals that were passed by the sender.
144    pub signals_from_sender: PacketSignals,
145    /// The number of SURBs the HOPR packet was carrying along with the [`ApplicationData`] instance.
146    pub num_saved_surbs: usize,
147}
148
149/// Holds packet transient information when [`ApplicationData`] is passed to the HOPR protocol layer from the
150/// Application layer.
151///
152/// The information passed to the HOPR protocol only serves as a suggestion, and the HOPR protocol
153/// may choose to ignore it, based on its configuration.
154#[derive(Copy, Clone, Debug, PartialEq, Eq)]
155pub struct OutgoingPacketInfo {
156    /// Packet signals that should be passed to the recipient.
157    pub signals_to_destination: PacketSignals,
158    /// The maximum number of SURBs the HOPR packet should be carrying when sent.
159    pub max_surbs_in_packet: usize,
160}
161
162impl Default for OutgoingPacketInfo {
163    fn default() -> Self {
164        Self {
165            signals_to_destination: PacketSignals::empty(),
166            max_surbs_in_packet: usize::MAX,
167        }
168    }
169}
170
171/// Wrapper for incoming [`ApplicationData`] with optional [`IncomingPacketInfo`].
172#[derive(Clone, Debug, PartialEq, Eq)]
173#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
174pub struct ApplicationDataIn {
175    /// The actual application-layer data.
176    pub data: ApplicationData,
177    /// Additional transient information about the incoming packet.
178    ///
179    /// This information is always populated by the HOPR packet layer.
180    #[cfg_attr(feature = "serde", serde(skip))]
181    pub packet_info: IncomingPacketInfo,
182}
183
184impl ApplicationDataIn {
185    /// Returns how many SURBs were carried with this packet.
186    pub fn num_surbs_with_msg(&self) -> usize {
187        self.packet_info
188            .num_saved_surbs
189            .min(HoprPacket::max_surbs_with_message(self.data.total_len()))
190    }
191}
192
193/// Wrapper for outgoing [`ApplicationData`] with optional [`IncomingPacketInfo`].
194#[derive(Clone, Debug, PartialEq, Eq)]
195#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
196pub struct ApplicationDataOut {
197    /// The actual application-layer data.
198    pub data: ApplicationData,
199    /// Additional transient information about the outgoing packet.
200    ///
201    /// This field is optional and acts mainly as a suggestion to the HOPR packet layer,
202    /// as it may choose to completely ignore it, based on its configuration.
203    #[cfg_attr(feature = "serde", serde(skip))]
204    pub packet_info: Option<OutgoingPacketInfo>,
205}
206
207impl ApplicationDataOut {
208    /// Creates a new instance with `packet_info` set to `None`.
209    pub fn with_no_packet_info(data: ApplicationData) -> Self {
210        Self {
211            data,
212            packet_info: None,
213        }
214    }
215
216    /// Returns the upper bound of how many SURBs that will be carried with this packet.
217    pub fn estimate_surbs_with_msg(&self) -> usize {
218        let max_possible = HoprPacket::max_surbs_with_message(self.data.total_len());
219        self.packet_info
220            .map(|info| info.max_surbs_in_packet.min(max_possible))
221            .unwrap_or(max_possible)
222    }
223}
224
225/// Represents the to-be-sent or received decrypted packet carrying the application-layer data.
226///
227/// This type is already HOPR specific, as it enforces the maximum payload size to be at most
228/// [`HoprPacket::PAYLOAD_SIZE`] bytes-long. This structure always owns the data.
229#[derive(Clone, PartialEq, Eq)]
230#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
231pub struct ApplicationData {
232    /// Tag identifying the application-layer protocol.
233    pub application_tag: Tag,
234    /// The actual application-layer data.
235    #[cfg_attr(feature = "serde", serde(with = "serde_bytes"))]
236    pub plain_text: Box<[u8]>,
237}
238
239impl ApplicationData {
240    /// The payload size is the [`HoprPacket::PAYLOAD_SIZE`] minus the [`Tag::SIZE`].
241    pub const PAYLOAD_SIZE: usize = HoprPacket::PAYLOAD_SIZE - Tag::SIZE;
242
243    /// Creates a new instance with the given tag and application layer data.
244    ///
245    /// Fails if the `plain_text` is larger than [`ApplicationData::PAYLOAD_SIZE`].
246    pub fn new<'a, T: Into<Tag>, D: Into<Cow<'a, [u8]>>>(
247        application_tag: T,
248        plain_text: D,
249    ) -> crate::errors::Result<Self> {
250        let data = plain_text.into();
251        if data.len() <= Self::PAYLOAD_SIZE {
252            Ok(Self {
253                application_tag: application_tag.into(),
254                plain_text: data.into(),
255            })
256        } else {
257            Err(ApplicationLayerError::PayloadTooLarge)
258        }
259    }
260
261    /// Length of the payload plus the [`Tag`].
262    ///
263    /// Can never be zero due to the `Tag`.
264    #[inline]
265    pub fn total_len(&self) -> usize {
266        Tag::SIZE + self.plain_text.len()
267    }
268
269    /// Indicates if the payload is empty.
270    #[inline]
271    pub fn is_payload_empty(&self) -> bool {
272        self.plain_text.is_empty()
273    }
274
275    /// Serializes the structure into binary representation.
276    pub fn to_bytes(&self) -> Box<[u8]> {
277        let mut buf = Vec::with_capacity(Tag::SIZE + self.plain_text.len());
278        buf.extend_from_slice(&self.application_tag.to_be_bytes());
279        buf.extend_from_slice(&self.plain_text);
280        buf.into_boxed_slice()
281    }
282}
283
284impl std::fmt::Debug for ApplicationData {
285    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
286        f.debug_struct("ApplicationData")
287            .field("application_tag", &self.application_tag)
288            .field("plain_text", &to_hex_shortened::<32>(&self.plain_text))
289            .finish()
290    }
291}
292
293impl std::fmt::Display for ApplicationData {
294    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
295        write!(
296            f,
297            "({}): {}",
298            self.application_tag,
299            to_hex_shortened::<16>(&self.plain_text)
300        )
301    }
302}
303
304impl TryFrom<&[u8]> for ApplicationData {
305    type Error = ApplicationLayerError;
306
307    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
308        if value.len() >= Tag::SIZE && value.len() <= HoprPacket::PAYLOAD_SIZE {
309            Ok(Self {
310                application_tag: Tag::from_be_bytes(
311                    value[0..Tag::SIZE]
312                        .try_into()
313                        .map_err(|_e| ApplicationLayerError::DecodingError("ApplicationData.tag".into()))?,
314                ),
315                plain_text: Box::from(&value[Tag::SIZE..]),
316            })
317        } else {
318            Err(ApplicationLayerError::DecodingError("ApplicationData.size".into()))
319        }
320    }
321}
322
323#[cfg(test)]
324mod tests {
325    use super::*;
326
327    #[test]
328    fn reserved_tag_v1_range_is_stable() {
329        let range = ReservedTag::range();
330        assert_eq!(range.start, 0);
331        assert_eq!(range.count(), 16); // 0 to 15 inclusive
332    }
333
334    #[test]
335    fn tag_should_be_obtainable_as_reserved_when_created_from_a_reserved_range() {
336        let reserved_tag = ReservedTag::Ping as u64;
337
338        assert_eq!(Tag::from(reserved_tag), Tag::Reserved(reserved_tag));
339    }
340
341    #[test]
342    fn v1_tags_should_have_3_most_significant_bits_unset() {
343        let tag: Tag = u64::MAX.into();
344        assert_eq!(tag.as_u64(), Tag::MAX);
345    }
346
347    #[test]
348    fn tag_should_be_obtainable_as_undefined_reserved_when_created_from_an_undefined_value_in_reserved_range() {
349        let reserved_tag_without_assignment = 7u64;
350
351        assert_eq!(
352            Tag::from(reserved_tag_without_assignment),
353            Tag::Reserved(ReservedTag::Undefined as u64)
354        );
355    }
356
357    #[test]
358    fn v1_format_is_binary_stable() -> anyhow::Result<()> {
359        let original = ApplicationData::new(10u64, &[0_u8, 1_u8])?;
360        let reserialized = ApplicationData::try_from(original.to_bytes().as_ref())?;
361        let reserialized = ApplicationData::try_from(reserialized.to_bytes().as_ref())?;
362
363        assert_eq!(original, reserialized);
364
365        Ok(())
366    }
367
368    #[test]
369    fn test_application_data() -> anyhow::Result<()> {
370        let ad_1 = ApplicationData::new(10u64, &[0_u8, 1_u8])?;
371        let ad_2 = ApplicationData::try_from(ad_1.to_bytes().as_ref())?;
372        assert_eq!(ad_1, ad_2);
373
374        let ad_1 = ApplicationData::new(0u64, &[])?;
375        let ad_2 = ApplicationData::try_from(ad_1.to_bytes().as_ref())?;
376        assert_eq!(ad_1, ad_2);
377
378        let ad_1 = ApplicationData::new(10u64, &[0_u8, 1_u8])?;
379        let ad_2 = ApplicationData::try_from(ad_1.to_bytes().as_ref())?;
380        assert_eq!(ad_1, ad_2);
381
382        let ad_1 = ApplicationData::new(10u64, &[0_u8; ApplicationData::PAYLOAD_SIZE])?;
383        let ad_2 = ApplicationData::try_from(ad_1.to_bytes().as_ref())?;
384        assert_eq!(ad_1, ad_2);
385
386        assert!(ApplicationData::try_from([0_u8; Tag::SIZE - 1].as_ref()).is_err());
387        assert!(ApplicationData::try_from([0_u8; ApplicationData::PAYLOAD_SIZE + Tag::SIZE + 1].as_ref()).is_err());
388
389        Ok(())
390    }
391
392    #[test]
393    fn application_data_should_not_allow_payload_larger_than_hopr_packet_payload_size() {
394        assert!(ApplicationData::new(10u64, [0_u8; HoprPacket::PAYLOAD_SIZE + 1].as_ref()).is_err());
395    }
396}