Skip to main content

reth_eth_wire_types/
capability.rs

1//! All capability related types
2
3use crate::{EthMessageID, EthVersion, SnapVersion};
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    /// Encodes this message (`id` followed by its payload) to bytes.
37    pub fn encoded(&self) -> Bytes {
38        alloy_rlp::encode(self).into()
39    }
40}
41
42impl Encodable for RawCapabilityMessage {
43    /// Encodes the `RawCapabilityMessage` into an RLP byte stream.
44    fn encode(&self, out: &mut dyn BufMut) {
45        self.id.encode(out);
46        out.put_slice(&self.payload);
47    }
48
49    /// Returns the total length of the encoded message.
50    fn length(&self) -> usize {
51        self.id.length() + self.payload.len()
52    }
53}
54
55impl Decodable for RawCapabilityMessage {
56    /// Decodes a `RawCapabilityMessage` from an RLP byte stream.
57    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
58        let id = usize::decode(buf)?;
59        let payload = Bytes::copy_from_slice(buf);
60        *buf = &buf[buf.len()..];
61
62        Ok(Self { id, payload })
63    }
64}
65
66/// A message indicating a supported capability and capability version.
67#[add_arbitrary_tests(rlp)]
68#[derive(Clone, Debug, PartialEq, Eq, RlpEncodable, RlpDecodable, Default, Hash)]
69#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
70pub struct Capability {
71    /// The name of the subprotocol
72    pub name: Cow<'static, str>,
73    /// The version of the subprotocol
74    pub version: usize,
75}
76
77impl Capability {
78    /// Create a new `Capability` with the given name and version.
79    pub const fn new(name: String, version: usize) -> Self {
80        Self { name: Cow::Owned(name), version }
81    }
82
83    /// Create a new `Capability` with the given static name and version.
84    pub const fn new_static(name: &'static str, version: usize) -> Self {
85        Self { name: Cow::Borrowed(name), version }
86    }
87
88    /// Returns the corresponding eth capability for the given version.
89    pub const fn eth(version: EthVersion) -> Self {
90        Self::new_static("eth", version as usize)
91    }
92
93    /// Returns the corresponding snap capability for the given version.
94    pub const fn snap(version: SnapVersion) -> Self {
95        Self::new_static("snap", version as usize)
96    }
97
98    /// Returns the [`EthVersion::Eth66`] capability.
99    pub const fn eth_66() -> Self {
100        Self::eth(EthVersion::Eth66)
101    }
102
103    /// Returns the [`EthVersion::Eth67`] capability.
104    pub const fn eth_67() -> Self {
105        Self::eth(EthVersion::Eth67)
106    }
107
108    /// Returns the [`EthVersion::Eth68`] capability.
109    pub const fn eth_68() -> Self {
110        Self::eth(EthVersion::Eth68)
111    }
112
113    /// Returns the [`EthVersion::Eth69`] capability.
114    pub const fn eth_69() -> Self {
115        Self::eth(EthVersion::Eth69)
116    }
117
118    /// Returns the [`EthVersion::Eth70`] capability.
119    pub const fn eth_70() -> Self {
120        Self::eth(EthVersion::Eth70)
121    }
122
123    /// Returns the [`EthVersion::Eth71`] capability.
124    pub const fn eth_71() -> Self {
125        Self::eth(EthVersion::Eth71)
126    }
127
128    /// Returns the [`EthVersion::Eth72`] capability.
129    pub const fn eth_72() -> Self {
130        Self::eth(EthVersion::Eth72)
131    }
132
133    /// Returns the eth/73 capability.
134    pub const fn eth_73() -> Self {
135        Self::eth(EthVersion::Eth73)
136    }
137
138    /// Returns the `snap/2` capability.
139    pub const fn snap_2() -> Self {
140        Self::snap(SnapVersion::V2)
141    }
142
143    /// Whether this is eth v66 protocol.
144    #[inline]
145    pub fn is_eth_v66(&self) -> bool {
146        self.name == "eth" && self.version == 66
147    }
148
149    /// Whether this is eth v67.
150    #[inline]
151    pub fn is_eth_v67(&self) -> bool {
152        self.name == "eth" && self.version == 67
153    }
154
155    /// Whether this is eth v68.
156    #[inline]
157    pub fn is_eth_v68(&self) -> bool {
158        self.name == "eth" && self.version == 68
159    }
160
161    /// Whether this is eth v69.
162    #[inline]
163    pub fn is_eth_v69(&self) -> bool {
164        self.name == "eth" && self.version == 69
165    }
166
167    /// Whether this is eth v70.
168    #[inline]
169    pub fn is_eth_v70(&self) -> bool {
170        self.name == "eth" && self.version == 70
171    }
172
173    /// Whether this is eth v71.
174    #[inline]
175    pub fn is_eth_v71(&self) -> bool {
176        self.name == "eth" && self.version == 71
177    }
178
179    /// Whether this is eth v72.
180    #[inline]
181    pub fn is_eth_v72(&self) -> bool {
182        self.name == "eth" && self.version == 72
183    }
184
185    /// Whether this is eth/73.
186    pub fn is_eth_v73(&self) -> bool {
187        self.name == "eth" && self.version == 73
188    }
189
190    /// Whether this is any eth version.
191    #[inline]
192    pub fn is_eth(&self) -> bool {
193        self.is_eth_v66() ||
194            self.is_eth_v67() ||
195            self.is_eth_v68() ||
196            self.is_eth_v69() ||
197            self.is_eth_v70() ||
198            self.is_eth_v71() ||
199            self.is_eth_v72() ||
200            self.is_eth_v73()
201    }
202}
203
204impl fmt::Display for Capability {
205    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
206        write!(f, "{}/{}", self.name, self.version)
207    }
208}
209
210impl From<EthVersion> for Capability {
211    #[inline]
212    fn from(value: EthVersion) -> Self {
213        Self::eth(value)
214    }
215}
216
217#[cfg(any(test, feature = "arbitrary"))]
218impl<'a> arbitrary::Arbitrary<'a> for Capability {
219    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
220        let version = u.int_in_range(66..=73)?; // Valid eth protocol versions are 66-73
221                                                // Only generate valid eth protocol name for now
222                                                // since it's the only supported protocol
223        Ok(Self::new_static("eth", version))
224    }
225}
226
227/// Represents all capabilities of a node.
228#[derive(Debug, Clone, Eq, PartialEq)]
229pub struct Capabilities {
230    /// All Capabilities and their versions
231    inner: Vec<Capability>,
232    eth_66: bool,
233    eth_67: bool,
234    eth_68: bool,
235    eth_69: bool,
236    eth_70: bool,
237    eth_71: bool,
238    eth_72: bool,
239    eth_73: bool,
240}
241
242impl Capabilities {
243    /// Create a new instance from the given vec.
244    pub fn new(value: Vec<Capability>) -> Self {
245        Self {
246            eth_66: value.iter().any(Capability::is_eth_v66),
247            eth_67: value.iter().any(Capability::is_eth_v67),
248            eth_68: value.iter().any(Capability::is_eth_v68),
249            eth_69: value.iter().any(Capability::is_eth_v69),
250            eth_70: value.iter().any(Capability::is_eth_v70),
251            eth_71: value.iter().any(Capability::is_eth_v71),
252            eth_72: value.iter().any(Capability::is_eth_v72),
253            eth_73: value.iter().any(Capability::is_eth_v73),
254            inner: value,
255        }
256    }
257
258    /// Returns true if this peer advertises an eth protocol version that is `>= version`.
259    ///
260    /// This is **not** an exact-match check: a peer advertising only `eth/71` will return
261    /// `true` for any of `Eth66..=Eth71`, because eth versions are additive — a newer version
262    /// implies support for the messages of all earlier versions.
263    ///
264    /// Use this to gate requests on a minimum protocol version (e.g. BAL requires `eth/71`),
265    /// not to check whether a peer advertises a specific version verbatim. For exact-version
266    /// checks use the `supports_eth_vXX` helpers (e.g. [`Self::supports_eth_v71`]).
267    pub const fn supports_eth_at_least(&self, version: &EthVersion) -> bool {
268        match version {
269            EthVersion::Eth66 => {
270                self.eth_66 ||
271                    self.eth_67 ||
272                    self.eth_68 ||
273                    self.eth_69 ||
274                    self.eth_70 ||
275                    self.eth_71 ||
276                    self.eth_72 ||
277                    self.eth_73
278            }
279            EthVersion::Eth67 => {
280                self.eth_67 ||
281                    self.eth_68 ||
282                    self.eth_69 ||
283                    self.eth_70 ||
284                    self.eth_71 ||
285                    self.eth_72 ||
286                    self.eth_73
287            }
288            EthVersion::Eth68 => {
289                self.eth_68 ||
290                    self.eth_69 ||
291                    self.eth_70 ||
292                    self.eth_71 ||
293                    self.eth_72 ||
294                    self.eth_73
295            }
296            EthVersion::Eth69 => {
297                self.eth_69 || self.eth_70 || self.eth_71 || self.eth_72 || self.eth_73
298            }
299            EthVersion::Eth70 => self.eth_70 || self.eth_71 || self.eth_72 || self.eth_73,
300            EthVersion::Eth71 => self.eth_71 || self.eth_72 || self.eth_73,
301            EthVersion::Eth72 => self.eth_72 || self.eth_73,
302            EthVersion::Eth73 => self.eth_73,
303        }
304    }
305
306    /// Returns all capabilities.
307    #[inline]
308    pub fn capabilities(&self) -> &[Capability] {
309        &self.inner
310    }
311
312    /// Consumes the type and returns the all capabilities.
313    #[inline]
314    pub fn into_inner(self) -> Vec<Capability> {
315        self.inner
316    }
317
318    /// Whether the peer supports `eth` sub-protocol.
319    #[inline]
320    pub const fn supports_eth(&self) -> bool {
321        self.eth_73 ||
322            self.eth_72 ||
323            self.eth_71 ||
324            self.eth_70 ||
325            self.eth_69 ||
326            self.eth_68 ||
327            self.eth_67 ||
328            self.eth_66
329    }
330
331    /// Whether this peer supports eth v66 protocol.
332    #[inline]
333    pub const fn supports_eth_v66(&self) -> bool {
334        self.eth_66
335    }
336
337    /// Whether this peer supports eth v67 protocol.
338    #[inline]
339    pub const fn supports_eth_v67(&self) -> bool {
340        self.eth_67
341    }
342
343    /// Whether this peer supports eth v68 protocol.
344    #[inline]
345    pub const fn supports_eth_v68(&self) -> bool {
346        self.eth_68
347    }
348
349    /// Whether this peer supports eth v69 protocol.
350    #[inline]
351    pub const fn supports_eth_v69(&self) -> bool {
352        self.eth_69
353    }
354
355    /// Whether this peer supports eth v70 protocol.
356    #[inline]
357    pub const fn supports_eth_v70(&self) -> bool {
358        self.eth_70
359    }
360
361    /// Whether this peer supports eth v71 protocol.
362    #[inline]
363    pub const fn supports_eth_v71(&self) -> bool {
364        self.eth_71
365    }
366}
367
368impl From<Vec<Capability>> for Capabilities {
369    fn from(value: Vec<Capability>) -> Self {
370        Self::new(value)
371    }
372}
373
374impl Encodable for Capabilities {
375    fn length(&self) -> usize {
376        self.inner.length()
377    }
378
379    fn encode(&self, out: &mut dyn BufMut) {
380        self.inner.encode(out)
381    }
382}
383
384impl Decodable for Capabilities {
385    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
386        let inner = Vec::<Capability>::decode(buf)?;
387
388        Ok(Self {
389            eth_66: inner.iter().any(Capability::is_eth_v66),
390            eth_67: inner.iter().any(Capability::is_eth_v67),
391            eth_68: inner.iter().any(Capability::is_eth_v68),
392            eth_69: inner.iter().any(Capability::is_eth_v69),
393            eth_70: inner.iter().any(Capability::is_eth_v70),
394            eth_71: inner.iter().any(Capability::is_eth_v71),
395            eth_72: inner.iter().any(Capability::is_eth_v72),
396            eth_73: inner.iter().any(Capability::is_eth_v73),
397            inner,
398        })
399    }
400}
401
402#[cfg(test)]
403mod tests {
404    use super::*;
405    use proptest::prelude::*;
406
407    #[test]
408    fn eth73_capability_inherits_message_versions() {
409        let capability = Capability::eth_73();
410        assert!(capability.is_eth());
411        assert!(capability.is_eth_v73());
412        let capabilities = Capabilities::new(vec![capability]);
413        assert!(capabilities.supports_eth());
414        for version in [
415            EthVersion::Eth66,
416            EthVersion::Eth67,
417            EthVersion::Eth68,
418            EthVersion::Eth69,
419            EthVersion::Eth70,
420            EthVersion::Eth71,
421            EthVersion::Eth72,
422            EthVersion::Eth73,
423        ] {
424            assert!(capabilities.supports_eth_at_least(&version));
425        }
426        let old = Capabilities::new(vec![Capability::eth_72()]);
427        assert!(!old.supports_eth_at_least(&EthVersion::Eth73));
428    }
429
430    proptest! {
431        #[test]
432        fn capabilities_rlp_roundtrip_and_length(
433            versions in proptest::collection::vec(66usize..=73, 0..32),
434        ) {
435            let capabilities = Capabilities::new(
436                versions.into_iter().map(|version| Capability::new_static("eth", version)).collect(),
437            );
438            let encoded = alloy_rlp::encode(&capabilities);
439            prop_assert_eq!(capabilities.length(), encoded.len());
440            let mut buf = encoded.as_slice();
441            let decoded = Capabilities::decode(&mut buf)?;
442            prop_assert_eq!(decoded, capabilities);
443            prop_assert!(buf.is_empty());
444        }
445    }
446}