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/paradigmxyz/reth/issues/"
52)]
53#![cfg_attr(not(test), warn(unused_crate_dependencies))]
54#![cfg_attr(docsrs, feature(doc_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 pub fn peer_id(&self) -> PeerId {
129 match self {
130 Self::NodeRecord(record) => record.id,
131 #[cfg(feature = "secp256k1")]
132 Self::Enr(enr) => pk2id(&enr.public_key()),
133 Self::PeerId(peer_id) => *peer_id,
134 }
135 }
136
137 pub fn node_record(&self) -> Option<NodeRecord> {
139 match self {
140 Self::NodeRecord(record) => Some(*record),
141 #[cfg(feature = "secp256k1")]
142 Self::Enr(enr) => {
143 let node_record = NodeRecord {
144 address: enr
145 .ip4()
146 .map(core::net::IpAddr::from)
147 .or_else(|| enr.ip6().map(core::net::IpAddr::from))?,
148 tcp_port: enr.tcp4().or_else(|| enr.tcp6())?,
149 udp_port: enr.udp4().or_else(|| enr.udp6())?,
150 id: pk2id(&enr.public_key()),
151 }
152 .into_ipv4_mapped();
153 Some(node_record)
154 }
155 _ => None,
156 }
157 }
158}
159
160impl From<NodeRecord> for AnyNode {
161 fn from(value: NodeRecord) -> Self {
162 Self::NodeRecord(value)
163 }
164}
165
166#[cfg(feature = "secp256k1")]
167impl From<Enr<secp256k1::SecretKey>> for AnyNode {
168 fn from(value: Enr<secp256k1::SecretKey>) -> Self {
169 Self::Enr(value)
170 }
171}
172
173impl FromStr for AnyNode {
174 type Err = String;
175
176 fn from_str(s: &str) -> Result<Self, Self::Err> {
177 if let Some(rem) = s.strip_prefix("enode://") {
178 if let Ok(record) = NodeRecord::from_str(s) {
179 return Ok(Self::NodeRecord(record))
180 }
181 if let Ok(peer_id) = PeerId::from_str(rem) {
183 return Ok(Self::PeerId(peer_id))
184 }
185 return Err(format!("invalid public key: {rem}"))
186 }
187 #[cfg(feature = "secp256k1")]
188 if s.starts_with("enr:") {
189 return Enr::from_str(s).map(AnyNode::Enr)
190 }
191 Err("missing 'enr:' prefix for base64-encoded record".to_string())
192 }
193}
194
195impl core::fmt::Display for AnyNode {
196 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
197 match self {
198 Self::NodeRecord(record) => write!(f, "{record}"),
199 #[cfg(feature = "secp256k1")]
200 Self::Enr(enr) => write!(f, "{enr}"),
201 Self::PeerId(peer_id) => {
202 write!(f, "enode://{}", alloy_primitives::hex::encode(peer_id.as_slice()))
203 }
204 }
205 }
206}
207
208#[derive(Debug)]
210pub struct WithPeerId<T>(PeerId, pub T);
211
212impl<T> From<(PeerId, T)> for WithPeerId<T> {
213 fn from(value: (PeerId, T)) -> Self {
214 Self(value.0, value.1)
215 }
216}
217
218impl<T> WithPeerId<T> {
219 pub const fn new(peer: PeerId, value: T) -> Self {
221 Self(peer, value)
222 }
223
224 pub const fn peer_id(&self) -> PeerId {
226 self.0
227 }
228
229 pub const fn data(&self) -> &T {
231 &self.1
232 }
233
234 pub fn into_data(self) -> T {
236 self.1
237 }
238
239 pub fn transform<F: From<T>>(self) -> WithPeerId<F> {
241 WithPeerId(self.0, self.1.into())
242 }
243
244 pub fn split(self) -> (PeerId, T) {
246 (self.0, self.1)
247 }
248
249 pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> WithPeerId<U> {
251 WithPeerId(self.0, op(self.1))
252 }
253}
254
255impl<T> WithPeerId<Option<T>> {
256 pub fn transpose(self) -> Option<WithPeerId<T>> {
258 self.1.map(|v| WithPeerId(self.0, v))
259 }
260
261 pub fn unwrap(self) -> T {
269 self.1.unwrap()
270 }
271
272 pub fn unwrapped(self) -> WithPeerId<T> {
278 self.transpose().unwrap()
279 }
280}
281
282#[cfg(test)]
283mod tests {
284 use super::*;
285
286 #[cfg(feature = "secp256k1")]
287 #[test]
288 fn test_node_record_parse() {
289 let url = "enode://6f8a80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@10.3.58.6:30303?discport=30301";
290 let node: AnyNode = url.parse().unwrap();
291 assert_eq!(node, AnyNode::NodeRecord(NodeRecord {
292 address: std::net::IpAddr::V4([10,3,58,6].into()),
293 tcp_port: 30303,
294 udp_port: 30301,
295 id: "6f8a80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0".parse().unwrap(),
296 }));
297 assert_eq!(node.to_string(), url)
298 }
299
300 #[test]
301 fn test_peer_id_parse() {
302 let url = "enode://6f8a80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0";
303 let node: AnyNode = url.parse().unwrap();
304 assert_eq!(node, AnyNode::PeerId("6f8a80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0".parse().unwrap()));
305 assert_eq!(node.to_string(), url);
306
307 let url = "enode://";
308 let err = url.parse::<AnyNode>().unwrap_err();
309 assert_eq!(err, "invalid public key: ");
310 }
311
312 #[cfg(feature = "secp256k1")]
314 #[test]
315 fn test_enr_parse() {
316 let url = "enr:-IS4QHCYrYZbAKWCBRlAy5zzaDZXJBGkcnh4MHcBFZntXNFrdvJjX04jRzjzCBOonrkTfj499SZuOh8R33Ls8RRcy5wBgmlkgnY0gmlwhH8AAAGJc2VjcDI1NmsxoQPKY0yuDUmstAHYpMa2_oxVtw0RW_QAdpzBQA8yWM0xOIN1ZHCCdl8";
317 let node: AnyNode = url.parse().unwrap();
318 assert_eq!(
319 node.peer_id(),
320 "0xca634cae0d49acb401d8a4c6b6fe8c55b70d115bf400769cc1400f3258cd31387574077f301b421bc84df7266c44e9e6d569fc56be00812904767bf5ccd1fc7f"
321 .parse::<PeerId>()
322 .unwrap()
323 );
324 assert_eq!(node.to_string(), url);
325 }
326
327 #[test]
328 #[cfg(feature = "secp256k1")]
329 fn pk2id2pk() {
330 let prikey = secp256k1::SecretKey::new(&mut rand_08::thread_rng());
331 let pubkey = secp256k1::PublicKey::from_secret_key(secp256k1::SECP256K1, &prikey);
332 assert_eq!(pubkey, id2pk(pk2id(&pubkey)).unwrap());
333 }
334}