reth_network_peers/
lib.rs1#![doc(
49 html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png",
50 html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256",
51 issue_tracker_base_url = "https://github.com/SeismicSystems/seismic-reth/issues/"
52)]
53#![cfg_attr(not(test), warn(unused_crate_dependencies))]
54#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
55#![cfg_attr(not(feature = "std"), no_std)]
56
57extern crate alloc;
58
59use alloc::{
60 format,
61 string::{String, ToString},
62};
63use alloy_primitives::B512;
64use core::str::FromStr;
65
66#[cfg(feature = "secp256k1")]
68pub use enr::Enr;
69
70pub type PeerId = B512;
72
73pub mod node_record;
74pub use node_record::{NodeRecord, NodeRecordParseError};
75
76pub mod trusted_peer;
77pub use trusted_peer::TrustedPeer;
78
79mod bootnodes;
80pub use bootnodes::*;
81
82#[cfg(feature = "secp256k1")]
89const SECP256K1_TAG_PUBKEY_UNCOMPRESSED: u8 = 4;
90
91#[cfg(feature = "secp256k1")]
94#[inline]
95pub fn pk2id(pk: &secp256k1::PublicKey) -> PeerId {
96 PeerId::from_slice(&pk.serialize_uncompressed()[1..])
97}
98
99#[cfg(feature = "secp256k1")]
102#[inline]
103pub fn id2pk(id: PeerId) -> Result<secp256k1::PublicKey, secp256k1::Error> {
104 let mut s = [0u8; secp256k1::constants::UNCOMPRESSED_PUBLIC_KEY_SIZE];
107 s[0] = SECP256K1_TAG_PUBKEY_UNCOMPRESSED;
108 s[1..].copy_from_slice(id.as_slice());
109 secp256k1::PublicKey::from_slice(&s)
110}
111
112#[derive(
114 Debug, Clone, Eq, PartialEq, Hash, serde_with::SerializeDisplay, serde_with::DeserializeFromStr,
115)]
116pub enum AnyNode {
117 NodeRecord(NodeRecord),
119 #[cfg(feature = "secp256k1")]
121 Enr(Enr<secp256k1::SecretKey>),
122 PeerId(PeerId),
124}
125
126impl AnyNode {
127 #[allow(clippy::missing_const_for_fn)]
129 pub fn peer_id(&self) -> PeerId {
130 match self {
131 Self::NodeRecord(record) => record.id,
132 #[cfg(feature = "secp256k1")]
133 Self::Enr(enr) => pk2id(&enr.public_key()),
134 Self::PeerId(peer_id) => *peer_id,
135 }
136 }
137
138 #[allow(clippy::missing_const_for_fn)]
140 pub fn node_record(&self) -> Option<NodeRecord> {
141 match self {
142 Self::NodeRecord(record) => Some(*record),
143 #[cfg(feature = "secp256k1")]
144 Self::Enr(enr) => {
145 let node_record = NodeRecord {
146 address: enr
147 .ip4()
148 .map(core::net::IpAddr::from)
149 .or_else(|| enr.ip6().map(core::net::IpAddr::from))?,
150 tcp_port: enr.tcp4().or_else(|| enr.tcp6())?,
151 udp_port: enr.udp4().or_else(|| enr.udp6())?,
152 id: pk2id(&enr.public_key()),
153 }
154 .into_ipv4_mapped();
155 Some(node_record)
156 }
157 _ => None,
158 }
159 }
160}
161
162impl From<NodeRecord> for AnyNode {
163 fn from(value: NodeRecord) -> Self {
164 Self::NodeRecord(value)
165 }
166}
167
168#[cfg(feature = "secp256k1")]
169impl From<Enr<secp256k1::SecretKey>> for AnyNode {
170 fn from(value: Enr<secp256k1::SecretKey>) -> Self {
171 Self::Enr(value)
172 }
173}
174
175impl FromStr for AnyNode {
176 type Err = String;
177
178 fn from_str(s: &str) -> Result<Self, Self::Err> {
179 if let Some(rem) = s.strip_prefix("enode://") {
180 if let Ok(record) = NodeRecord::from_str(s) {
181 return Ok(Self::NodeRecord(record))
182 }
183 if let Ok(peer_id) = PeerId::from_str(rem) {
185 return Ok(Self::PeerId(peer_id))
186 }
187 return Err(format!("invalid public key: {rem}"))
188 }
189 #[cfg(feature = "secp256k1")]
190 if s.starts_with("enr:") {
191 return Enr::from_str(s).map(AnyNode::Enr)
192 }
193 Err("missing 'enr:' prefix for base64-encoded record".to_string())
194 }
195}
196
197impl core::fmt::Display for AnyNode {
198 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
199 match self {
200 Self::NodeRecord(record) => write!(f, "{record}"),
201 #[cfg(feature = "secp256k1")]
202 Self::Enr(enr) => write!(f, "{enr}"),
203 Self::PeerId(peer_id) => {
204 write!(f, "enode://{}", alloy_primitives::hex::encode(peer_id.as_slice()))
205 }
206 }
207 }
208}
209
210#[derive(Debug)]
212pub struct WithPeerId<T>(PeerId, pub T);
213
214impl<T> From<(PeerId, T)> for WithPeerId<T> {
215 fn from(value: (PeerId, T)) -> Self {
216 Self(value.0, value.1)
217 }
218}
219
220impl<T> WithPeerId<T> {
221 pub const fn new(peer: PeerId, value: T) -> Self {
223 Self(peer, value)
224 }
225
226 pub const fn peer_id(&self) -> PeerId {
228 self.0
229 }
230
231 pub const fn data(&self) -> &T {
233 &self.1
234 }
235
236 pub fn into_data(self) -> T {
238 self.1
239 }
240
241 pub fn transform<F: From<T>>(self) -> WithPeerId<F> {
243 WithPeerId(self.0, self.1.into())
244 }
245
246 pub fn split(self) -> (PeerId, T) {
248 (self.0, self.1)
249 }
250
251 pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> WithPeerId<U> {
253 WithPeerId(self.0, op(self.1))
254 }
255}
256
257impl<T> WithPeerId<Option<T>> {
258 pub fn transpose(self) -> Option<WithPeerId<T>> {
260 self.1.map(|v| WithPeerId(self.0, v))
261 }
262}
263
264#[cfg(test)]
265mod tests {
266 use super::*;
267
268 #[cfg(feature = "secp256k1")]
269 #[test]
270 fn test_node_record_parse() {
271 let url = "enode://6f8a80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@10.3.58.6:30303?discport=30301";
272 let node: AnyNode = url.parse().unwrap();
273 assert_eq!(node, AnyNode::NodeRecord(NodeRecord {
274 address: std::net::IpAddr::V4([10,3,58,6].into()),
275 tcp_port: 30303,
276 udp_port: 30301,
277 id: "6f8a80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0".parse().unwrap(),
278 }));
279 assert_eq!(node.to_string(), url)
280 }
281
282 #[test]
283 fn test_peer_id_parse() {
284 let url = "enode://6f8a80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0";
285 let node: AnyNode = url.parse().unwrap();
286 assert_eq!(node, AnyNode::PeerId("6f8a80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0".parse().unwrap()));
287 assert_eq!(node.to_string(), url);
288
289 let url = "enode://";
290 let err = url.parse::<AnyNode>().unwrap_err();
291 assert_eq!(err, "invalid public key: ");
292 }
293
294 #[cfg(feature = "secp256k1")]
296 #[test]
297 fn test_enr_parse() {
298 let url = "enr:-IS4QHCYrYZbAKWCBRlAy5zzaDZXJBGkcnh4MHcBFZntXNFrdvJjX04jRzjzCBOonrkTfj499SZuOh8R33Ls8RRcy5wBgmlkgnY0gmlwhH8AAAGJc2VjcDI1NmsxoQPKY0yuDUmstAHYpMa2_oxVtw0RW_QAdpzBQA8yWM0xOIN1ZHCCdl8";
299 let node: AnyNode = url.parse().unwrap();
300 assert_eq!(
301 node.peer_id(),
302 "0xca634cae0d49acb401d8a4c6b6fe8c55b70d115bf400769cc1400f3258cd31387574077f301b421bc84df7266c44e9e6d569fc56be00812904767bf5ccd1fc7f"
303 .parse::<PeerId>()
304 .unwrap()
305 );
306 assert_eq!(node.to_string(), url);
307 }
308
309 #[test]
310 #[cfg(feature = "secp256k1")]
311 fn pk2id2pk() {
312 let prikey = secp256k1::SecretKey::new(&mut rand::thread_rng());
313 let pubkey = secp256k1::PublicKey::from_secret_key(secp256k1::SECP256K1, &prikey);
314 assert_eq!(pubkey, id2pk(pk2id(&pubkey)).unwrap());
315 }
316}