nym_sphinx_params/
packet_types.rs

1// Copyright 2021-2023 - Nym Technologies SA <contact@nymtech.net>
2// SPDX-License-Identifier: Apache-2.0
3
4#![allow(deprecated)]
5// allow the u8 repr of `Vpn` PacketType whilst deprecating all of its other uses
6
7use crate::PacketSize;
8use serde::{Deserialize, Serialize};
9
10use std::fmt;
11use thiserror::Error;
12
13#[derive(Error, Debug)]
14#[error("{received} is not a valid packet type tag")]
15pub struct InvalidPacketType {
16    received: u8,
17}
18
19#[repr(u8)]
20#[allow(deprecated)]
21#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Serialize, Deserialize)]
22pub enum PacketType {
23    /// Represents 'normal' packet sent through the network that should be delayed by an appropriate
24    /// value at each hop.
25    #[default]
26    #[serde(rename = "mix")]
27    #[serde(alias = "sphinx")]
28    Mix = 0,
29
30    /// Abusing this to add Outfox support
31    #[serde(rename = "outfox")]
32    Outfox = 2,
33}
34
35impl fmt::Display for PacketType {
36    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
37        match self {
38            PacketType::Mix => write!(f, "Mix"),
39            PacketType::Outfox => write!(f, "Outfox"),
40        }
41    }
42}
43
44impl PacketType {
45    pub fn is_mix(self) -> bool {
46        self == PacketType::Mix
47    }
48
49    pub fn is_outfox(self) -> bool {
50        self == PacketType::Outfox
51    }
52}
53
54impl TryFrom<u8> for PacketType {
55    type Error = InvalidPacketType;
56
57    fn try_from(value: u8) -> Result<Self, Self::Error> {
58        match value {
59            _ if value == (PacketType::Mix as u8) => Ok(Self::Mix),
60            _ if value == (PacketType::Outfox as u8) => Ok(Self::Outfox),
61            v => Err(InvalidPacketType { received: v }),
62        }
63    }
64}
65
66impl From<PacketSize> for PacketType {
67    fn from(s: PacketSize) -> Self {
68        match s {
69            PacketSize::RegularPacket => PacketType::Mix,
70            PacketSize::AckPacket => PacketType::Mix,
71            PacketSize::ExtendedPacket32 => PacketType::Mix,
72            PacketSize::ExtendedPacket8 => PacketType::Mix,
73            PacketSize::ExtendedPacket16 => PacketType::Mix,
74            PacketSize::OutfoxRegularPacket => PacketType::Outfox,
75            PacketSize::OutfoxAckPacket => PacketType::Outfox,
76        }
77    }
78}