reth_eth_wire_types/
capability.rs

1//! All capability related types
2
3use crate::{EthMessageID, EthVersion};
4use alloc::{borrow::Cow, string::String, vec::Vec};
5use alloy_primitives::bytes::Bytes;
6use alloy_rlp::{Decodable, Encodable, RlpDecodable, RlpEncodable};
7use bytes::BufMut;
8use core::fmt;
9use reth_codecs_derive::add_arbitrary_tests;
10
11/// A Capability message consisting of the message-id and the payload.
12#[derive(Debug, Clone, Eq, PartialEq)]
13#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
14pub struct RawCapabilityMessage {
15    /// Identifier of the message.
16    pub id: usize,
17    /// Actual __encoded__ payload
18    pub payload: Bytes,
19}
20
21impl RawCapabilityMessage {
22    /// Creates a new capability message with the given id and payload.
23    pub const fn new(id: usize, payload: Bytes) -> Self {
24        Self { id, payload }
25    }
26
27    /// Creates a raw message for the eth sub-protocol.
28    ///
29    /// Caller must ensure that the rlp encoded `payload` matches the given `id`.
30    ///
31    /// See also  [`EthMessage`](crate::EthMessage)
32    pub const fn eth(id: EthMessageID, payload: Bytes) -> Self {
33        Self::new(id.to_u8() as usize, payload)
34    }
35}
36
37impl Encodable for RawCapabilityMessage {
38    /// Encodes the `RawCapabilityMessage` into an RLP byte stream.
39    fn encode(&self, out: &mut dyn BufMut) {
40        self.id.encode(out);
41        out.put_slice(&self.payload);
42    }
43
44    /// Returns the total length of the encoded message.
45    fn length(&self) -> usize {
46        self.id.length() + self.payload.len()
47    }
48}
49
50impl Decodable for RawCapabilityMessage {
51    /// Decodes a `RawCapabilityMessage` from an RLP byte stream.
52    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
53        let id = usize::decode(buf)?;
54        let payload = Bytes::copy_from_slice(buf);
55        *buf = &buf[buf.len()..];
56
57        Ok(Self { id, payload })
58    }
59}
60
61/// A message indicating a supported capability and capability version.
62#[add_arbitrary_tests(rlp)]
63#[derive(Clone, Debug, PartialEq, Eq, RlpEncodable, RlpDecodable, Default, Hash)]
64#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
65pub struct Capability {
66    /// The name of the subprotocol
67    pub name: Cow<'static, str>,
68    /// The version of the subprotocol
69    pub version: usize,
70}
71
72impl Capability {
73    /// Create a new `Capability` with the given name and version.
74    pub const fn new(name: String, version: usize) -> Self {
75        Self { name: Cow::Owned(name), version }
76    }
77
78    /// Create a new `Capability` with the given static name and version.
79    pub const fn new_static(name: &'static str, version: usize) -> Self {
80        Self { name: Cow::Borrowed(name), version }
81    }
82
83    /// Returns the corresponding eth capability for the given version.
84    pub const fn eth(version: EthVersion) -> Self {
85        Self::new_static("eth", version as usize)
86    }
87
88    /// Returns the [`EthVersion::Eth66`] capability.
89    pub const fn eth_66() -> Self {
90        Self::eth(EthVersion::Eth66)
91    }
92
93    /// Returns the [`EthVersion::Eth67`] capability.
94    pub const fn eth_67() -> Self {
95        Self::eth(EthVersion::Eth67)
96    }
97
98    /// Returns the [`EthVersion::Eth68`] capability.
99    pub const fn eth_68() -> Self {
100        Self::eth(EthVersion::Eth68)
101    }
102
103    /// Whether this is eth v66 protocol.
104    #[inline]
105    pub fn is_eth_v66(&self) -> bool {
106        self.name == "eth" && self.version == 66
107    }
108
109    /// Whether this is eth v67.
110    #[inline]
111    pub fn is_eth_v67(&self) -> bool {
112        self.name == "eth" && self.version == 67
113    }
114
115    /// Whether this is eth v68.
116    #[inline]
117    pub fn is_eth_v68(&self) -> bool {
118        self.name == "eth" && self.version == 68
119    }
120
121    /// Whether this is any eth version.
122    #[inline]
123    pub fn is_eth(&self) -> bool {
124        self.is_eth_v66() || self.is_eth_v67() || self.is_eth_v68()
125    }
126}
127
128impl fmt::Display for Capability {
129    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130        write!(f, "{}/{}", self.name, self.version)
131    }
132}
133
134impl From<EthVersion> for Capability {
135    #[inline]
136    fn from(value: EthVersion) -> Self {
137        Self::eth(value)
138    }
139}
140
141#[cfg(any(test, feature = "arbitrary"))]
142impl<'a> arbitrary::Arbitrary<'a> for Capability {
143    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
144        let version = u.int_in_range(66..=69)?; // Valid eth protocol versions are 66-69
145                                                // Only generate valid eth protocol name for now since it's the only supported protocol
146        Ok(Self::new_static("eth", version))
147    }
148}
149
150/// Represents all capabilities of a node.
151#[derive(Debug, Clone, Eq, PartialEq)]
152pub struct Capabilities {
153    /// All Capabilities and their versions
154    inner: Vec<Capability>,
155    eth_66: bool,
156    eth_67: bool,
157    eth_68: bool,
158}
159
160impl Capabilities {
161    /// Returns all capabilities.
162    #[inline]
163    pub fn capabilities(&self) -> &[Capability] {
164        &self.inner
165    }
166
167    /// Consumes the type and returns the all capabilities.
168    #[inline]
169    pub fn into_inner(self) -> Vec<Capability> {
170        self.inner
171    }
172
173    /// Whether the peer supports `eth` sub-protocol.
174    #[inline]
175    pub const fn supports_eth(&self) -> bool {
176        self.eth_68 || self.eth_67 || self.eth_66
177    }
178
179    /// Whether this peer supports eth v66 protocol.
180    #[inline]
181    pub const fn supports_eth_v66(&self) -> bool {
182        self.eth_66
183    }
184
185    /// Whether this peer supports eth v67 protocol.
186    #[inline]
187    pub const fn supports_eth_v67(&self) -> bool {
188        self.eth_67
189    }
190
191    /// Whether this peer supports eth v68 protocol.
192    #[inline]
193    pub const fn supports_eth_v68(&self) -> bool {
194        self.eth_68
195    }
196}
197
198impl From<Vec<Capability>> for Capabilities {
199    fn from(value: Vec<Capability>) -> Self {
200        Self {
201            eth_66: value.iter().any(Capability::is_eth_v66),
202            eth_67: value.iter().any(Capability::is_eth_v67),
203            eth_68: value.iter().any(Capability::is_eth_v68),
204            inner: value,
205        }
206    }
207}
208
209impl Encodable for Capabilities {
210    fn encode(&self, out: &mut dyn BufMut) {
211        self.inner.encode(out)
212    }
213}
214
215impl Decodable for Capabilities {
216    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
217        let inner = Vec::<Capability>::decode(buf)?;
218
219        Ok(Self {
220            eth_66: inner.iter().any(Capability::is_eth_v66),
221            eth_67: inner.iter().any(Capability::is_eth_v67),
222            eth_68: inner.iter().any(Capability::is_eth_v68),
223            inner,
224        })
225    }
226}