reth_eth_wire/
protocol.rs

1//! A Protocol defines a P2P subprotocol in an `RLPx` connection
2
3use crate::{Capability, EthMessageID, EthVersion};
4
5/// Type that represents a [Capability] and the number of messages it uses.
6///
7/// Only the [Capability] is shared with the remote peer, assuming both parties know the number of
8/// messages used by the protocol which is used for message ID multiplexing.
9#[derive(Clone, Debug, PartialEq, Eq, Hash)]
10#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
11pub struct Protocol {
12    /// The name of the subprotocol
13    pub cap: Capability,
14    /// The number of messages used/reserved by this protocol
15    ///
16    /// This is used for message ID multiplexing
17    messages: u8,
18}
19
20impl Protocol {
21    /// Create a new protocol with the given name and number of messages
22    pub const fn new(cap: Capability, messages: u8) -> Self {
23        Self { cap, messages }
24    }
25
26    /// Returns the corresponding eth capability for the given version.
27    pub const fn eth(version: EthVersion) -> Self {
28        let cap = Capability::eth(version);
29        let messages = version.total_messages();
30        Self::new(cap, messages)
31    }
32
33    /// Returns the [`EthVersion::Eth66`] capability.
34    pub const fn eth_66() -> Self {
35        Self::eth(EthVersion::Eth66)
36    }
37
38    /// Returns the [`EthVersion::Eth67`] capability.
39    pub const fn eth_67() -> Self {
40        Self::eth(EthVersion::Eth67)
41    }
42
43    /// Returns the [`EthVersion::Eth68`] capability.
44    pub const fn eth_68() -> Self {
45        Self::eth(EthVersion::Eth68)
46    }
47
48    /// Consumes the type and returns a tuple of the [Capability] and number of messages.
49    #[inline]
50    pub(crate) fn split(self) -> (Capability, u8) {
51        (self.cap, self.messages)
52    }
53
54    /// The number of values needed to represent all message IDs of capability.
55    pub fn messages(&self) -> u8 {
56        if self.cap.is_eth() {
57            return EthMessageID::max() + 1
58        }
59        self.messages
60    }
61}
62
63impl From<EthVersion> for Protocol {
64    fn from(version: EthVersion) -> Self {
65        Self::eth(version)
66    }
67}
68
69/// A helper type to keep track of the protocol version and number of messages used by the protocol.
70#[derive(Clone, Debug, PartialEq, Eq, Hash)]
71pub(crate) struct ProtoVersion {
72    /// Number of messages for a protocol
73    pub(crate) messages: u8,
74    /// Version of the protocol
75    pub(crate) version: usize,
76}