Skip to main content

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    ///
32    /// [EIP-7975](https://eips.ethereum.org/EIPS/eip-7975) adds partial block receipt
33    /// lists by extending `GetReceipts` and `Receipts` with pagination fields.
34    Eth70 = 70,
35    /// The `eth` protocol version 71.
36    ///
37    /// [EIP-8159](https://eips.ethereum.org/EIPS/eip-8159) adds block access list
38    /// exchange with `GetBlockAccessLists` and `BlockAccessLists`.
39    Eth71 = 71,
40    /// The `eth` protocol version 72.
41    ///
42    /// [EIP-8070](https://eips.ethereum.org/EIPS/eip-8070) adds sparse blobpool
43    /// support by extending `NewPooledTransactionHashes` with `cell_mask` and adding
44    /// `GetCells` and `Cells`.
45    Eth72 = 72,
46    /// Indexed cell requests and responses ([EIP-8408](https://eips.ethereum.org/EIPS/eip-8408)).
47    Eth73 = 73,
48}
49
50impl EthVersion {
51    /// The latest known eth version
52    pub const LATEST: Self = Self::Eth71;
53
54    /// All known eth versions
55    pub const ALL_VERSIONS: &'static [Self] =
56        &[Self::Eth71, Self::Eth70, Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];
57
58    /// Returns true if the version is eth/66
59    pub const fn is_eth66(&self) -> bool {
60        matches!(self, Self::Eth66)
61    }
62
63    /// Returns true if the version is eth/67
64    pub const fn is_eth67(&self) -> bool {
65        matches!(self, Self::Eth67)
66    }
67
68    /// Returns true if the version is eth/68
69    pub const fn is_eth68(&self) -> bool {
70        matches!(self, Self::Eth68)
71    }
72
73    /// Returns true if the version carries eth/68 transaction announcement metadata.
74    pub const fn has_eth68_metadata(&self) -> bool {
75        matches!(
76            self,
77            Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72 | Self::Eth73
78        )
79    }
80
81    /// Returns true if the version is eth/69
82    pub const fn is_eth69(&self) -> bool {
83        matches!(self, Self::Eth69)
84    }
85
86    /// Returns true if the version is eth/70
87    pub const fn is_eth70(&self) -> bool {
88        matches!(self, Self::Eth70)
89    }
90
91    /// Returns true if the version is eth/71
92    pub const fn is_eth71(&self) -> bool {
93        matches!(self, Self::Eth71)
94    }
95
96    /// Returns true if the version is eth/72
97    pub const fn is_eth72(&self) -> bool {
98        matches!(self, Self::Eth72)
99    }
100
101    /// Returns true if the version is eth/73.
102    pub const fn is_eth73(&self) -> bool {
103        matches!(self, Self::Eth73)
104    }
105
106    /// Returns true if the version is eth/69 or newer.
107    pub const fn is_eth69_or_newer(&self) -> bool {
108        matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72 | Self::Eth73)
109    }
110
111    /// Returns true if the version is eth/72 or newer.
112    pub const fn is_eth72_or_newer(&self) -> bool {
113        *self as u8 >= Self::Eth72 as u8
114    }
115}
116
117/// RLP encodes `EthVersion` as a single byte (66-73).
118impl Encodable for EthVersion {
119    fn encode(&self, out: &mut dyn BufMut) {
120        (*self as u8).encode(out)
121    }
122
123    fn length(&self) -> usize {
124        (*self as u8).length()
125    }
126}
127
128/// RLP decodes a single byte into `EthVersion`.
129/// Returns error if byte is not a valid version (66-73).
130impl Decodable for EthVersion {
131    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
132        let version = u8::decode(buf)?;
133        Self::try_from(version).map_err(|_| RlpError::Custom("invalid eth version"))
134    }
135}
136
137/// Allow for converting from a `&str` to an `EthVersion`.
138///
139/// # Example
140/// ```
141/// use reth_eth_wire_types::EthVersion;
142///
143/// let version = EthVersion::try_from("67").unwrap();
144/// assert_eq!(version, EthVersion::Eth67);
145/// ```
146impl TryFrom<&str> for EthVersion {
147    type Error = ParseVersionError;
148
149    #[inline]
150    fn try_from(s: &str) -> Result<Self, Self::Error> {
151        match s {
152            "66" => Ok(Self::Eth66),
153            "67" => Ok(Self::Eth67),
154            "68" => Ok(Self::Eth68),
155            "69" => Ok(Self::Eth69),
156            "70" => Ok(Self::Eth70),
157            "71" => Ok(Self::Eth71),
158            "72" => Ok(Self::Eth72),
159            "73" => Ok(Self::Eth73),
160            _ => Err(ParseVersionError(s.to_string())),
161        }
162    }
163}
164
165/// Allow for converting from a u8 to an `EthVersion`.
166///
167/// # Example
168/// ```
169/// use reth_eth_wire_types::EthVersion;
170///
171/// let version = EthVersion::try_from(67).unwrap();
172/// assert_eq!(version, EthVersion::Eth67);
173/// ```
174impl TryFrom<u8> for EthVersion {
175    type Error = ParseVersionError;
176
177    #[inline]
178    fn try_from(u: u8) -> Result<Self, Self::Error> {
179        match u {
180            66 => Ok(Self::Eth66),
181            67 => Ok(Self::Eth67),
182            68 => Ok(Self::Eth68),
183            69 => Ok(Self::Eth69),
184            70 => Ok(Self::Eth70),
185            71 => Ok(Self::Eth71),
186            72 => Ok(Self::Eth72),
187            73 => Ok(Self::Eth73),
188            _ => Err(ParseVersionError(u.to_string())),
189        }
190    }
191}
192
193impl FromStr for EthVersion {
194    type Err = ParseVersionError;
195
196    #[inline]
197    fn from_str(s: &str) -> Result<Self, Self::Err> {
198        Self::try_from(s)
199    }
200}
201
202impl From<EthVersion> for u8 {
203    #[inline]
204    fn from(v: EthVersion) -> Self {
205        v as Self
206    }
207}
208
209impl From<EthVersion> for &'static str {
210    #[inline]
211    fn from(v: EthVersion) -> &'static str {
212        match v {
213            EthVersion::Eth66 => "66",
214            EthVersion::Eth67 => "67",
215            EthVersion::Eth68 => "68",
216            EthVersion::Eth69 => "69",
217            EthVersion::Eth70 => "70",
218            EthVersion::Eth71 => "71",
219            EthVersion::Eth72 => "72",
220            EthVersion::Eth73 => "73",
221        }
222    }
223}
224
225/// `RLPx` `p2p` protocol version
226#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
227#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
228#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
229#[add_arbitrary_tests(rlp)]
230pub enum ProtocolVersion {
231    /// `p2p` version 4
232    V4 = 4,
233    /// `p2p` version 5
234    #[default]
235    V5 = 5,
236}
237
238impl fmt::Display for ProtocolVersion {
239    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
240        write!(f, "v{}", *self as u8)
241    }
242}
243
244impl Encodable for ProtocolVersion {
245    fn encode(&self, out: &mut dyn BufMut) {
246        (*self as u8).encode(out)
247    }
248    fn length(&self) -> usize {
249        // the version should be a single byte
250        (*self as u8).length()
251    }
252}
253
254impl Decodable for ProtocolVersion {
255    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
256        let version = u8::decode(buf)?;
257        match version {
258            4 => Ok(Self::V4),
259            5 => Ok(Self::V5),
260            _ => Err(RlpError::Custom("unknown p2p protocol version")),
261        }
262    }
263}
264
265#[cfg(test)]
266mod tests {
267    use super::*;
268    use alloy_rlp::{Decodable, Encodable, Error as RlpError};
269    use bytes::BytesMut;
270
271    #[test]
272    fn test_eth_version_try_from_str() {
273        assert_eq!(EthVersion::Eth66, EthVersion::try_from("66").unwrap());
274        assert_eq!(EthVersion::Eth67, EthVersion::try_from("67").unwrap());
275        assert_eq!(EthVersion::Eth68, EthVersion::try_from("68").unwrap());
276        assert_eq!(EthVersion::Eth69, EthVersion::try_from("69").unwrap());
277        assert_eq!(EthVersion::Eth70, EthVersion::try_from("70").unwrap());
278        assert_eq!(EthVersion::Eth71, EthVersion::try_from("71").unwrap());
279        assert_eq!(EthVersion::Eth72, EthVersion::try_from("72").unwrap());
280        assert_eq!(EthVersion::Eth73, EthVersion::try_from("73").unwrap());
281    }
282
283    #[test]
284    fn test_eth_version_from_str() {
285        assert_eq!(EthVersion::Eth66, "66".parse().unwrap());
286        assert_eq!(EthVersion::Eth67, "67".parse().unwrap());
287        assert_eq!(EthVersion::Eth68, "68".parse().unwrap());
288        assert_eq!(EthVersion::Eth69, "69".parse().unwrap());
289        assert_eq!(EthVersion::Eth70, "70".parse().unwrap());
290        assert_eq!(EthVersion::Eth71, "71".parse().unwrap());
291        assert_eq!(EthVersion::Eth72, "72".parse().unwrap());
292        assert_eq!(EthVersion::Eth73, "73".parse().unwrap());
293        assert_eq!(<&str>::from(EthVersion::Eth73), "73");
294        assert!(EthVersion::Eth73.is_eth73());
295        assert!(EthVersion::Eth73.is_eth69_or_newer());
296    }
297
298    #[test]
299    fn test_has_eth68_metadata() {
300        assert!(!EthVersion::Eth66.has_eth68_metadata());
301        assert!(!EthVersion::Eth67.has_eth68_metadata());
302        assert!(EthVersion::Eth68.has_eth68_metadata());
303        assert!(EthVersion::Eth69.has_eth68_metadata());
304        assert!(EthVersion::Eth70.has_eth68_metadata());
305        assert!(EthVersion::Eth71.has_eth68_metadata());
306        assert!(EthVersion::Eth72.has_eth68_metadata());
307        assert!(EthVersion::Eth73.has_eth68_metadata());
308    }
309
310    #[test]
311    fn test_is_eth72_or_newer() {
312        assert!(!EthVersion::Eth71.is_eth72_or_newer());
313        assert!(EthVersion::Eth72.is_eth72_or_newer());
314        assert!(EthVersion::Eth73.is_eth72_or_newer());
315    }
316
317    #[test]
318    fn test_eth_version_rlp_encode() {
319        let versions = [
320            EthVersion::Eth66,
321            EthVersion::Eth67,
322            EthVersion::Eth68,
323            EthVersion::Eth69,
324            EthVersion::Eth70,
325            EthVersion::Eth71,
326            EthVersion::Eth72,
327            EthVersion::Eth73,
328        ];
329
330        for version in versions {
331            let mut encoded = BytesMut::new();
332            version.encode(&mut encoded);
333
334            assert_eq!(encoded.len(), 1);
335            assert_eq!(encoded[0], version as u8);
336        }
337    }
338    #[test]
339    fn test_eth_version_rlp_decode() {
340        let test_cases = [
341            (66_u8, Ok(EthVersion::Eth66)),
342            (67_u8, Ok(EthVersion::Eth67)),
343            (68_u8, Ok(EthVersion::Eth68)),
344            (69_u8, Ok(EthVersion::Eth69)),
345            (70_u8, Ok(EthVersion::Eth70)),
346            (71_u8, Ok(EthVersion::Eth71)),
347            (72_u8, Ok(EthVersion::Eth72)),
348            (73_u8, Ok(EthVersion::Eth73)),
349            (65_u8, Err(RlpError::Custom("invalid eth version"))),
350        ];
351
352        for (input, expected) in test_cases {
353            let mut encoded = BytesMut::new();
354            input.encode(&mut encoded);
355
356            let mut slice = encoded.as_ref();
357            let result = EthVersion::decode(&mut slice);
358            assert_eq!(result, expected);
359        }
360    }
361}