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#[repr(u64)]
11#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, strum::EnumIter)]
12pub enum ReservedTag {
13 Ping = 0,
15
16 SessionStart = 1,
18
19 Session = 2,
21
22 Undefined = 15,
24}
25
26impl ReservedTag {
27 pub const UPPER_BOUND: u64 = Self::Undefined as u64 + 1;
31
32 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#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
50pub enum Tag {
51 Reserved(u64),
52 Application(u64),
53}
54
55impl Tag {
56 pub const APPLICATION_TAG_RANGE: Range<Self> =
58 (Self::Application(ReservedTag::Undefined as u64 + 1))..Self::Application(Self::MAX);
59 pub const MAX: u64 = 0x1fffffffffffffff_u64;
64 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 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#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
142pub struct IncomingPacketInfo {
143 pub signals_from_sender: PacketSignals,
145 pub num_saved_surbs: usize,
147}
148
149#[derive(Copy, Clone, Debug, PartialEq, Eq)]
155pub struct OutgoingPacketInfo {
156 pub signals_to_destination: PacketSignals,
158 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#[derive(Clone, Debug, PartialEq, Eq)]
173#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
174pub struct ApplicationDataIn {
175 pub data: ApplicationData,
177 #[cfg_attr(feature = "serde", serde(skip))]
181 pub packet_info: IncomingPacketInfo,
182}
183
184impl ApplicationDataIn {
185 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#[derive(Clone, Debug, PartialEq, Eq)]
195#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
196pub struct ApplicationDataOut {
197 pub data: ApplicationData,
199 #[cfg_attr(feature = "serde", serde(skip))]
204 pub packet_info: Option<OutgoingPacketInfo>,
205}
206
207impl ApplicationDataOut {
208 pub fn with_no_packet_info(data: ApplicationData) -> Self {
210 Self {
211 data,
212 packet_info: None,
213 }
214 }
215
216 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#[derive(Clone, PartialEq, Eq)]
230#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
231pub struct ApplicationData {
232 pub application_tag: Tag,
234 #[cfg_attr(feature = "serde", serde(with = "serde_bytes"))]
236 pub plain_text: Box<[u8]>,
237}
238
239impl ApplicationData {
240 pub const PAYLOAD_SIZE: usize = HoprPacket::PAYLOAD_SIZE - Tag::SIZE;
242
243 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 #[inline]
265 pub fn total_len(&self) -> usize {
266 Tag::SIZE + self.plain_text.len()
267 }
268
269 #[inline]
271 pub fn is_payload_empty(&self) -> bool {
272 self.plain_text.is_empty()
273 }
274
275 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); }
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}