reth_network/test_utils/init.rs
1use enr::{k256::ecdsa::SigningKey, Enr, EnrPublicKey};
2use reth_network_peers::PeerId;
3use std::net::SocketAddr;
4
5/// Obtains a `PeerId` from an ENR. In this case, the `PeerId` represents the public key contained
6/// in the ENR.
7pub fn enr_to_peer_id(enr: Enr<SigningKey>) -> PeerId {
8 // In the following tests, methods which accept a public key expect it to contain the public
9 // key in its 64-byte encoded (uncompressed) form.
10 enr.public_key().encode_uncompressed().into()
11}
12
13// copied from ethers-rs
14/// A bit of hack to find an unused TCP port.
15///
16/// Does not guarantee that the given port is unused after the function exits, just that it was
17/// unused before the function started (i.e., it does not reserve a port).
18pub fn unused_port() -> u16 {
19 unused_tcp_addr().port()
20}
21
22/// Finds an unused tcp address
23pub fn unused_tcp_addr() -> SocketAddr {
24 let listener = std::net::TcpListener::bind("127.0.0.1:0")
25 .expect("Failed to create TCP listener to find unused port");
26 listener.local_addr().expect("Failed to read TCP listener local_addr to find unused port")
27}
28
29/// Finds an unused udp port
30pub fn unused_udp_port() -> u16 {
31 unused_udp_addr().port()
32}
33/// Finds an unused udp address
34pub fn unused_udp_addr() -> SocketAddr {
35 let udp_listener = std::net::UdpSocket::bind("127.0.0.1:0")
36 .expect("Failed to create UDP listener to find unused port");
37 udp_listener.local_addr().expect("Failed to read UDP listener local_addr to find unused port")
38}
39
40/// Finds a single port that is unused for both TCP and UDP.
41pub fn unused_tcp_and_udp_port() -> u16 {
42 loop {
43 let port = unused_port();
44 if std::net::UdpSocket::bind(format!("127.0.0.1:{port}")).is_ok() {
45 return port
46 }
47 }
48}
49
50/// Creates two unused `SocketAddrs`, intended for use as the p2p (TCP) and discovery ports (UDP)
51/// for new reth instances.
52pub fn unused_tcp_udp() -> (SocketAddr, SocketAddr) {
53 (unused_tcp_addr(), unused_udp_addr())
54}