reth_eth_wire_types/
version.rs

1//! Support for representing the version of the `eth`
2
3use crate::alloc::string::ToString;
4use alloc::string::String;
5use alloy_rlp::{Decodable, Encodable, Error as RlpError};
6use bytes::BufMut;
7use core::{fmt, str::FromStr};
8use derive_more::Display;
9use reth_codecs_derive::add_arbitrary_tests;
10
11/// Error thrown when failed to parse a valid [`EthVersion`].
12#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
13#[error("Unknown eth protocol version: {0}")]
14pub struct ParseVersionError(String);
15
16/// The `eth` protocol version.
17#[repr(u8)]
18#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]
19#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
20#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
21pub enum EthVersion {
22    /// The `eth` protocol version 66.
23    Eth66 = 66,
24    /// The `eth` protocol version 67.
25    Eth67 = 67,
26    /// The `eth` protocol version 68.
27    Eth68 = 68,
28    /// The `eth` protocol version 69.
29    Eth69 = 69,
30    /// The `eth` protocol version 70.
31    Eth70 = 70,
32}
33
34impl EthVersion {
35    /// The latest known eth version
36    pub const LATEST: Self = Self::Eth69;
37
38    /// All known eth versions
39    pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];
40
41    /// Returns true if the version is eth/66
42    pub const fn is_eth66(&self) -> bool {
43        matches!(self, Self::Eth66)
44    }
45
46    /// Returns true if the version is eth/67
47    pub const fn is_eth67(&self) -> bool {
48        matches!(self, Self::Eth67)
49    }
50
51    /// Returns true if the version is eth/68
52    pub const fn is_eth68(&self) -> bool {
53        matches!(self, Self::Eth68)
54    }
55
56    /// Returns true if the version is eth/69
57    pub const fn is_eth69(&self) -> bool {
58        matches!(self, Self::Eth69)
59    }
60
61    /// Returns true if the version is eth/70
62    pub const fn is_eth70(&self) -> bool {
63        matches!(self, Self::Eth70)
64    }
65}
66
67/// RLP encodes `EthVersion` as a single byte (66-69).
68impl Encodable for EthVersion {
69    fn encode(&self, out: &mut dyn BufMut) {
70        (*self as u8).encode(out)
71    }
72
73    fn length(&self) -> usize {
74        (*self as u8).length()
75    }
76}
77
78/// RLP decodes a single byte into `EthVersion`.
79/// Returns error if byte is not a valid version (66-69).
80impl Decodable for EthVersion {
81    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
82        let version = u8::decode(buf)?;
83        Self::try_from(version).map_err(|_| RlpError::Custom("invalid eth version"))
84    }
85}
86
87/// Allow for converting from a `&str` to an `EthVersion`.
88///
89/// # Example
90/// ```
91/// use reth_eth_wire_types::EthVersion;
92///
93/// let version = EthVersion::try_from("67").unwrap();
94/// assert_eq!(version, EthVersion::Eth67);
95/// ```
96impl TryFrom<&str> for EthVersion {
97    type Error = ParseVersionError;
98
99    #[inline]
100    fn try_from(s: &str) -> Result<Self, Self::Error> {
101        match s {
102            "66" => Ok(Self::Eth66),
103            "67" => Ok(Self::Eth67),
104            "68" => Ok(Self::Eth68),
105            "69" => Ok(Self::Eth69),
106            "70" => Ok(Self::Eth70),
107            _ => Err(ParseVersionError(s.to_string())),
108        }
109    }
110}
111
112/// Allow for converting from a u8 to an `EthVersion`.
113///
114/// # Example
115/// ```
116/// use reth_eth_wire_types::EthVersion;
117///
118/// let version = EthVersion::try_from(67).unwrap();
119/// assert_eq!(version, EthVersion::Eth67);
120/// ```
121impl TryFrom<u8> for EthVersion {
122    type Error = ParseVersionError;
123
124    #[inline]
125    fn try_from(u: u8) -> Result<Self, Self::Error> {
126        match u {
127            66 => Ok(Self::Eth66),
128            67 => Ok(Self::Eth67),
129            68 => Ok(Self::Eth68),
130            69 => Ok(Self::Eth69),
131            70 => Ok(Self::Eth70),
132            _ => Err(ParseVersionError(u.to_string())),
133        }
134    }
135}
136
137impl FromStr for EthVersion {
138    type Err = ParseVersionError;
139
140    #[inline]
141    fn from_str(s: &str) -> Result<Self, Self::Err> {
142        Self::try_from(s)
143    }
144}
145
146impl From<EthVersion> for u8 {
147    #[inline]
148    fn from(v: EthVersion) -> Self {
149        v as Self
150    }
151}
152
153impl From<EthVersion> for &'static str {
154    #[inline]
155    fn from(v: EthVersion) -> &'static str {
156        match v {
157            EthVersion::Eth66 => "66",
158            EthVersion::Eth67 => "67",
159            EthVersion::Eth68 => "68",
160            EthVersion::Eth69 => "69",
161            EthVersion::Eth70 => "70",
162        }
163    }
164}
165
166/// `RLPx` `p2p` protocol version
167#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
168#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
169#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
170#[add_arbitrary_tests(rlp)]
171pub enum ProtocolVersion {
172    /// `p2p` version 4
173    V4 = 4,
174    /// `p2p` version 5
175    #[default]
176    V5 = 5,
177}
178
179impl fmt::Display for ProtocolVersion {
180    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181        write!(f, "v{}", *self as u8)
182    }
183}
184
185impl Encodable for ProtocolVersion {
186    fn encode(&self, out: &mut dyn BufMut) {
187        (*self as u8).encode(out)
188    }
189    fn length(&self) -> usize {
190        // the version should be a single byte
191        (*self as u8).length()
192    }
193}
194
195impl Decodable for ProtocolVersion {
196    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
197        let version = u8::decode(buf)?;
198        match version {
199            4 => Ok(Self::V4),
200            5 => Ok(Self::V5),
201            _ => Err(RlpError::Custom("unknown p2p protocol version")),
202        }
203    }
204}
205
206#[cfg(test)]
207mod tests {
208    use super::EthVersion;
209    use alloy_rlp::{Decodable, Encodable, Error as RlpError};
210    use bytes::BytesMut;
211
212    #[test]
213    fn test_eth_version_try_from_str() {
214        assert_eq!(EthVersion::Eth66, EthVersion::try_from("66").unwrap());
215        assert_eq!(EthVersion::Eth67, EthVersion::try_from("67").unwrap());
216        assert_eq!(EthVersion::Eth68, EthVersion::try_from("68").unwrap());
217        assert_eq!(EthVersion::Eth69, EthVersion::try_from("69").unwrap());
218        assert_eq!(EthVersion::Eth70, EthVersion::try_from("70").unwrap());
219    }
220
221    #[test]
222    fn test_eth_version_from_str() {
223        assert_eq!(EthVersion::Eth66, "66".parse().unwrap());
224        assert_eq!(EthVersion::Eth67, "67".parse().unwrap());
225        assert_eq!(EthVersion::Eth68, "68".parse().unwrap());
226        assert_eq!(EthVersion::Eth69, "69".parse().unwrap());
227        assert_eq!(EthVersion::Eth70, "70".parse().unwrap());
228    }
229
230    #[test]
231    fn test_eth_version_rlp_encode() {
232        let versions = [
233            EthVersion::Eth66,
234            EthVersion::Eth67,
235            EthVersion::Eth68,
236            EthVersion::Eth69,
237            EthVersion::Eth70,
238        ];
239
240        for version in versions {
241            let mut encoded = BytesMut::new();
242            version.encode(&mut encoded);
243
244            assert_eq!(encoded.len(), 1);
245            assert_eq!(encoded[0], version as u8);
246        }
247    }
248    #[test]
249    fn test_eth_version_rlp_decode() {
250        let test_cases = [
251            (66_u8, Ok(EthVersion::Eth66)),
252            (67_u8, Ok(EthVersion::Eth67)),
253            (68_u8, Ok(EthVersion::Eth68)),
254            (69_u8, Ok(EthVersion::Eth69)),
255            (70_u8, Ok(EthVersion::Eth70)),
256            (65_u8, Err(RlpError::Custom("invalid eth version"))),
257        ];
258
259        for (input, expected) in test_cases {
260            let mut encoded = BytesMut::new();
261            input.encode(&mut encoded);
262
263            let mut slice = encoded.as_ref();
264            let result = EthVersion::decode(&mut slice);
265            assert_eq!(result, expected);
266        }
267    }
268}