1use std::{borrow::Cow, fmt::Formatter, ops::Range, str::FromStr};
2
3use bytes::{Buf, Bytes};
4use hopr_crypto_packet::prelude::{HoprPacket, PacketSignals};
5use hopr_types::primitive::to_hex_shortened;
6use strum::IntoEnumIterator;
7
8use crate::errors::ApplicationLayerError;
9
10#[repr(u64)]
12#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, strum::EnumIter)]
13pub enum ReservedTag {
14 Ping = 0,
16
17 SessionStart = 1,
19
20 Session = 2,
22
23 Undefined = 15,
25}
26
27impl ReservedTag {
28 pub const UPPER_BOUND: u64 = Self::Undefined as u64 + 1;
32
33 pub fn range() -> Range<u64> {
35 0..Self::UPPER_BOUND
36 }
37}
38
39impl From<ReservedTag> for Tag {
40 fn from(tag: ReservedTag) -> Self {
41 (tag as u64).into()
42 }
43}
44
45#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
51pub enum Tag {
52 Reserved(u64),
53 Application(u64),
54}
55
56impl Tag {
57 pub const APPLICATION_TAG_RANGE: Range<Self> =
59 (Self::Application(ReservedTag::Undefined as u64 + 1))..Self::Application(Self::MAX);
60 pub const MAX: u64 = 0x1fffffffffffffff_u64;
65 pub const SIZE: usize = size_of::<u64>();
67
68 pub fn from_be_bytes(bytes: [u8; Self::SIZE]) -> Self {
69 let tag = u64::from_be_bytes(bytes);
70 tag.into()
71 }
72
73 pub fn to_be_bytes(&self) -> [u8; Self::SIZE] {
74 match self {
75 Tag::Reserved(tag) | Tag::Application(tag) => tag.to_be_bytes(),
76 }
77 }
78
79 pub fn as_u64(&self) -> u64 {
80 match self {
81 Tag::Reserved(tag) | Tag::Application(tag) => (*tag) & Self::MAX,
82 }
83 }
84}
85
86impl<T: Into<u64>> From<T> for Tag {
87 fn from(tag: T) -> Self {
88 let tag: u64 = tag.into() & Self::MAX;
90
91 if ReservedTag::range().contains(&tag) {
92 Tag::Reserved(
93 ReservedTag::iter()
94 .find(|&t| t as u64 == tag)
95 .unwrap_or(ReservedTag::Undefined) as u64,
96 )
97 } else {
98 Tag::Application(tag)
99 }
100 }
101}
102
103#[cfg(feature = "serde")]
104impl serde::Serialize for Tag {
105 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
106 where
107 S: serde::Serializer,
108 {
109 serializer.serialize_u64(self.as_u64())
110 }
111}
112
113#[cfg(feature = "serde")]
114impl<'a> serde::Deserialize<'a> for Tag {
115 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
116 where
117 D: serde::Deserializer<'a>,
118 {
119 Ok(u64::deserialize(deserializer)?.into())
120 }
121}
122
123impl std::fmt::Display for Tag {
124 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
125 write!(f, "{}", self.as_u64())
126 }
127}
128
129impl FromStr for Tag {
130 type Err = std::num::ParseIntError;
131
132 fn from_str(s: &str) -> Result<Self, Self::Err> {
133 u64::from_str(s).map(Tag::from)
134 }
135}
136
137#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
143pub struct IncomingPacketInfo {
144 pub signals_from_sender: PacketSignals,
146 pub num_saved_surbs: usize,
148 pub num_evicted_surbs: usize,
165 pub min_return_path_hops: Option<u8>,
171}
172
173#[derive(Copy, Clone, Debug, PartialEq, Eq)]
179pub struct OutgoingPacketInfo {
180 pub signals_to_destination: PacketSignals,
182 pub max_surbs_in_packet: usize,
184 pub surb_generation: Option<u8>,
188}
189
190impl Default for OutgoingPacketInfo {
191 fn default() -> Self {
192 Self {
193 signals_to_destination: PacketSignals::empty(),
194 max_surbs_in_packet: usize::MAX,
195 surb_generation: None,
196 }
197 }
198}
199
200#[derive(Clone, Debug, PartialEq, Eq)]
202#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
203pub struct ApplicationDataIn {
204 pub data: ApplicationData,
206 #[cfg_attr(feature = "serde", serde(skip))]
210 pub packet_info: IncomingPacketInfo,
211}
212
213impl ApplicationDataIn {
214 pub fn num_surbs_with_msg(&self) -> usize {
216 self.packet_info
217 .num_saved_surbs
218 .min(HoprPacket::max_surbs_with_message(self.data.total_len()))
219 }
220}
221
222#[derive(Clone, Default)]
237pub struct SurbRefund(Option<std::sync::Arc<std::sync::atomic::AtomicU64>>);
238
239impl SurbRefund {
240 pub fn to(refunds: std::sync::Arc<std::sync::atomic::AtomicU64>) -> Self {
242 Self(Some(refunds))
243 }
244
245 pub fn is_counted(&self) -> bool {
247 self.0.is_some()
248 }
249
250 pub fn give_back(&self) {
252 if let Some(refunds) = &self.0 {
253 refunds.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
254 }
255 }
256}
257
258impl std::fmt::Debug for SurbRefund {
259 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
260 f.write_str(if self.0.is_some() {
261 "SurbRefund(counted)"
262 } else {
263 "SurbRefund(none)"
264 })
265 }
266}
267
268impl PartialEq for SurbRefund {
270 fn eq(&self, other: &Self) -> bool {
271 match (&self.0, &other.0) {
272 (Some(a), Some(b)) => std::sync::Arc::ptr_eq(a, b),
273 (None, None) => true,
274 _ => false,
275 }
276 }
277}
278
279impl Eq for SurbRefund {}
280
281#[derive(Clone, Debug, PartialEq, Eq)]
283#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
284pub struct ApplicationDataOut {
285 pub data: ApplicationData,
287 #[cfg_attr(feature = "serde", serde(skip))]
292 pub packet_info: Option<OutgoingPacketInfo>,
293 #[cfg_attr(feature = "serde", serde(skip))]
295 pub surb_refund: SurbRefund,
296}
297
298impl ApplicationDataOut {
299 pub fn with_no_packet_info(data: ApplicationData) -> Self {
301 Self {
302 data,
303 packet_info: None,
304 surb_refund: SurbRefund::default(),
305 }
306 }
307
308 pub fn estimate_surbs_with_msg(&self) -> usize {
310 let max_possible = HoprPacket::max_surbs_with_message(self.data.total_len());
311 self.packet_info
312 .map(|info| info.max_surbs_in_packet.min(max_possible))
313 .unwrap_or(max_possible)
314 }
315}
316
317#[derive(Clone, PartialEq, Eq)]
323#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
324pub struct ApplicationData {
325 pub application_tag: Tag,
327 pub plain_text: Bytes,
329}
330
331impl ApplicationData {
332 pub const PAYLOAD_SIZE: usize = HoprPacket::PAYLOAD_SIZE - Tag::SIZE;
334
335 pub fn new<'a, T: Into<Tag>, D: Into<Cow<'a, [u8]>>>(
339 application_tag: T,
340 plain_text: D,
341 ) -> crate::errors::Result<Self> {
342 let data = plain_text.into();
343 if data.len() <= Self::PAYLOAD_SIZE {
344 Ok(Self {
345 application_tag: application_tag.into(),
346 plain_text: match data {
347 Cow::Owned(vec) => vec.into(),
348 Cow::Borrowed(slice) => Bytes::copy_from_slice(slice),
349 },
350 })
351 } else {
352 Err(ApplicationLayerError::PayloadTooLarge)
353 }
354 }
355
356 #[inline]
360 pub fn total_len(&self) -> usize {
361 Tag::SIZE + self.plain_text.len()
362 }
363
364 #[inline]
366 pub fn is_payload_empty(&self) -> bool {
367 self.plain_text.is_empty()
368 }
369
370 pub fn to_bytes(&self) -> Box<[u8]> {
372 let mut buf = Vec::with_capacity(Tag::SIZE + self.plain_text.len());
373 buf.extend_from_slice(&self.application_tag.to_be_bytes());
374 buf.extend_from_slice(&self.plain_text);
375 buf.into_boxed_slice()
376 }
377}
378
379impl std::fmt::Debug for ApplicationData {
380 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
381 f.debug_struct("ApplicationData")
382 .field("application_tag", &self.application_tag)
383 .field("plain_text", &to_hex_shortened::<32>(&self.plain_text))
384 .finish()
385 }
386}
387
388impl std::fmt::Display for ApplicationData {
389 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
390 write!(
391 f,
392 "({}): {}",
393 self.application_tag,
394 to_hex_shortened::<16>(&self.plain_text)
395 )
396 }
397}
398
399fn check_len(len: usize) -> Result<(), ApplicationLayerError> {
401 if (Tag::SIZE..=HoprPacket::PAYLOAD_SIZE).contains(&len) {
402 Ok(())
403 } else {
404 Err(ApplicationLayerError::DecodingError("ApplicationData.size".into()))
405 }
406}
407
408impl TryFrom<&[u8]> for ApplicationData {
409 type Error = ApplicationLayerError;
410
411 fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
412 check_len(value.len())?;
413 Self::try_from(Bytes::copy_from_slice(value))
414 }
415}
416
417impl TryFrom<Bytes> for ApplicationData {
418 type Error = ApplicationLayerError;
419
420 fn try_from(mut value: Bytes) -> Result<Self, Self::Error> {
422 check_len(value.len())?;
423 let application_tag = Tag::from_be_bytes(
424 value[0..Tag::SIZE]
425 .try_into()
426 .map_err(|_e| ApplicationLayerError::DecodingError("ApplicationData.tag".into()))?,
427 );
428 value.advance(Tag::SIZE);
429 Ok(Self {
430 application_tag,
431 plain_text: value,
432 })
433 }
434}
435
436#[cfg(test)]
437mod tests {
438 use super::*;
439
440 #[test]
441 fn reserved_tag_v1_range_is_stable() {
442 let range = ReservedTag::range();
443 assert_eq!(range.start, 0);
444 assert_eq!(range.count(), 16); }
446
447 #[test]
448 fn tag_should_be_obtainable_as_reserved_when_created_from_a_reserved_range() {
449 let reserved_tag = ReservedTag::Ping as u64;
450
451 assert_eq!(Tag::from(reserved_tag), Tag::Reserved(reserved_tag));
452 }
453
454 #[test]
455 fn v1_tags_should_have_3_most_significant_bits_unset() {
456 let tag: Tag = u64::MAX.into();
457 assert_eq!(tag.as_u64(), Tag::MAX);
458 }
459
460 #[test]
461 fn tag_should_be_obtainable_as_undefined_reserved_when_created_from_an_undefined_value_in_reserved_range() {
462 let reserved_tag_without_assignment = 7u64;
463
464 assert_eq!(
465 Tag::from(reserved_tag_without_assignment),
466 Tag::Reserved(ReservedTag::Undefined as u64)
467 );
468 }
469
470 #[test]
471 fn v1_format_is_binary_stable() -> anyhow::Result<()> {
472 let original = ApplicationData::new(10u64, &[0_u8, 1_u8])?;
473 let reserialized = ApplicationData::try_from(original.to_bytes().as_ref())?;
474 let reserialized = ApplicationData::try_from(reserialized.to_bytes().as_ref())?;
475
476 assert_eq!(original, reserialized);
477
478 Ok(())
479 }
480
481 #[test]
482 fn test_application_data() -> anyhow::Result<()> {
483 let ad_1 = ApplicationData::new(10u64, &[0_u8, 1_u8])?;
484 let ad_2 = ApplicationData::try_from(ad_1.to_bytes().as_ref())?;
485 assert_eq!(ad_1, ad_2);
486
487 let ad_1 = ApplicationData::new(0u64, &[])?;
488 let ad_2 = ApplicationData::try_from(ad_1.to_bytes().as_ref())?;
489 assert_eq!(ad_1, ad_2);
490
491 let ad_1 = ApplicationData::new(10u64, &[0_u8, 1_u8])?;
492 let ad_2 = ApplicationData::try_from(ad_1.to_bytes().as_ref())?;
493 assert_eq!(ad_1, ad_2);
494
495 let ad_1 = ApplicationData::new(10u64, &[0_u8; ApplicationData::PAYLOAD_SIZE])?;
496 let ad_2 = ApplicationData::try_from(ad_1.to_bytes().as_ref())?;
497 assert_eq!(ad_1, ad_2);
498
499 assert!(ApplicationData::try_from([0_u8; Tag::SIZE - 1].as_ref()).is_err());
500 assert!(ApplicationData::try_from([0_u8; ApplicationData::PAYLOAD_SIZE + Tag::SIZE + 1].as_ref()).is_err());
501
502 Ok(())
503 }
504
505 #[test]
506 fn application_data_from_bytes_should_share_the_buffer() -> anyhow::Result<()> {
507 let original = ApplicationData::new(10u64, &[0_u8, 1_u8])?;
508 let encoded = Bytes::from(original.to_bytes().into_vec());
509
510 let decoded = ApplicationData::try_from(encoded.clone())?;
511 assert_eq!(original, decoded);
512 assert_eq!(encoded[Tag::SIZE..].as_ptr(), decoded.plain_text.as_ptr());
513
514 assert!(ApplicationData::try_from(Bytes::from(vec![0_u8; Tag::SIZE - 1])).is_err());
515 assert!(ApplicationData::try_from(Bytes::from(vec![0_u8; HoprPacket::PAYLOAD_SIZE + 1])).is_err());
516
517 Ok(())
518 }
519
520 #[test]
521 fn application_data_should_not_allow_payload_larger_than_hopr_packet_payload_size() {
522 assert!(ApplicationData::new(10u64, [0_u8; HoprPacket::PAYLOAD_SIZE + 1].as_ref()).is_err());
523 }
524
525 #[test]
526 fn a_surb_refund_should_give_back_once_per_call_and_only_when_counted() {
527 let refunds = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(5));
528 SurbRefund::default().give_back();
529 assert_eq!(
530 5,
531 refunds.load(std::sync::atomic::Ordering::Relaxed),
532 "nothing counted, nothing given back"
533 );
534
535 let refund = SurbRefund::to(refunds.clone());
536 assert!(refund.is_counted());
537 refund.give_back();
538 assert_eq!(
539 6,
540 refunds.load(std::sync::atomic::Ordering::Relaxed),
541 "the SURB is counted as given back"
542 );
543
544 assert_eq!(refund, SurbRefund::to(refunds.clone()), "the same counter");
545 assert_ne!(
546 refund,
547 SurbRefund::to(std::sync::Arc::new(std::sync::atomic::AtomicU64::new(5)))
548 );
549 assert_ne!(refund, SurbRefund::default());
550 assert_eq!(SurbRefund::default(), SurbRefund::default());
551 }
552}