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