From 960ecc3f5692575dca1aee3410f8da749b53e1c3 Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Sat, 14 Nov 2026 09:49:27 -0300 Subject: [PATCH 1/6] feat: take a name as the peer, look it up before each dial, and dial its addresses in a random order until one takes the connect (#44) --- README.md | 11 +- src/logging.rs | 7 +- src/main.rs | 296 +++++++++++++++++++++++++++++++++++++++------- src/net.rs | 112 +++++++++++++----- tests/bitcoind.rs | 37 +++++- 5 files changed, 388 insertions(+), 75 deletions(-) diff --git a/README.md b/README.md index 064e43e..2c550fa 100644 --- a/README.md +++ b/README.md @@ -50,9 +50,16 @@ chain stays in memory, so the next connection syncs from its tip. A chain below the minimum work starts again from genesis. ```sh -elo [:port] # IPv6 as [::1]:8333 +elo [:port] # IPv6 as [::1]:8333 ``` +The peer is an IP address or a name. Before each dial, elo looks up the name +with the resolver of the OS, within 30 s. It takes at most 256 of its +addresses, in a random order, and dials them in that order until one takes the +connect. So a name with many addresses, such as a DNS seed, gives a new peer +on each dial. A failed lookup is an `end`, and elo looks up the name again +after 5 s. + SIGTERM and SIGINT (Ctrl-C) stop elo at any step, also in the wait before a dial. It logs the signal and exits with 0. elo exits with 1 only on a fault of this host: its async runtime or its signal handlers do not start, a write to @@ -75,7 +82,7 @@ level=info event=stop signal=SIGTERM | --- | --- | --- | | `version` | `info` | `peer` `version` `services` `user_agent` `start_height` `relay` | | `tip` | `info` | `peer` `height` `hash` `work` | -| `end` | `warn` | `peer` `reason` `wait_ms`: elo dials the peer again after `wait_ms` | +| `end` | `warn` | `peer` `reason` `wait_ms`: elo dials the peer again after `wait_ms`. `peer` is the peer of the command line, also a name | | `exit` | `error` | `reason`: a fault of this host, and elo exits with 1 | | `stop` | `info` | `signal`: elo exits with 0 | | `panic` | `error` | `reason`: a bug, and elo exits with 101 | diff --git a/src/logging.rs b/src/logging.rs index a579d5c..9bda793 100644 --- a/src/logging.rs +++ b/src/logging.rs @@ -52,9 +52,10 @@ pub enum Event<'a> { peer: std::net::SocketAddr, tip: &'a crate::chain::Tip, }, - /// The connection to `peer` ended for `reason`, and elo dials it again after `wait`. + /// The connection to `peer` ended for `reason`, and elo dials it again after `wait`. `peer` is + /// the peer of the command line: an IP address, or a name that elo looks up again. End { - peer: std::net::SocketAddr, + peer: &'a dyn std::fmt::Display, reason: &'a dyn std::fmt::Display, wait: std::time::Duration, }, @@ -302,7 +303,7 @@ mod tests { ), ( super::Event::End { - peer: PEER, + peer: &PEER, reason: &"the peer closed the connection", wait: std::time::Duration::from_secs(5), }, diff --git a/src/main.rs b/src/main.rs index 69aeb37..7706d7e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,11 +1,15 @@ -//! `elo [:port]`: dials one peer, does the handshake, and logs the peer's -//! `version`. Then it syncs the header chain from the peer and logs the tip. It asks the peer to -//! announce each new header, takes it on the tip, and logs the tip when it moves. It pings the -//! peer and answers its `ping` messages until the connection ends. Then it waits and dials the -//! peer again. The chain stays in memory, so the next connection syncs from its tip. SIGTERM -//! and SIGINT stop it at any of these steps. Each step writes a line of `elo::logging` to stdout. +//! `elo [:port]`: dials one peer, does the handshake, and logs the peer's +//! `version`. The host is an IP address or a name. Before each dial, elo looks up the name, and +//! dials its addresses in a random order until one takes the connect. Then it syncs the header +//! chain from the peer and logs the tip. It asks the peer to announce each new header, takes it on +//! the tip, and logs the tip when it moves. It pings the peer and answers its `ping` messages +//! until the connection ends. Then it waits and dials the peer again. The chain stays in memory, +//! so the next connection syncs from its tip. SIGTERM and SIGINT stop it at any of these steps. +//! Each step writes a line of `elo::logging` to stdout. -const USAGE: &str = "usage: elo [:port]"; +use std::hash::BuildHasher; + +const USAGE: &str = "usage: elo [:port]"; /// The exit code for bad usage. A stop by a signal exits with 0, and a panic with 101. Every /// other exit is 1, because only a fault of this host ends elo. @@ -15,6 +19,14 @@ const EXIT_USAGE: u8 = 2; /// down, or that ends each connection at once, gets at most one try in each wait. const RECONNECT_WAIT: std::time::Duration = std::time::Duration::from_secs(5); +/// How long the lookup of a name may take. The resolver of the OS tries each name server again +/// after its own timeout, by default 5 s, two times for each of at most 3 servers. +const LOOKUP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); + +/// The most addresses of a name that one dial tries. Each try takes at most the connect timeout, +/// so this bounds the time of a dial. +const ADDRESSES_COUNT_MAX: usize = 256; + fn main() -> std::process::ExitCode { // First of all, so each panic writes a `panic` line, and not the text of the default hook, // which is not a line of the log. A panic in this hook aborts elo. @@ -40,14 +52,15 @@ fn main() -> std::process::ExitCode { Ok(runtime) => runtime, Err(error) => return exit(&format_args!("runtime: {error}")), }; - runtime.block_on(run(network, peer)) + let code = runtime.block_on(run(network, peer)); + // A lookup runs on a blocking thread of the runtime, and a stop or a lookup timeout does not + // end it. The drop of the runtime would wait for that thread, so the runtime does not wait. + runtime.shutdown_background(); + code } /// Dials `peer` again after each end that retries, until a signal or an end that exits. -async fn run( - network: elo::chainparams::Network, - peer: std::net::SocketAddr, -) -> std::process::ExitCode { +async fn run(network: elo::chainparams::Network, peer: Peer) -> std::process::ExitCode { // Before the first dial, so a signal from here on stops elo. As PID 1 in a container, a // process with no handler never sees a SIGTERM: the kernel drops it, and the stop ends in // SIGKILL after its timeout. @@ -63,7 +76,7 @@ async fn run( loop { // The drop of the connection closes its socket. elo keeps nothing on disk, so the stop // has nothing else to finish. - let end = match signals.unless(dial(peer, &mut chain)).await { + let end = match signals.unless(dial(&peer, &mut chain)).await { Ok(Ok(end)) => end, Ok(Err(error)) => return exit_stdout(error), Err(signal) => return stop(signal), @@ -73,8 +86,10 @@ async fn run( if !end.retries() { return exit(&end); } + // The peer of the command line, and not the address of the connection: the next dial + // looks up a name again. let logged = log(&elo::logging::Event::End { - peer, + peer: &peer, reason: &end, wait: RECONNECT_WAIT, }); @@ -188,6 +203,8 @@ impl Signals { /// How one connection ended. A failed write to stdout is no end of a connection: it ends elo. #[derive(Debug)] enum End { + /// The lookup of the name of the peer failed. + Lookup(LookupError), /// The connect or the handshake failed. Handshake(elo::net::HandshakeError), /// The connection ended in the sync or after it. @@ -201,6 +218,7 @@ impl End { /// a new error does not compile until it has a side. fn retries(&self) -> bool { match self { + End::Lookup(LookupError::Failed(_) | LookupError::Timeout | LookupError::Empty) => true, End::Handshake(elo::net::HandshakeError::Salt(_)) => false, End::Handshake( elo::net::HandshakeError::Connect(_) @@ -225,6 +243,7 @@ impl End { impl std::fmt::Display for End { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { + End::Lookup(error) => write!(f, "{error}"), End::Handshake(error) => write!(f, "{error}"), End::Run(error) => write!(f, "{error}"), } @@ -234,14 +253,19 @@ impl std::fmt::Display for End { /// Dials `peer`, does the handshake and logs the `version` of the peer. Then syncs `chain` and /// logs its tip, and logs it again each time an announcement of the peer moves it, until the /// connection ends. `Err` is a failed write to stdout. -async fn dial( - peer: std::net::SocketAddr, - chain: &mut elo::chain::Chain, -) -> Result { - let (connection, version) = match elo::net::handshake(peer, chain).await { +async fn dial(peer: &Peer, chain: &mut elo::chain::Chain) -> Result { + let addresses = match peer { + Peer::Address(address) => vec![*address], + Peer::Name { host, port } => match lookup(host, *port).await { + Ok(addresses) => addresses, + Err(error) => return Ok(End::Lookup(error)), + }, + }; + let (connection, version) = match elo::net::handshake(&addresses, chain).await { Ok(handshake) => handshake, Err(error) => return Ok(End::Handshake(error)), }; + let peer = connection.address(); log(&elo::logging::Event::Version { peer, version: &version, @@ -262,11 +286,83 @@ async fn dial( } } +/// The peer that the command line names. +#[derive(Debug, PartialEq, Eq)] +enum Peer { + /// An IP address, which elo dials with no lookup. + Address(std::net::SocketAddr), + /// A name, which elo looks up before each dial. + Name { host: String, port: u16 }, +} + +impl std::fmt::Display for Peer { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Peer::Address(address) => write!(f, "{address}"), + Peer::Name { host, port } => write!(f, "{host}:{port}"), + } + } +} + +/// Why the lookup of a name gave no address to dial. +#[derive(Debug)] +enum LookupError { + /// The resolver of the OS failed. + Failed(std::io::Error), + /// The lookup took longer than `LOOKUP_TIMEOUT`. + Timeout, + /// The name has no address that names a peer. + Empty, +} + +impl std::fmt::Display for LookupError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + LookupError::Failed(error) => write!(f, "lookup: {error}"), + LookupError::Timeout => write!( + f, + "the lookup took longer than {} s", + LOOKUP_TIMEOUT.as_secs() + ), + LookupError::Empty => write!(f, "the lookup gave no address"), + } + } +} + +/// The addresses of `host` at `port`, as `dial_order` gives them. +async fn lookup(host: &str, port: u16) -> Result, LookupError> { + match tokio::time::timeout(LOOKUP_TIMEOUT, tokio::net::lookup_host((host, port))).await { + Ok(Ok(answers)) => dial_order(answers), + Ok(Err(error)) => Err(LookupError::Failed(error)), + Err(_elapsed) => Err(LookupError::Timeout), + } +} + +/// The `answers` of a lookup that name a peer, at most `ADDRESSES_COUNT_MAX`, in a random order. +/// So each dial can start on another address of a name that has many, such as a seed. The order +/// needs no secret, so it comes from the keys of `RandomState`. +fn dial_order( + answers: impl Iterator, +) -> Result, LookupError> { + // As in `parse`: `0.0.0.0` and `::` name no peer. Some resolvers give them for a name that + // they block. + let mut addresses: Vec = answers + .filter(|address| !address.ip().to_canonical().is_unspecified()) + .take(ADDRESSES_COUNT_MAX) + .collect(); + if addresses.is_empty() { + return Err(LookupError::Empty); + } + let random = std::hash::RandomState::new(); + addresses.sort_by_cached_key(|address| random.hash_one(address)); + Ok(addresses) +} + /// The args after the program name. `None` is bad usage. /// /// An IPv6 address needs brackets even without a port, because `::1:8333` is an IPv6 address /// and not `::1` with a port. -fn parse(args: &[std::ffi::OsString]) -> Option<(elo::chainparams::Network, std::net::SocketAddr)> { +fn parse(args: &[std::ffi::OsString]) -> Option<(elo::chainparams::Network, Peer)> { let [network, peer] = args else { return None; }; @@ -279,25 +375,66 @@ fn parse(args: &[std::ffi::OsString]) -> Option<(elo::chainparams::Network, std: }; let peer = peer.to_str()?; - let peer = if let Ok(peer) = peer.parse() { - peer - } else if let Some(ip) = peer.strip_prefix('[').and_then(|ip| ip.strip_suffix(']')) { - let ip = ip.parse::().ok()?; - std::net::SocketAddr::from((ip, network.default_port())) + let peer = if let Some(address) = address(peer, network.default_port()) { + // Port 0, `0.0.0.0`, `[::]` and `[::ffff:0.0.0.0]` name no peer. + if address.port() == 0 || address.ip().to_canonical().is_unspecified() { + return None; + } + Peer::Address(address) } else { - let ip = peer.parse::().ok()?; - std::net::SocketAddr::from((ip, network.default_port())) + let (host, port) = match peer.split_once(':') { + Some((host, port)) => (host, port.parse().ok()?), + None => (peer, network.default_port()), + }; + if port == 0 || !is_name(host) { + return None; + } + Peer::Name { + host: host.to_owned(), + port, + } }; - // Port 0, `0.0.0.0`, `[::]` and `[::ffff:0.0.0.0]` name no peer. - if peer.port() == 0 || peer.ip().to_canonical().is_unspecified() { - return None; - } Some((network, peer)) } +/// `peer` as an IP address with an optional port, or `None` if it is no IP address. +fn address(peer: &str, default_port: u16) -> Option { + if let Ok(address) = peer.parse() { + return Some(address); + } + let ip = match peer.strip_prefix('[').and_then(|ip| ip.strip_suffix(']')) { + Some(ip) => std::net::IpAddr::V6(ip.parse().ok()?), + None => std::net::IpAddr::V4(peer.parse().ok()?), + }; + Some(std::net::SocketAddr::from((ip, default_port))) +} + +/// Whether `host` is a name of a host: labels of letters, digits and `-`, split by `.`. A label +/// has 1 to 63 bytes, and does not start or end with `-`. The name has at most 253 bytes, and can +/// have one more `.` at the end, as a name with all its labels. The last label is not only +/// digits, so the resolver cannot read the name as an IPv4 address in a short form, such as +/// `127.1`. +fn is_name(host: &str) -> bool { + let host = host.strip_suffix('.').unwrap_or(host); + let label = |label: &str| { + (1..=63).contains(&label.len()) + && !label.starts_with('-') + && !label.ends_with('-') + && label + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-') + }; + host.len() <= 253 + && host.split('.').all(label) + && host + .rsplit('.') + .next() + .is_some_and(|last| !last.bytes().all(|byte| byte.is_ascii_digit())) +} + #[cfg(test)] mod tests { - fn parse(args: &[&str]) -> Option<(elo::chainparams::Network, std::net::SocketAddr)> { + fn parse(args: &[&str]) -> Option<(elo::chainparams::Network, super::Peer)> { let args: Vec = args.iter().map(std::ffi::OsString::from).collect(); super::parse(&args) } @@ -305,7 +442,7 @@ mod tests { // The L3 tests also hold a closed connection, which retries, and a stdout fault, which // exits. A stdout fault is no `End`, so it has no row here. #[test] - fn a_fault_of_this_host_ends_elo_and_a_failed_connect_retries() { + fn a_fault_of_this_host_ends_elo_and_a_failed_connect_or_lookup_retries() { for (end, retries) in [ ( super::End::Handshake(elo::net::HandshakeError::Salt(std::io::Error::other( @@ -323,6 +460,7 @@ mod tests { super::End::Handshake(elo::net::HandshakeError::ConnectTimeout), true, ), + (super::End::Lookup(super::LookupError::Timeout), true), ] { assert_eq!(end.retries(), retries, "{end}"); } @@ -347,40 +485,118 @@ mod tests { ("signet", elo::chainparams::Network::Signet, 38333), ("regtest", elo::chainparams::Network::Regtest, 18444), ] { - let peer = std::net::SocketAddr::from(([127, 0, 0, 1], port)); + let peer = super::Peer::Address(std::net::SocketAddr::from(([127, 0, 0, 1], port))); assert_eq!(parse(&[name, "127.0.0.1"]), Some((network, peer)), "{name}"); + let peer = super::Peer::Name { + host: "localhost".to_owned(), + port, + }; + assert_eq!(parse(&[name, "localhost"]), Some((network, peer)), "{name}"); } } #[test] - fn peer_is_an_ip_literal_with_an_optional_port() { + fn peer_is_an_ip_literal_or_a_name_with_an_optional_port() { let localhost_v6 = std::net::Ipv6Addr::LOCALHOST; + let address = |address| Some(super::Peer::Address(address)); + let name = |host: &str, port| { + Some(super::Peer::Name { + host: host.to_owned(), + port, + }) + }; + let label = "a".repeat(63); + let long = [label.as_str(); 4].join("."); + let longest = &long[..253]; for (peer, expected) in [ ( "127.0.0.1:1", - Some(std::net::SocketAddr::from(([127, 0, 0, 1], 1))), + address(std::net::SocketAddr::from(([127, 0, 0, 1], 1))), ), ( "[::1]", - Some(std::net::SocketAddr::from((localhost_v6, 18444))), + address(std::net::SocketAddr::from((localhost_v6, 18444))), ), ( "[::1]:1", - Some(std::net::SocketAddr::from((localhost_v6, 1))), + address(std::net::SocketAddr::from((localhost_v6, 1))), ), ("::1:8333", None), ("127.0.0.1:0", None), ("0.0.0.0", None), ("[::]", None), ("[::ffff:0.0.0.0]", None), - ("localhost", None), - ("localhost:18444", None), + ("[localhost]", None), + ("localhost", name("localhost", 18444)), + ("localhost:1", name("localhost", 1)), + ("seed-1.example.org", name("seed-1.example.org", 18444)), + ("x9.Seed.example", name("x9.Seed.example", 18444)), + ("1a", name("1a", 18444)), + (longest, name(longest, 18444)), + (&long[..254], None), + (&format!("{label}a"), None), + ("localhost:0", None), + ("localhost:65536", None), + ("localhost:", None), + ("localhost.", name("localhost.", 18444)), + ("localhost..", None), + (".", None), + (&format!("{longest}."), name(&format!("{longest}."), 18444)), + (".localhost", None), + ("local..host", None), + ("-localhost", None), + ("localhost-", None), + ("local_host", None), + ("local host", None), + ("127.1", None), + ("999.0.0.1", None), + ("", None), ] { let parsed = parse(&["regtest", peer]).map(|(_, peer)| peer); assert_eq!(parsed, expected, "{peer}"); } } + #[test] + fn dial_order_drops_the_answers_that_name_no_peer_and_keeps_at_most_the_count_max() { + let unspecified = [ + std::net::SocketAddr::from(([0, 0, 0, 0], 1)), + std::net::SocketAddr::from((std::net::Ipv6Addr::UNSPECIFIED, 1)), + std::net::SocketAddr::from((std::net::Ipv4Addr::UNSPECIFIED.to_ipv6_mapped(), 1)), + ]; + let result = super::dial_order(unspecified.into_iter()); + assert!( + matches!(result, Err(super::LookupError::Empty)), + "{result:?}" + ); + + // One more than the count max, after the unspecified ones. Each port is new, so the + // ones that it keeps are the first ones. + let answers: Vec = (1..=super::ADDRESSES_COUNT_MAX + 1) + .map(|port| std::net::SocketAddr::from(([127, 0, 0, 1], u16::try_from(port).unwrap()))) + .collect(); + let mut kept = + super::dial_order(unspecified.into_iter().chain(answers.iter().copied())).unwrap(); + kept.sort_unstable(); + assert_eq!(kept, answers[..super::ADDRESSES_COUNT_MAX]); + } + + // The resolver of the OS reads `localhost` from its hosts file, with no name server. + #[test] + fn lookup_gives_the_addresses_of_a_name_with_the_port() { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_io() + .enable_time() + .build() + .unwrap(); + let addresses = runtime.block_on(super::lookup("localhost", 1)).unwrap(); + assert!(!addresses.is_empty()); + for address in addresses { + assert!(address.ip().is_loopback(), "{address}"); + assert_eq!(address.port(), 1, "{address}"); + } + } + #[test] fn usage_is_a_network_name_and_a_peer() { for args in [ diff --git a/src/net.rs b/src/net.rs index ae2521e..6c23d81 100644 --- a/src/net.rs +++ b/src/net.rs @@ -137,6 +137,8 @@ enum ReceiveError { pub struct Connection<'a> { socket: Socket, peer: crate::net_processing::Peer<'a>, + /// The address of the peer that took the connect. + address: std::net::SocketAddr, } /// One peer after the header sync. Only `Connection::sync` makes one, so `next_tip` cannot start @@ -176,25 +178,47 @@ enum PartialFrame { }, } -/// Dials `peer` on the network of `chain` and runs the handshake. Returns the connection for the -/// messages after it, and their `version`. The sync of the connection extends `chain` from its +/// Dials the first of `peers` that takes the TCP connect, in their order, on the network of +/// `chain`, and runs the handshake. Returns the connection for the messages after it, and their +/// `version`. The sync of the connection extends `chain` from its /// tip, so the next connection with the same chain does not get those headers again. A chain /// below the minimum work starts again from genesis. A peer whose chain does not have our tip /// answers from the highest header of our locator on its chain, and a branch with more work takes /// the place of ours. -pub async fn handshake( - peer: std::net::SocketAddr, - chain: &mut crate::chain::Chain, -) -> Result<(Connection<'_>, crate::protocol::Version), HandshakeError> { - let connect = tokio::net::TcpStream::connect(peer); - let stream = match tokio::time::timeout(CONNECT_TIMEOUT, connect).await { - Ok(Ok(stream)) => stream, - Ok(Err(error)) => return Err(HandshakeError::Connect(error)), - Err(_elapsed) => return Err(HandshakeError::ConnectTimeout), - }; +pub async fn handshake<'a>( + peers: &[std::net::SocketAddr], + chain: &'a mut crate::chain::Chain, +) -> Result<(Connection<'a>, crate::protocol::Version), HandshakeError> { + let (peer, stream) = connect_first(peers).await?; handshake_stream(peer, stream, chain).await } +/// The TCP connect to the first of `peers` that takes it. Each try takes at most +/// `CONNECT_TIMEOUT`, so the length of `peers` bounds the time. When each try fails, the error is +/// the one of the last peer. +async fn connect_first( + peers: &[std::net::SocketAddr], +) -> Result<(std::net::SocketAddr, tokio::net::TcpStream), HandshakeError> { + let Some((&last, before)) = peers.split_last() else { + panic!("no peer to dial"); + }; + for &peer in before { + if let Ok(stream) = connect(peer).await { + return Ok((peer, stream)); + } + } + connect(last).await.map(|stream| (last, stream)) +} + +/// The TCP connect to `peer`, within `CONNECT_TIMEOUT`. +async fn connect(peer: std::net::SocketAddr) -> Result { + match tokio::time::timeout(CONNECT_TIMEOUT, tokio::net::TcpStream::connect(peer)).await { + Ok(Ok(stream)) => Ok(stream), + Ok(Err(error)) => Err(HandshakeError::Connect(error)), + Err(_elapsed) => Err(HandshakeError::ConnectTimeout), + } +} + /// The handshake on a connected `stream`, within `HANDSHAKE_TIMEOUT`. async fn handshake_stream( peer: std::net::SocketAddr, @@ -211,7 +235,7 @@ async fn handshake_stream( /// Sends our `version`, then reads messages until the handshake is done. The handshake /// bounds the loop: it refuses a peer that sends too many messages without its `verack`. async fn handshake_stream_exchange( - peer: std::net::SocketAddr, + address: std::net::SocketAddr, stream: tokio::net::TcpStream, chain: &mut crate::chain::Chain, ) -> Result<(Connection<'_>, crate::protocol::Version), HandshakeError> { @@ -219,8 +243,14 @@ async fn handshake_stream_exchange( let mut socket = Socket::new(stream, network); let work_min = crate::pow::chain_work_min(network); let salt = salt().map_err(HandshakeError::Salt)?; - let (mut handshake, outbound) = - crate::net_processing::Handshake::start(peer, timestamp(), nonce(), chain, work_min, salt); + let (mut handshake, outbound) = crate::net_processing::Handshake::start( + address, + timestamp(), + nonce(), + chain, + work_min, + salt, + ); socket .send_handshake_outbound(&outbound) .await @@ -243,7 +273,11 @@ async fn handshake_stream_exchange( // The peer can send more frames in the same segment as its `verack`. Each read // stops at the end of a frame, so they are still in the stream, and `sync` reads // them next. - let connection = Connection { socket, peer }; + let connection = Connection { + socket, + peer, + address, + }; return Ok((connection, theirs)); } } @@ -251,6 +285,11 @@ async fn handshake_stream_exchange( } impl<'a> Connection<'a> { + /// The address of the peer: of the peers that `handshake` got, the one that took the connect. + pub fn address(&self) -> std::net::SocketAddr { + self.address + } + /// Runs one turn after the other until a batch that is not full ends the sync. Returns the /// peer for `Synced::next_tip`, and the tip of our chain. The loop has no count bound, because /// only the chain of the peer bounds the sync. A low-work sync gets the chain twice, and the @@ -268,6 +307,7 @@ impl<'a> Connection<'a> { let Connection { mut socket, mut peer, + address: _, } = self; loop { match run_turn(&mut socket, peer).await? { @@ -820,7 +860,7 @@ mod tests { verack }); - let result = block_on(super::handshake(peer, &mut chain)); + let result = block_on(super::handshake(&[peer], &mut chain)); let verack = peer_thread.join().unwrap(); assert_eq!(verack, crate::fixtures::hex(crate::fixtures::VERACK_FRAME)); assert!(result.is_ok(), "{result:?}"); @@ -849,7 +889,7 @@ mod tests { i64::try_from(elapsed.as_secs()).unwrap() }; let before = seconds(); - let _closed = block_on(super::handshake(peer, &mut chain)); + let _closed = block_on(super::handshake(&[peer], &mut chain)); let after = seconds(); let message = peer_thread.join().unwrap(); assert_eq!(message.msg_type(), crate::protocol::VERSION); @@ -903,7 +943,7 @@ mod tests { }); let (result, elapsed) = block_on(async { - let (connection, _theirs) = super::handshake(peer, &mut chain).await.unwrap(); + let (connection, _theirs) = super::handshake(&[peer], &mut chain).await.unwrap(); tokio::time::pause(); let start = tokio::time::Instant::now(); let result = connection.sync().await; @@ -960,7 +1000,7 @@ mod tests { }); let result = block_on(async { - let (connection, _theirs) = super::handshake(peer, &mut chain).await.unwrap(); + let (connection, _theirs) = super::handshake(&[peer], &mut chain).await.unwrap(); connection.sync().await }); peer_thread.join().unwrap(); @@ -1019,7 +1059,7 @@ mod tests { }); let result = block_on(async { - let (connection, _theirs) = super::handshake(peer, &mut chain).await.unwrap(); + let (connection, _theirs) = super::handshake(&[peer], &mut chain).await.unwrap(); connection.sync().await }); let expected = [ @@ -1063,7 +1103,7 @@ mod tests { }); let (error, elapsed) = block_on(async { - let (connection, _theirs) = super::handshake(peer, &mut chain).await.unwrap(); + let (connection, _theirs) = super::handshake(&[peer], &mut chain).await.unwrap(); let start = tokio::time::Instant::now(); let (synced, _tip) = connection.sync().await.unwrap(); tokio::time::pause(); @@ -1118,7 +1158,7 @@ mod tests { }); let (synced_tip, next_tip) = block_on(async { - let (connection, _theirs) = super::handshake(peer, &mut chain).await.unwrap(); + let (connection, _theirs) = super::handshake(&[peer], &mut chain).await.unwrap(); let (synced, synced_tip) = connection.sync().await.unwrap(); let (_synced, next_tip) = synced.next_tip().await.unwrap(); (synced_tip, next_tip) @@ -1160,7 +1200,7 @@ mod tests { }); let (error, elapsed) = block_on(async { - let (connection, _theirs) = super::handshake(peer, &mut chain).await.unwrap(); + let (connection, _theirs) = super::handshake(&[peer], &mut chain).await.unwrap(); let start = tokio::time::Instant::now(); let (synced, _tip) = connection.sync().await.unwrap(); tokio::time::pause(); @@ -1197,7 +1237,7 @@ mod tests { let peer_thread = std::thread::spawn(move || accept_handshake(&listener)); let (result, elapsed) = block_on(async { - let (connection, _theirs) = super::handshake(peer, &mut chain).await.unwrap(); + let (connection, _theirs) = super::handshake(&[peer], &mut chain).await.unwrap(); // The peer thread ends when it has sent its `verack`, so this wait blocks nothing. // The stream stays open, and nothing reads it. let _stream = peer_thread.join().unwrap(); @@ -1239,7 +1279,7 @@ mod tests { stream.write_all(&frame[..frame.len() - 1]).unwrap(); }); - let result = block_on(super::handshake(peer, &mut chain)); + let result = block_on(super::handshake(&[peer], &mut chain)); peer_thread.join().unwrap(); assert!( matches!(result, Err(super::HandshakeError::Closed)), @@ -1318,7 +1358,7 @@ mod tests { }); let result = block_on(async { - let (connection, _theirs) = super::handshake(peer, &mut chain).await.unwrap(); + let (connection, _theirs) = super::handshake(&[peer], &mut chain).await.unwrap(); connection.sync().await }); let pong = peer_thread.join().unwrap(); @@ -1340,7 +1380,7 @@ mod tests { .unwrap() .local_addr() .unwrap(); - let result = block_on(super::handshake(peer, &mut chain)); + let result = block_on(super::handshake(&[peer], &mut chain)); assert!( matches!( result, @@ -1351,6 +1391,22 @@ mod tests { ); } + #[test] + fn connect_takes_the_first_peer_that_takes_it() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let listening = listener.local_addr().unwrap(); + // Nothing listens on a port that was bound and then freed. The listener is open while + // the bind picks the port, so the two ports differ. + let refused = std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap(); + for peers in [[refused, listening], [listening, refused]] { + let (peer, _stream) = block_on(super::connect_first(&peers)).unwrap(); + assert_eq!(peer, listening, "{peers:?}"); + } + } + #[test] fn each_salt_word_is_new() { // A fixed salt, or one that reads a word twice, passes each other test, and a peer that diff --git a/tests/bitcoind.rs b/tests/bitcoind.rs index 319c4b5..85e39a4 100644 --- a/tests/bitcoind.rs +++ b/tests/bitcoind.rs @@ -167,7 +167,7 @@ fn handshake_with_bitcoind_returns_its_version() { .unwrap(); let mut chain = elo::chain::Chain::new(elo::chainparams::Network::Regtest); let (_connection, version) = runtime - .block_on(elo::net::handshake(bitcoind.peer, &mut chain)) + .block_on(elo::net::handshake(&[bitcoind.peer], &mut chain)) .unwrap(); assert_eq!(version.version(), 70016); @@ -304,6 +304,34 @@ fn closed_connection_gets_a_new_handshake_and_sync() { assert_eq!(elo.event("tip", SYNC_TIMEOUT), tip); } +#[test] +fn peer_with_a_name_gets_a_lookup_and_a_dial_to_its_address() { + let bitcoind = Bitcoind::start(); + let named = format!("localhost:{}", bitcoind.peer.port()); + let elo = Elo::start_on(&named); + + // `localhost` can also have `::1`, where bitcoind does not listen. elo tries each address of + // the name in one dial, so the first dial gets to bitcoind, with no `end` before it. + let version = elo.event("version", SYNC_TIMEOUT); + let expected = format!( + "level=info event=version peer={} version=70016 ", + bitcoind.peer + ); + assert!(version.starts_with(&expected), "{version}"); + let ends = elo.events("end"); + assert!(ends.is_empty(), "{ends:?}"); + + // The `end` has the name, because the next dial looks it up again. elo is the only peer of + // bitcoind, so it is node 0. + elo.event("tip", SYNC_TIMEOUT); + bitcoind.cli(&["-named", "disconnectnode", "nodeid=0"]); + let end = elo.event("end", END_TIMEOUT); + assert!( + end.starts_with(&format!("level=warn event=end peer={named} ")), + "{end}" + ); +} + #[test] fn signal_in_a_connection_exits_with_0() { let bitcoind = Bitcoind::start(); @@ -640,9 +668,14 @@ struct Elo { impl Elo { fn start(bitcoind: &Bitcoind) -> Self { + Self::start_on(&bitcoind.peer.to_string()) + } + + /// elo on regtest with `peer` as the peer of its command line. + fn start_on(peer: &str) -> Self { let mut child = std::process::Command::new(env!("CARGO_BIN_EXE_elo")) .arg("regtest") - .arg(bitcoind.peer.to_string()) + .arg(peer) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()) .spawn() From d6f473042610ac7f0a17f2fd4077213cadf4e118 Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Sat, 14 Nov 2026 10:07:27 -0300 Subject: [PATCH 2/6] fix: refuse a name that the resolver reads as an IPv4 address, and move the destination, its lookup and the address bound into `net` (#44) - `Name::new` refuses a last label that is a number: only digits, or `0x` and only hex digits. glibc reads `0x7f000001` and `127.0x1` as `127.0.0.1`, and `0x0` as `0.0.0.0`. - `net::Destination` and `net::Name` take the place of `Peer` in `main`. Only `Name::new` makes a name. `Event::End.peer` is a `&Destination`. - `net::handshake` takes the destination and does the lookup. `End::Lookup` is now `HandshakeError::Lookup`. - `connect_first` asserts `ADDRESSES_COUNT_MAX`, in the module of the `take` in `dial_order`. - `HandshakeError::Connect` has the last address and the count of addresses. `ConnectError` holds the `io` error or the timeout. - `VALUE_LENGTH_MAX` is 260, and a const assert holds `DESTINATION_LENGTH_MAX` under it, so the `end` line of the longest name keeps its port. - `address` is the name of each `SocketAddr`, and `peer` stays the peer of the protocol. --- src/logging.rs | 13 +- src/main.rs | 275 ++++++++-------------------- src/net.rs | 454 +++++++++++++++++++++++++++++++++++++++------- tests/bitcoind.rs | 5 +- 4 files changed, 479 insertions(+), 268 deletions(-) diff --git a/src/logging.rs b/src/logging.rs index 9bda793..e096211 100644 --- a/src/logging.rs +++ b/src/logging.rs @@ -7,8 +7,11 @@ use std::fmt::Write; /// The most bytes of a value before its escapes. A longer value is cut, and ends with `...`. So -/// a peer that sends a long string cannot make a long line. -const VALUE_LENGTH_MAX: usize = 256; +/// a peer that sends a long string cannot make a long line. The longest destination of the +/// command line fits, so the `peer` of an `end` line is never cut. +const VALUE_LENGTH_MAX: usize = 260; + +const _: () = assert!(crate::net::DESTINATION_LENGTH_MAX <= VALUE_LENGTH_MAX); /// What `...` adds to a value that is cut. const CUT_MARK: &str = "..."; @@ -53,9 +56,9 @@ pub enum Event<'a> { tip: &'a crate::chain::Tip, }, /// The connection to `peer` ended for `reason`, and elo dials it again after `wait`. `peer` is - /// the peer of the command line: an IP address, or a name that elo looks up again. + /// the destination of the command line: an IP address, or a name that elo looks up again. End { - peer: &'a dyn std::fmt::Display, + peer: &'a crate::net::Destination, reason: &'a dyn std::fmt::Display, wait: std::time::Duration, }, @@ -303,7 +306,7 @@ mod tests { ), ( super::Event::End { - peer: &PEER, + peer: &crate::net::Destination::Address(PEER), reason: &"the peer closed the connection", wait: std::time::Duration::from_secs(5), }, diff --git a/src/main.rs b/src/main.rs index 7706d7e..713cf33 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,8 +7,6 @@ //! so the next connection syncs from its tip. SIGTERM and SIGINT stop it at any of these steps. //! Each step writes a line of `elo::logging` to stdout. -use std::hash::BuildHasher; - const USAGE: &str = "usage: elo [:port]"; /// The exit code for bad usage. A stop by a signal exits with 0, and a panic with 101. Every @@ -19,14 +17,6 @@ const EXIT_USAGE: u8 = 2; /// down, or that ends each connection at once, gets at most one try in each wait. const RECONNECT_WAIT: std::time::Duration = std::time::Duration::from_secs(5); -/// How long the lookup of a name may take. The resolver of the OS tries each name server again -/// after its own timeout, by default 5 s, two times for each of at most 3 servers. -const LOOKUP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); - -/// The most addresses of a name that one dial tries. Each try takes at most the connect timeout, -/// so this bounds the time of a dial. -const ADDRESSES_COUNT_MAX: usize = 256; - fn main() -> std::process::ExitCode { // First of all, so each panic writes a `panic` line, and not the text of the default hook, // which is not a line of the log. A panic in this hook aborts elo. @@ -38,7 +28,7 @@ fn main() -> std::process::ExitCode { })); let args: Vec = std::env::args_os().skip(1).collect(); - let Some((network, peer)) = parse(&args) else { + let Some((network, destination)) = parse(&args) else { eprintln!("{USAGE}"); return std::process::ExitCode::from(EXIT_USAGE); }; @@ -52,15 +42,18 @@ fn main() -> std::process::ExitCode { Ok(runtime) => runtime, Err(error) => return exit(&format_args!("runtime: {error}")), }; - let code = runtime.block_on(run(network, peer)); + let code = runtime.block_on(run(network, destination)); // A lookup runs on a blocking thread of the runtime, and a stop or a lookup timeout does not // end it. The drop of the runtime would wait for that thread, so the runtime does not wait. runtime.shutdown_background(); code } -/// Dials `peer` again after each end that retries, until a signal or an end that exits. -async fn run(network: elo::chainparams::Network, peer: Peer) -> std::process::ExitCode { +/// Dials `destination` again after each end that retries, until a signal or an end that exits. +async fn run( + network: elo::chainparams::Network, + destination: elo::net::Destination, +) -> std::process::ExitCode { // Before the first dial, so a signal from here on stops elo. As PID 1 in a container, a // process with no handler never sees a SIGTERM: the kernel drops it, and the stop ends in // SIGKILL after its timeout. @@ -76,7 +69,7 @@ async fn run(network: elo::chainparams::Network, peer: Peer) -> std::process::Ex loop { // The drop of the connection closes its socket. elo keeps nothing on disk, so the stop // has nothing else to finish. - let end = match signals.unless(dial(&peer, &mut chain)).await { + let end = match signals.unless(dial(&destination, &mut chain)).await { Ok(Ok(end)) => end, Ok(Err(error)) => return exit_stdout(error), Err(signal) => return stop(signal), @@ -86,10 +79,10 @@ async fn run(network: elo::chainparams::Network, peer: Peer) -> std::process::Ex if !end.retries() { return exit(&end); } - // The peer of the command line, and not the address of the connection: the next dial - // looks up a name again. + // The destination of the command line, and not the address of the connection: the next + // dial looks up a name again. let logged = log(&elo::logging::Event::End { - peer: &peer, + peer: &destination, reason: &end, wait: RECONNECT_WAIT, }); @@ -203,9 +196,7 @@ impl Signals { /// How one connection ended. A failed write to stdout is no end of a connection: it ends elo. #[derive(Debug)] enum End { - /// The lookup of the name of the peer failed. - Lookup(LookupError), - /// The connect or the handshake failed. + /// The lookup, the connect or the handshake failed. Handshake(elo::net::HandshakeError), /// The connection ended in the sync or after it. Run(elo::net::RunError), @@ -218,11 +209,17 @@ impl End { /// a new error does not compile until it has a side. fn retries(&self) -> bool { match self { - End::Lookup(LookupError::Failed(_) | LookupError::Timeout | LookupError::Empty) => true, End::Handshake(elo::net::HandshakeError::Salt(_)) => false, End::Handshake( - elo::net::HandshakeError::Connect(_) - | elo::net::HandshakeError::ConnectTimeout + elo::net::HandshakeError::Lookup( + elo::net::LookupError::Failed(_) + | elo::net::LookupError::Timeout + | elo::net::LookupError::Empty, + ) + | elo::net::HandshakeError::Connect { + error: elo::net::ConnectError::Io(_) | elo::net::ConnectError::Timeout, + .. + } | elo::net::HandshakeError::HandshakeTimeout | elo::net::HandshakeError::Io(_) | elo::net::HandshakeError::Closed @@ -243,31 +240,26 @@ impl End { impl std::fmt::Display for End { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - End::Lookup(error) => write!(f, "{error}"), End::Handshake(error) => write!(f, "{error}"), End::Run(error) => write!(f, "{error}"), } } } -/// Dials `peer`, does the handshake and logs the `version` of the peer. Then syncs `chain` and -/// logs its tip, and logs it again each time an announcement of the peer moves it, until the -/// connection ends. `Err` is a failed write to stdout. -async fn dial(peer: &Peer, chain: &mut elo::chain::Chain) -> Result { - let addresses = match peer { - Peer::Address(address) => vec![*address], - Peer::Name { host, port } => match lookup(host, *port).await { - Ok(addresses) => addresses, - Err(error) => return Ok(End::Lookup(error)), - }, - }; - let (connection, version) = match elo::net::handshake(&addresses, chain).await { +/// Dials `destination`, does the handshake and logs the `version` of the peer. Then syncs +/// `chain` and logs its tip, and logs it again each time an announcement of the peer moves it, +/// until the connection ends. `Err` is a failed write to stdout. +async fn dial( + destination: &elo::net::Destination, + chain: &mut elo::chain::Chain, +) -> Result { + let (connection, version) = match elo::net::handshake(destination, chain).await { Ok(handshake) => handshake, Err(error) => return Ok(End::Handshake(error)), }; - let peer = connection.address(); + let address = connection.address(); log(&elo::logging::Event::Version { - peer, + peer: address, version: &version, })?; @@ -278,7 +270,10 @@ async fn dial(peer: &Peer, chain: &mut elo::chain::Chain) -> Result next, Err(error) => return Ok(End::Run(error)), @@ -286,83 +281,13 @@ async fn dial(peer: &Peer, chain: &mut elo::chain::Chain) -> Result) -> std::fmt::Result { - match self { - Peer::Address(address) => write!(f, "{address}"), - Peer::Name { host, port } => write!(f, "{host}:{port}"), - } - } -} - -/// Why the lookup of a name gave no address to dial. -#[derive(Debug)] -enum LookupError { - /// The resolver of the OS failed. - Failed(std::io::Error), - /// The lookup took longer than `LOOKUP_TIMEOUT`. - Timeout, - /// The name has no address that names a peer. - Empty, -} - -impl std::fmt::Display for LookupError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - LookupError::Failed(error) => write!(f, "lookup: {error}"), - LookupError::Timeout => write!( - f, - "the lookup took longer than {} s", - LOOKUP_TIMEOUT.as_secs() - ), - LookupError::Empty => write!(f, "the lookup gave no address"), - } - } -} - -/// The addresses of `host` at `port`, as `dial_order` gives them. -async fn lookup(host: &str, port: u16) -> Result, LookupError> { - match tokio::time::timeout(LOOKUP_TIMEOUT, tokio::net::lookup_host((host, port))).await { - Ok(Ok(answers)) => dial_order(answers), - Ok(Err(error)) => Err(LookupError::Failed(error)), - Err(_elapsed) => Err(LookupError::Timeout), - } -} - -/// The `answers` of a lookup that name a peer, at most `ADDRESSES_COUNT_MAX`, in a random order. -/// So each dial can start on another address of a name that has many, such as a seed. The order -/// needs no secret, so it comes from the keys of `RandomState`. -fn dial_order( - answers: impl Iterator, -) -> Result, LookupError> { - // As in `parse`: `0.0.0.0` and `::` name no peer. Some resolvers give them for a name that - // they block. - let mut addresses: Vec = answers - .filter(|address| !address.ip().to_canonical().is_unspecified()) - .take(ADDRESSES_COUNT_MAX) - .collect(); - if addresses.is_empty() { - return Err(LookupError::Empty); - } - let random = std::hash::RandomState::new(); - addresses.sort_by_cached_key(|address| random.hash_one(address)); - Ok(addresses) -} - /// The args after the program name. `None` is bad usage. /// /// An IPv6 address needs brackets even without a port, because `::1:8333` is an IPv6 address /// and not `::1` with a port. -fn parse(args: &[std::ffi::OsString]) -> Option<(elo::chainparams::Network, Peer)> { +fn parse( + args: &[std::ffi::OsString], +) -> Option<(elo::chainparams::Network, elo::net::Destination)> { let [network, peer] = args else { return None; }; @@ -375,26 +300,26 @@ fn parse(args: &[std::ffi::OsString]) -> Option<(elo::chainparams::Network, Peer }; let peer = peer.to_str()?; - let peer = if let Some(address) = address(peer, network.default_port()) { + let destination = if let Some(address) = address(peer, network.default_port()) { // Port 0, `0.0.0.0`, `[::]` and `[::ffff:0.0.0.0]` name no peer. if address.port() == 0 || address.ip().to_canonical().is_unspecified() { return None; } - Peer::Address(address) + elo::net::Destination::Address(address) } else { let (host, port) = match peer.split_once(':') { Some((host, port)) => (host, port.parse().ok()?), None => (peer, network.default_port()), }; - if port == 0 || !is_name(host) { + if port == 0 { return None; } - Peer::Name { - host: host.to_owned(), + elo::net::Destination::Name { + name: elo::net::Name::new(host)?, port, } }; - Some((network, peer)) + Some((network, destination)) } /// `peer` as an IP address with an optional port, or `None` if it is no IP address. @@ -409,32 +334,9 @@ fn address(peer: &str, default_port: u16) -> Option { Some(std::net::SocketAddr::from((ip, default_port))) } -/// Whether `host` is a name of a host: labels of letters, digits and `-`, split by `.`. A label -/// has 1 to 63 bytes, and does not start or end with `-`. The name has at most 253 bytes, and can -/// have one more `.` at the end, as a name with all its labels. The last label is not only -/// digits, so the resolver cannot read the name as an IPv4 address in a short form, such as -/// `127.1`. -fn is_name(host: &str) -> bool { - let host = host.strip_suffix('.').unwrap_or(host); - let label = |label: &str| { - (1..=63).contains(&label.len()) - && !label.starts_with('-') - && !label.ends_with('-') - && label - .bytes() - .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-') - }; - host.len() <= 253 - && host.split('.').all(label) - && host - .rsplit('.') - .next() - .is_some_and(|last| !last.bytes().all(|byte| byte.is_ascii_digit())) -} - #[cfg(test)] mod tests { - fn parse(args: &[&str]) -> Option<(elo::chainparams::Network, super::Peer)> { + fn parse(args: &[&str]) -> Option<(elo::chainparams::Network, elo::net::Destination)> { let args: Vec = args.iter().map(std::ffi::OsString::from).collect(); super::parse(&args) } @@ -451,16 +353,19 @@ mod tests { false, ), ( - super::End::Handshake(elo::net::HandshakeError::Connect(std::io::Error::other( - "connect", - ))), + super::End::Handshake(elo::net::HandshakeError::Connect { + address: std::net::SocketAddr::from(([127, 0, 0, 1], 1)), + addresses_count: 1, + error: elo::net::ConnectError::Timeout, + }), true, ), ( - super::End::Handshake(elo::net::HandshakeError::ConnectTimeout), + super::End::Handshake(elo::net::HandshakeError::Lookup( + elo::net::LookupError::Timeout, + )), true, ), - (super::End::Lookup(super::LookupError::Timeout), true), ] { assert_eq!(end.retries(), retries, "{end}"); } @@ -485,23 +390,32 @@ mod tests { ("signet", elo::chainparams::Network::Signet, 38333), ("regtest", elo::chainparams::Network::Regtest, 18444), ] { - let peer = super::Peer::Address(std::net::SocketAddr::from(([127, 0, 0, 1], port))); - assert_eq!(parse(&[name, "127.0.0.1"]), Some((network, peer)), "{name}"); - let peer = super::Peer::Name { - host: "localhost".to_owned(), + let address = std::net::SocketAddr::from(([127, 0, 0, 1], port)); + let destination = elo::net::Destination::Address(address); + assert_eq!( + parse(&[name, "127.0.0.1"]), + Some((network, destination)), + "{name}" + ); + let destination = elo::net::Destination::Name { + name: elo::net::Name::new("localhost").unwrap(), port, }; - assert_eq!(parse(&[name, "localhost"]), Some((network, peer)), "{name}"); + assert_eq!( + parse(&[name, "localhost"]), + Some((network, destination)), + "{name}" + ); } } #[test] fn peer_is_an_ip_literal_or_a_name_with_an_optional_port() { let localhost_v6 = std::net::Ipv6Addr::LOCALHOST; - let address = |address| Some(super::Peer::Address(address)); + let address = |address| Some(elo::net::Destination::Address(address)); let name = |host: &str, port| { - Some(super::Peer::Name { - host: host.to_owned(), + Some(elo::net::Destination::Name { + name: elo::net::Name::new(host).unwrap(), port, }) }; @@ -550,53 +464,20 @@ mod tests { ("local host", None), ("127.1", None), ("999.0.0.1", None), + ("0x7f000001", None), + ("0X7F000001", None), + ("127.0x1", None), + ("0x0", None), + ("0x7f000001.", None), + ("0x7g", name("0x7g", 18444)), + ("0x7f.example", name("0x7f.example", 18444)), ("", None), ] { - let parsed = parse(&["regtest", peer]).map(|(_, peer)| peer); + let parsed = parse(&["regtest", peer]).map(|(_, destination)| destination); assert_eq!(parsed, expected, "{peer}"); } } - #[test] - fn dial_order_drops_the_answers_that_name_no_peer_and_keeps_at_most_the_count_max() { - let unspecified = [ - std::net::SocketAddr::from(([0, 0, 0, 0], 1)), - std::net::SocketAddr::from((std::net::Ipv6Addr::UNSPECIFIED, 1)), - std::net::SocketAddr::from((std::net::Ipv4Addr::UNSPECIFIED.to_ipv6_mapped(), 1)), - ]; - let result = super::dial_order(unspecified.into_iter()); - assert!( - matches!(result, Err(super::LookupError::Empty)), - "{result:?}" - ); - - // One more than the count max, after the unspecified ones. Each port is new, so the - // ones that it keeps are the first ones. - let answers: Vec = (1..=super::ADDRESSES_COUNT_MAX + 1) - .map(|port| std::net::SocketAddr::from(([127, 0, 0, 1], u16::try_from(port).unwrap()))) - .collect(); - let mut kept = - super::dial_order(unspecified.into_iter().chain(answers.iter().copied())).unwrap(); - kept.sort_unstable(); - assert_eq!(kept, answers[..super::ADDRESSES_COUNT_MAX]); - } - - // The resolver of the OS reads `localhost` from its hosts file, with no name server. - #[test] - fn lookup_gives_the_addresses_of_a_name_with_the_port() { - let runtime = tokio::runtime::Builder::new_current_thread() - .enable_io() - .enable_time() - .build() - .unwrap(); - let addresses = runtime.block_on(super::lookup("localhost", 1)).unwrap(); - assert!(!addresses.is_empty()); - for address in addresses { - assert!(address.ip().is_loopback(), "{address}"); - assert_eq!(address.port(), 1, "{address}"); - } - } - #[test] fn usage_is_a_network_name_and_a_peer() { for args in [ diff --git a/src/net.rs b/src/net.rs index 6c23d81..ce917da 100644 --- a/src/net.rs +++ b/src/net.rs @@ -17,13 +17,161 @@ const HANDSHAKE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60 /// read can block forever. The ping timeout covers each read. const SEND_TIMEOUT: std::time::Duration = std::time::Duration::from_mins(20); -/// Why the connect or the handshake failed. +/// How long the lookup of a name may take. The resolver of the OS tries each name server again +/// after its own timeout, by default 5 s, two times for each of at most 3 servers. +const LOOKUP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); + +/// The most addresses of a name that one dial tries. Each try takes at most `CONNECT_TIMEOUT`, so +/// this bounds the time of a dial. +const ADDRESSES_COUNT_MAX: usize = 256; + +/// The most bytes of a name, with no `.` at the end. +const NAME_LENGTH_MAX: usize = 253; + +/// The most bytes of one label of a name. +const LABEL_LENGTH_MAX: usize = 63; + +/// The most bytes of the text of a `Destination`: a name of `NAME_LENGTH_MAX` bytes, its `.` at +/// the end, and the longest port. An IP address with its port is shorter: at most 58 bytes, an +/// IPv6 address with a scope. +pub(crate) const DESTINATION_LENGTH_MAX: usize = NAME_LENGTH_MAX + ".".len() + ":65535".len(); + +/// The peer that the command line names. +#[derive(Debug, PartialEq, Eq)] +pub enum Destination { + /// An IP address, which `handshake` dials with no lookup. + Address(std::net::SocketAddr), + /// A name, which `handshake` looks up before each dial. + Name { name: Name, port: u16 }, +} + +impl std::fmt::Display for Destination { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Destination::Address(address) => write!(f, "{address}"), + Destination::Name { name, port } => write!(f, "{name}:{port}"), + } + } +} + +/// The name of a host. Only `Name::new` makes one, so each name has the form that it checks. +#[derive(Debug, PartialEq, Eq)] +pub struct Name(String); + +impl Name { + /// `host` as a name, or `None` if it is no name. A name has labels, split by `.`, of at most + /// `NAME_LENGTH_MAX` bytes in all, and can have one more `.` at the end, as a name with all + /// its labels. The last label is no number, so the resolver cannot read the name as an IPv4 + /// address. + pub fn new(host: &str) -> Option { + let labels = host.strip_suffix('.').unwrap_or(host); + if labels.len() > NAME_LENGTH_MAX { + return None; + } + if !labels.split('.').all(is_label) { + return None; + } + let last = labels.rsplit_once('.').map_or(labels, |(_, last)| last); + if is_number(last) { + return None; + } + Some(Name(host.to_owned())) + } +} + +impl std::fmt::Display for Name { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.0) + } +} + +/// Whether `label` is a label of a name: 1 to `LABEL_LENGTH_MAX` letters, digits and `-`, with no +/// `-` at the start or the end. +fn is_label(label: &str) -> bool { + if label.is_empty() { + return false; + } + if label.len() > LABEL_LENGTH_MAX { + return false; + } + if label.starts_with('-') || label.ends_with('-') { + return false; + } + label + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-') +} + +/// Whether the IPv4 parse of the resolver reads `label` as a number: only digits, or `0x` and +/// only hex digits. That parse also reads the short forms, so `127.1`, `0x7f000001` and `127.0x1` +/// are each `127.0.0.1`. It needs each part to be a number, so a name whose last label is no +/// number goes to DNS. Octal, after a `0`, has only digits. +fn is_number(label: &str) -> bool { + let (digits, radix) = match label + .strip_prefix("0x") + .or_else(|| label.strip_prefix("0X")) + { + Some(hex) => (hex, 16), + None => (label, 10), + }; + digits.chars().all(|digit| digit.is_digit(radix)) +} + +/// Why the lookup of a name gave no address to dial. +#[derive(Debug)] +pub enum LookupError { + /// The resolver of the OS failed. + Failed(std::io::Error), + /// The lookup took longer than `LOOKUP_TIMEOUT`. + Timeout, + /// The name has no address that names a peer. + Empty, +} + +impl std::fmt::Display for LookupError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + LookupError::Failed(error) => write!(f, "lookup: {error}"), + LookupError::Timeout => write!( + f, + "the lookup took longer than {} s", + LOOKUP_TIMEOUT.as_secs() + ), + LookupError::Empty => write!(f, "the lookup gave no address"), + } + } +} + +/// Why the TCP connect to one address failed. +#[derive(Debug)] +pub enum ConnectError { + /// The connect failed. + Io(std::io::Error), + /// The connect took longer than `CONNECT_TIMEOUT`. + Timeout, +} + +impl std::fmt::Display for ConnectError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ConnectError::Io(error) => write!(f, "{error}"), + ConnectError::Timeout => write!(f, "took longer than {} s", CONNECT_TIMEOUT.as_secs()), + } + } +} + +/// Why the lookup, the connect or the handshake failed. #[derive(Debug)] pub enum HandshakeError { - /// The TCP connect failed. - Connect(std::io::Error), - /// The TCP connect took longer than `CONNECT_TIMEOUT`. - ConnectTimeout, + /// The lookup of the name of the destination failed. + Lookup(LookupError), + /// The TCP connect to each address of the destination failed. `address` is the last one, + /// `error` is its error, and `addresses_count` is how many addresses `handshake` tried. + Connect { + address: std::net::SocketAddr, + addresses_count: usize, + error: ConnectError, + }, /// The handshake took longer than `HANDSHAKE_TIMEOUT`. HandshakeTimeout, /// A read or a write on the socket failed. @@ -41,14 +189,20 @@ pub enum HandshakeError { impl std::fmt::Display for HandshakeError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - HandshakeError::Connect(error) => write!(f, "connect: {error}"), - HandshakeError::ConnectTimeout => { - write!( - f, - "connect took longer than {} s", - CONNECT_TIMEOUT.as_secs() - ) - } + HandshakeError::Lookup(error) => write!(f, "{error}"), + HandshakeError::Connect { + address, + addresses_count: 1, + error, + } => write!(f, "connect to {address}: {error}"), + HandshakeError::Connect { + address, + addresses_count, + error, + } => write!( + f, + "connect to {address}, the last of {addresses_count} addresses: {error}" + ), HandshakeError::HandshakeTimeout => { write!( f, @@ -178,54 +332,103 @@ enum PartialFrame { }, } -/// Dials the first of `peers` that takes the TCP connect, in their order, on the network of -/// `chain`, and runs the handshake. Returns the connection for the messages after it, and their -/// `version`. The sync of the connection extends `chain` from its -/// tip, so the next connection with the same chain does not get those headers again. A chain -/// below the minimum work starts again from genesis. A peer whose chain does not have our tip -/// answers from the highest header of our locator on its chain, and a branch with more work takes -/// the place of ours. +/// Looks up `destination` if it is a name. Then dials the first of its addresses that takes the +/// TCP connect, in the order of `dial_order`, on the network of `chain`, and runs the handshake. +/// Returns the connection for the messages after it, and their `version`. The sync of the +/// connection extends `chain` from its tip, so the next connection with the same chain does not +/// get those headers again. A chain below the minimum work starts again from genesis. A peer +/// whose chain does not have our tip answers from the highest header of our locator on its chain, +/// and a branch with more work takes the place of ours. pub async fn handshake<'a>( - peers: &[std::net::SocketAddr], + destination: &Destination, chain: &'a mut crate::chain::Chain, ) -> Result<(Connection<'a>, crate::protocol::Version), HandshakeError> { - let (peer, stream) = connect_first(peers).await?; - handshake_stream(peer, stream, chain).await + let addresses = match destination { + Destination::Address(address) => vec![*address], + Destination::Name { name, port } => { + lookup(name, *port).await.map_err(HandshakeError::Lookup)? + } + }; + let (address, stream) = connect_first(&addresses).await?; + handshake_stream(address, stream, chain).await } -/// The TCP connect to the first of `peers` that takes it. Each try takes at most -/// `CONNECT_TIMEOUT`, so the length of `peers` bounds the time. When each try fails, the error is -/// the one of the last peer. +/// The addresses of `name` at `port`, as `dial_order` gives them. +async fn lookup(name: &Name, port: u16) -> Result, LookupError> { + let answers = tokio::net::lookup_host((name.0.as_str(), port)); + match tokio::time::timeout(LOOKUP_TIMEOUT, answers).await { + Ok(Ok(answers)) => dial_order(answers), + Ok(Err(error)) => Err(LookupError::Failed(error)), + Err(_elapsed) => Err(LookupError::Timeout), + } +} + +/// The `answers` of a lookup that name a peer, at most `ADDRESSES_COUNT_MAX`, in a random order. +/// So each dial can start on another address of a name that has many, such as a seed. The order +/// needs no secret, so it comes from the keys of `RandomState`. +fn dial_order( + answers: impl Iterator, +) -> Result, LookupError> { + // `0.0.0.0` and `::` name no peer, and the command line refuses them. Some resolvers give + // them for a name that they block. + let mut addresses: Vec = answers + .filter(|address| !address.ip().to_canonical().is_unspecified()) + .take(ADDRESSES_COUNT_MAX) + .collect(); + if addresses.is_empty() { + return Err(LookupError::Empty); + } + let random = std::hash::RandomState::new(); + addresses.sort_by_cached_key(|address| random.hash_one(address)); + Ok(addresses) +} + +/// The TCP connect to the first of `addresses` that takes it. Each try takes at most +/// `CONNECT_TIMEOUT`, and `ADDRESSES_COUNT_MAX` bounds the tries, so the time of a dial is +/// bounded. When each try fails, the error has the last address, its error, and the count. async fn connect_first( - peers: &[std::net::SocketAddr], + addresses: &[std::net::SocketAddr], ) -> Result<(std::net::SocketAddr, tokio::net::TcpStream), HandshakeError> { - let Some((&last, before)) = peers.split_last() else { - panic!("no peer to dial"); + // `dial_order` keeps at most `ADDRESSES_COUNT_MAX`, and gives no empty list. + assert!( + addresses.len() <= ADDRESSES_COUNT_MAX, + "{}", + addresses.len() + ); + let Some((&last, before)) = addresses.split_last() else { + panic!("no address to dial"); }; - for &peer in before { - if let Ok(stream) = connect(peer).await { - return Ok((peer, stream)); + for &address in before { + if let Ok(stream) = connect(address).await { + return Ok((address, stream)); } } - connect(last).await.map(|stream| (last, stream)) + match connect(last).await { + Ok(stream) => Ok((last, stream)), + Err(error) => Err(HandshakeError::Connect { + address: last, + addresses_count: addresses.len(), + error, + }), + } } -/// The TCP connect to `peer`, within `CONNECT_TIMEOUT`. -async fn connect(peer: std::net::SocketAddr) -> Result { - match tokio::time::timeout(CONNECT_TIMEOUT, tokio::net::TcpStream::connect(peer)).await { +/// The TCP connect to `address`, within `CONNECT_TIMEOUT`. +async fn connect(address: std::net::SocketAddr) -> Result { + match tokio::time::timeout(CONNECT_TIMEOUT, tokio::net::TcpStream::connect(address)).await { Ok(Ok(stream)) => Ok(stream), - Ok(Err(error)) => Err(HandshakeError::Connect(error)), - Err(_elapsed) => Err(HandshakeError::ConnectTimeout), + Ok(Err(error)) => Err(ConnectError::Io(error)), + Err(_elapsed) => Err(ConnectError::Timeout), } } /// The handshake on a connected `stream`, within `HANDSHAKE_TIMEOUT`. async fn handshake_stream( - peer: std::net::SocketAddr, + address: std::net::SocketAddr, stream: tokio::net::TcpStream, chain: &mut crate::chain::Chain, ) -> Result<(Connection<'_>, crate::protocol::Version), HandshakeError> { - let exchange = handshake_stream_exchange(peer, stream, chain); + let exchange = handshake_stream_exchange(address, stream, chain); match tokio::time::timeout(HANDSHAKE_TIMEOUT, exchange).await { Ok(result) => result, Err(_elapsed) => Err(HandshakeError::HandshakeTimeout), @@ -285,7 +488,8 @@ async fn handshake_stream_exchange( } impl<'a> Connection<'a> { - /// The address of the peer: of the peers that `handshake` got, the one that took the connect. + /// The address of the peer: of the addresses of the destination, the one that took the + /// connect. pub fn address(&self) -> std::net::SocketAddr { self.address } @@ -860,7 +1064,10 @@ mod tests { verack }); - let result = block_on(super::handshake(&[peer], &mut chain)); + let result = block_on(super::handshake( + &super::Destination::Address(peer), + &mut chain, + )); let verack = peer_thread.join().unwrap(); assert_eq!(verack, crate::fixtures::hex(crate::fixtures::VERACK_FRAME)); assert!(result.is_ok(), "{result:?}"); @@ -889,7 +1096,10 @@ mod tests { i64::try_from(elapsed.as_secs()).unwrap() }; let before = seconds(); - let _closed = block_on(super::handshake(&[peer], &mut chain)); + let _closed = block_on(super::handshake( + &super::Destination::Address(peer), + &mut chain, + )); let after = seconds(); let message = peer_thread.join().unwrap(); assert_eq!(message.msg_type(), crate::protocol::VERSION); @@ -943,7 +1153,10 @@ mod tests { }); let (result, elapsed) = block_on(async { - let (connection, _theirs) = super::handshake(&[peer], &mut chain).await.unwrap(); + let (connection, _theirs) = + super::handshake(&super::Destination::Address(peer), &mut chain) + .await + .unwrap(); tokio::time::pause(); let start = tokio::time::Instant::now(); let result = connection.sync().await; @@ -1000,7 +1213,10 @@ mod tests { }); let result = block_on(async { - let (connection, _theirs) = super::handshake(&[peer], &mut chain).await.unwrap(); + let (connection, _theirs) = + super::handshake(&super::Destination::Address(peer), &mut chain) + .await + .unwrap(); connection.sync().await }); peer_thread.join().unwrap(); @@ -1059,7 +1275,10 @@ mod tests { }); let result = block_on(async { - let (connection, _theirs) = super::handshake(&[peer], &mut chain).await.unwrap(); + let (connection, _theirs) = + super::handshake(&super::Destination::Address(peer), &mut chain) + .await + .unwrap(); connection.sync().await }); let expected = [ @@ -1103,7 +1322,10 @@ mod tests { }); let (error, elapsed) = block_on(async { - let (connection, _theirs) = super::handshake(&[peer], &mut chain).await.unwrap(); + let (connection, _theirs) = + super::handshake(&super::Destination::Address(peer), &mut chain) + .await + .unwrap(); let start = tokio::time::Instant::now(); let (synced, _tip) = connection.sync().await.unwrap(); tokio::time::pause(); @@ -1158,7 +1380,10 @@ mod tests { }); let (synced_tip, next_tip) = block_on(async { - let (connection, _theirs) = super::handshake(&[peer], &mut chain).await.unwrap(); + let (connection, _theirs) = + super::handshake(&super::Destination::Address(peer), &mut chain) + .await + .unwrap(); let (synced, synced_tip) = connection.sync().await.unwrap(); let (_synced, next_tip) = synced.next_tip().await.unwrap(); (synced_tip, next_tip) @@ -1200,7 +1425,10 @@ mod tests { }); let (error, elapsed) = block_on(async { - let (connection, _theirs) = super::handshake(&[peer], &mut chain).await.unwrap(); + let (connection, _theirs) = + super::handshake(&super::Destination::Address(peer), &mut chain) + .await + .unwrap(); let start = tokio::time::Instant::now(); let (synced, _tip) = connection.sync().await.unwrap(); tokio::time::pause(); @@ -1237,7 +1465,10 @@ mod tests { let peer_thread = std::thread::spawn(move || accept_handshake(&listener)); let (result, elapsed) = block_on(async { - let (connection, _theirs) = super::handshake(&[peer], &mut chain).await.unwrap(); + let (connection, _theirs) = + super::handshake(&super::Destination::Address(peer), &mut chain) + .await + .unwrap(); // The peer thread ends when it has sent its `verack`, so this wait blocks nothing. // The stream stays open, and nothing reads it. let _stream = peer_thread.join().unwrap(); @@ -1279,7 +1510,10 @@ mod tests { stream.write_all(&frame[..frame.len() - 1]).unwrap(); }); - let result = block_on(super::handshake(&[peer], &mut chain)); + let result = block_on(super::handshake( + &super::Destination::Address(peer), + &mut chain, + )); peer_thread.join().unwrap(); assert!( matches!(result, Err(super::HandshakeError::Closed)), @@ -1358,7 +1592,10 @@ mod tests { }); let result = block_on(async { - let (connection, _theirs) = super::handshake(&[peer], &mut chain).await.unwrap(); + let (connection, _theirs) = + super::handshake(&super::Destination::Address(peer), &mut chain) + .await + .unwrap(); connection.sync().await }); let pong = peer_thread.join().unwrap(); @@ -1380,19 +1617,30 @@ mod tests { .unwrap() .local_addr() .unwrap(); - let result = block_on(super::handshake(&[peer], &mut chain)); - assert!( - matches!( - result, - Err(super::HandshakeError::Connect(ref error)) - if error.kind() == std::io::ErrorKind::ConnectionRefused - ), - "{result:?}" - ); + let result = block_on(super::handshake( + &super::Destination::Address(peer), + &mut chain, + )); + let Err(error) = result else { + panic!("{result:?}"); + }; + let super::HandshakeError::Connect { + address, + addresses_count, + error: super::ConnectError::Io(io), + } = &error + else { + panic!("{error:?}"); + }; + assert_eq!(io.kind(), std::io::ErrorKind::ConnectionRefused); + assert_eq!(*address, peer); + assert_eq!(*addresses_count, 1); + let text = error.to_string(); + assert!(text.starts_with(&format!("connect to {peer}: ")), "{text}"); } #[test] - fn connect_takes_the_first_peer_that_takes_it() { + fn connect_takes_the_first_address_that_takes_it() { let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let listening = listener.local_addr().unwrap(); // Nothing listens on a port that was bound and then freed. The listener is open while @@ -1401,12 +1649,88 @@ mod tests { .unwrap() .local_addr() .unwrap(); - for peers in [[refused, listening], [listening, refused]] { - let (peer, _stream) = block_on(super::connect_first(&peers)).unwrap(); - assert_eq!(peer, listening, "{peers:?}"); + for addresses in [[refused, listening], [listening, refused]] { + let (address, _stream) = block_on(super::connect_first(&addresses)).unwrap(); + assert_eq!(address, listening, "{addresses:?}"); } } + #[test] + fn connect_to_no_address_gives_the_last_one_and_the_count() { + // Both listeners are open while the binds pick the ports, so the two ports differ. + // Nothing listens on them after the drop. + let first = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let last = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addresses = [first.local_addr().unwrap(), last.local_addr().unwrap()]; + drop((first, last)); + + let result = block_on(super::connect_first(&addresses)); + let Err(error) = result else { + panic!("{result:?}"); + }; + let super::HandshakeError::Connect { + address, + addresses_count, + error: super::ConnectError::Io(_), + } = &error + else { + panic!("{error:?}"); + }; + assert_eq!(*address, addresses[1]); + assert_eq!(*addresses_count, 2); + let text = error.to_string(); + let expected = format!("connect to {}, the last of 2 addresses: ", addresses[1]); + assert!(text.starts_with(&expected), "{text}"); + } + + #[test] + fn dial_order_drops_the_answers_that_name_no_peer_and_keeps_at_most_the_count_max() { + let unspecified = [ + std::net::SocketAddr::from(([0, 0, 0, 0], 1)), + std::net::SocketAddr::from((std::net::Ipv6Addr::UNSPECIFIED, 1)), + std::net::SocketAddr::from((std::net::Ipv4Addr::UNSPECIFIED.to_ipv6_mapped(), 1)), + ]; + let result = super::dial_order(unspecified.into_iter()); + assert!( + matches!(result, Err(super::LookupError::Empty)), + "{result:?}" + ); + + // One more than the count max, after the unspecified ones. Each port is new, so the + // ones that it keeps are the first ones. + let answers: Vec = (1..=super::ADDRESSES_COUNT_MAX + 1) + .map(|port| std::net::SocketAddr::from(([127, 0, 0, 1], u16::try_from(port).unwrap()))) + .collect(); + let mut kept = + super::dial_order(unspecified.into_iter().chain(answers.iter().copied())).unwrap(); + kept.sort_unstable(); + assert_eq!(kept, answers[..super::ADDRESSES_COUNT_MAX]); + } + + // The resolver of the OS reads `localhost` from its hosts file, with no name server. + #[test] + fn lookup_gives_the_addresses_of_a_name_with_the_port() { + let name = super::Name::new("localhost").unwrap(); + let addresses = block_on(super::lookup(&name, 1)).unwrap(); + assert!(!addresses.is_empty()); + for address in addresses { + assert!(address.ip().is_loopback(), "{address}"); + assert_eq!(address.port(), 1, "{address}"); + } + } + + #[test] + fn longest_destination_has_the_length_max() { + let label = "a".repeat(super::LABEL_LENGTH_MAX); + let labels = [label.as_str(); 4].join("."); + let longest = format!("{}.", &labels[..super::NAME_LENGTH_MAX]); + let destination = super::Destination::Name { + name: super::Name::new(&longest).unwrap(), + port: u16::MAX, + }; + assert_eq!(destination.to_string().len(), super::DESTINATION_LENGTH_MAX); + } + #[test] fn each_salt_word_is_new() { // A fixed salt, or one that reads a word twice, passes each other test, and a peer that diff --git a/tests/bitcoind.rs b/tests/bitcoind.rs index 85e39a4..8891f5f 100644 --- a/tests/bitcoind.rs +++ b/tests/bitcoind.rs @@ -167,7 +167,10 @@ fn handshake_with_bitcoind_returns_its_version() { .unwrap(); let mut chain = elo::chain::Chain::new(elo::chainparams::Network::Regtest); let (_connection, version) = runtime - .block_on(elo::net::handshake(&[bitcoind.peer], &mut chain)) + .block_on(elo::net::handshake( + &elo::net::Destination::Address(bitcoind.peer), + &mut chain, + )) .unwrap(); assert_eq!(version.version(), 70016); From 229a1b547b8fafbae7b5457072c564bd54cae630 Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Sat, 14 Nov 2026 11:12:47 -0300 Subject: [PATCH 3/6] refactor: make each address that elo dials name a peer by its type, with `net::PeerAddress` and a port that is not 0 (#44) - `net::PeerAddress` is a `SocketAddr` with a port that is not 0, and an IP that is not `0.0.0.0` or `::`. A connect to those reaches this host. Only `PeerAddress::new` makes one. - `Destination::Address` holds a `PeerAddress`. `Destination::Name` has a `NonZeroU16` port, and `Network::default_port` gives one. - `main::parse` loses its two checks of the port and the IP: `PeerAddress::new` and the parse of a `NonZeroU16` refuse them. - `dial_order` keeps the answers that `PeerAddress::new` takes, so it also refuses port 0. Before, it refused only the IP. - `connect_first` and `connect` take `PeerAddress`, so each dial goes to an address that names a peer, also from a writer that does not use `parse`, such as the seeds of the next slice. --- src/chainparams.rs | 16 +++-- src/logging.rs | 4 +- src/main.rs | 25 ++++---- src/net.rs | 151 ++++++++++++++++++++++++--------------------- tests/bitcoind.rs | 2 +- 5 files changed, 108 insertions(+), 90 deletions(-) diff --git a/src/chainparams.rs b/src/chainparams.rs index 446bb1d..e28219a 100644 --- a/src/chainparams.rs +++ b/src/chainparams.rs @@ -63,6 +63,12 @@ const CHAIN_WORK_MIN_SIGNET: [u8; 32] = [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x46, 0x3e, 0xa0, 0xa4, 0xb8, ]; +// `NonZeroU16::new` runs at compile time here, so a port of 0 does not build. +const PORT_MAINNET: std::num::NonZeroU16 = std::num::NonZeroU16::new(8333).expect("not 0"); +const PORT_TESTNET4: std::num::NonZeroU16 = std::num::NonZeroU16::new(48333).expect("not 0"); +const PORT_SIGNET: std::num::NonZeroU16 = std::num::NonZeroU16::new(38333).expect("not 0"); +const PORT_REGTEST: std::num::NonZeroU16 = std::num::NonZeroU16::new(18444).expect("not 0"); + impl Network { /// The bytes that start every message. pub(crate) const fn magic(self) -> [u8; MAGIC_SIZE] { @@ -75,12 +81,12 @@ impl Network { } /// The port that a node of the network listens on. - pub const fn default_port(self) -> u16 { + pub const fn default_port(self) -> std::num::NonZeroU16 { match self { - Network::Mainnet => 8333, - Network::Testnet4 => 48333, - Network::Signet => 38333, - Network::Regtest => 18444, + Network::Mainnet => PORT_MAINNET, + Network::Testnet4 => PORT_TESTNET4, + Network::Signet => PORT_SIGNET, + Network::Regtest => PORT_REGTEST, } } diff --git a/src/logging.rs b/src/logging.rs index e096211..65ace40 100644 --- a/src/logging.rs +++ b/src/logging.rs @@ -306,7 +306,9 @@ mod tests { ), ( super::Event::End { - peer: &crate::net::Destination::Address(PEER), + peer: &crate::net::Destination::Address( + crate::net::PeerAddress::new(PEER).unwrap(), + ), reason: &"the peer closed the connection", wait: std::time::Duration::from_secs(5), }, diff --git a/src/main.rs b/src/main.rs index 713cf33..37a09ac 100644 --- a/src/main.rs +++ b/src/main.rs @@ -302,18 +302,13 @@ fn parse( let peer = peer.to_str()?; let destination = if let Some(address) = address(peer, network.default_port()) { // Port 0, `0.0.0.0`, `[::]` and `[::ffff:0.0.0.0]` name no peer. - if address.port() == 0 || address.ip().to_canonical().is_unspecified() { - return None; - } - elo::net::Destination::Address(address) + elo::net::Destination::Address(elo::net::PeerAddress::new(address)?) } else { + // The parse of a `NonZeroU16` refuses port 0. let (host, port) = match peer.split_once(':') { Some((host, port)) => (host, port.parse().ok()?), None => (peer, network.default_port()), }; - if port == 0 { - return None; - } elo::net::Destination::Name { name: elo::net::Name::new(host)?, port, @@ -323,7 +318,7 @@ fn parse( } /// `peer` as an IP address with an optional port, or `None` if it is no IP address. -fn address(peer: &str, default_port: u16) -> Option { +fn address(peer: &str, default_port: std::num::NonZeroU16) -> Option { if let Ok(address) = peer.parse() { return Some(address); } @@ -331,7 +326,7 @@ fn address(peer: &str, default_port: u16) -> Option { Some(ip) => std::net::IpAddr::V6(ip.parse().ok()?), None => std::net::IpAddr::V4(peer.parse().ok()?), }; - Some(std::net::SocketAddr::from((ip, default_port))) + Some(std::net::SocketAddr::from((ip, default_port.get()))) } #[cfg(test)] @@ -391,7 +386,8 @@ mod tests { ("regtest", elo::chainparams::Network::Regtest, 18444), ] { let address = std::net::SocketAddr::from(([127, 0, 0, 1], port)); - let destination = elo::net::Destination::Address(address); + let destination = + elo::net::Destination::Address(elo::net::PeerAddress::new(address).unwrap()); assert_eq!( parse(&[name, "127.0.0.1"]), Some((network, destination)), @@ -399,7 +395,7 @@ mod tests { ); let destination = elo::net::Destination::Name { name: elo::net::Name::new("localhost").unwrap(), - port, + port: std::num::NonZeroU16::new(port).unwrap(), }; assert_eq!( parse(&[name, "localhost"]), @@ -412,11 +408,14 @@ mod tests { #[test] fn peer_is_an_ip_literal_or_a_name_with_an_optional_port() { let localhost_v6 = std::net::Ipv6Addr::LOCALHOST; - let address = |address| Some(elo::net::Destination::Address(address)); + let address = |address| { + let address = elo::net::PeerAddress::new(address).unwrap(); + Some(elo::net::Destination::Address(address)) + }; let name = |host: &str, port| { Some(elo::net::Destination::Name { name: elo::net::Name::new(host).unwrap(), - port, + port: std::num::NonZeroU16::new(port).unwrap(), }) }; let label = "a".repeat(63); diff --git a/src/net.rs b/src/net.rs index ce917da..2aa407e 100644 --- a/src/net.rs +++ b/src/net.rs @@ -40,20 +40,40 @@ pub(crate) const DESTINATION_LENGTH_MAX: usize = NAME_LENGTH_MAX + ".".len() + " #[derive(Debug, PartialEq, Eq)] pub enum Destination { /// An IP address, which `handshake` dials with no lookup. - Address(std::net::SocketAddr), + Address(PeerAddress), /// A name, which `handshake` looks up before each dial. - Name { name: Name, port: u16 }, + Name { + name: Name, + port: std::num::NonZeroU16, + }, } impl std::fmt::Display for Destination { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Destination::Address(address) => write!(f, "{address}"), + Destination::Address(address) => write!(f, "{}", address.0), Destination::Name { name, port } => write!(f, "{name}:{port}"), } } } +/// An address that names a peer: its port is not 0, and its IP is not `0.0.0.0` or `::`. A +/// connect to those reaches this host. Only `PeerAddress::new` makes one, so each address that +/// `handshake` dials names a peer. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct PeerAddress(std::net::SocketAddr); + +impl PeerAddress { + /// `address` as the address of a peer, or `None` if it names no peer. An IPv4 address in + /// IPv6, such as `[::ffff:0.0.0.0]`, is checked as the IPv4 address. + pub fn new(address: std::net::SocketAddr) -> Option { + if address.port() == 0 || address.ip().to_canonical().is_unspecified() { + return None; + } + Some(PeerAddress(address)) + } +} + /// The name of a host. Only `Name::new` makes one, so each name has the form that it checks. #[derive(Debug, PartialEq, Eq)] pub struct Name(String); @@ -354,8 +374,8 @@ pub async fn handshake<'a>( } /// The addresses of `name` at `port`, as `dial_order` gives them. -async fn lookup(name: &Name, port: u16) -> Result, LookupError> { - let answers = tokio::net::lookup_host((name.0.as_str(), port)); +async fn lookup(name: &Name, port: std::num::NonZeroU16) -> Result, LookupError> { + let answers = tokio::net::lookup_host((name.0.as_str(), port.get())); match tokio::time::timeout(LOOKUP_TIMEOUT, answers).await { Ok(Ok(answers)) => dial_order(answers), Ok(Err(error)) => Err(LookupError::Failed(error)), @@ -368,11 +388,10 @@ async fn lookup(name: &Name, port: u16) -> Result, Loo /// needs no secret, so it comes from the keys of `RandomState`. fn dial_order( answers: impl Iterator, -) -> Result, LookupError> { - // `0.0.0.0` and `::` name no peer, and the command line refuses them. Some resolvers give - // them for a name that they block. - let mut addresses: Vec = answers - .filter(|address| !address.ip().to_canonical().is_unspecified()) +) -> Result, LookupError> { + // Some resolvers give `0.0.0.0` or `::` for a name that they block. + let mut addresses: Vec = answers + .filter_map(PeerAddress::new) .take(ADDRESSES_COUNT_MAX) .collect(); if addresses.is_empty() { @@ -387,7 +406,7 @@ fn dial_order( /// `CONNECT_TIMEOUT`, and `ADDRESSES_COUNT_MAX` bounds the tries, so the time of a dial is /// bounded. When each try fails, the error has the last address, its error, and the count. async fn connect_first( - addresses: &[std::net::SocketAddr], + addresses: &[PeerAddress], ) -> Result<(std::net::SocketAddr, tokio::net::TcpStream), HandshakeError> { // `dial_order` keeps at most `ADDRESSES_COUNT_MAX`, and gives no empty list. assert!( @@ -400,13 +419,13 @@ async fn connect_first( }; for &address in before { if let Ok(stream) = connect(address).await { - return Ok((address, stream)); + return Ok((address.0, stream)); } } match connect(last).await { - Ok(stream) => Ok((last, stream)), + Ok(stream) => Ok((last.0, stream)), Err(error) => Err(HandshakeError::Connect { - address: last, + address: last.0, addresses_count: addresses.len(), error, }), @@ -414,8 +433,9 @@ async fn connect_first( } /// The TCP connect to `address`, within `CONNECT_TIMEOUT`. -async fn connect(address: std::net::SocketAddr) -> Result { - match tokio::time::timeout(CONNECT_TIMEOUT, tokio::net::TcpStream::connect(address)).await { +async fn connect(address: PeerAddress) -> Result { + let connect = tokio::net::TcpStream::connect(address.0); + match tokio::time::timeout(CONNECT_TIMEOUT, connect).await { Ok(Ok(stream)) => Ok(stream), Ok(Err(error)) => Err(ConnectError::Io(error)), Err(_elapsed) => Err(ConnectError::Timeout), @@ -962,6 +982,15 @@ mod tests { .block_on(future) } + fn destination(peer: std::net::SocketAddr) -> super::Destination { + super::Destination::Address(super::PeerAddress::new(peer).unwrap()) + } + + fn peer_addresses(addresses: &[std::net::SocketAddr]) -> Vec { + let peer_address = |address| super::PeerAddress::new(address).unwrap(); + addresses.iter().copied().map(peer_address).collect() + } + /// Reads one frame on the peer's side of the socket. fn read_frame(stream: &mut std::net::TcpStream) -> Vec { read_frame_on(stream, crate::chainparams::Network::Regtest) @@ -1064,10 +1093,7 @@ mod tests { verack }); - let result = block_on(super::handshake( - &super::Destination::Address(peer), - &mut chain, - )); + let result = block_on(super::handshake(&destination(peer), &mut chain)); let verack = peer_thread.join().unwrap(); assert_eq!(verack, crate::fixtures::hex(crate::fixtures::VERACK_FRAME)); assert!(result.is_ok(), "{result:?}"); @@ -1096,10 +1122,7 @@ mod tests { i64::try_from(elapsed.as_secs()).unwrap() }; let before = seconds(); - let _closed = block_on(super::handshake( - &super::Destination::Address(peer), - &mut chain, - )); + let _closed = block_on(super::handshake(&destination(peer), &mut chain)); let after = seconds(); let message = peer_thread.join().unwrap(); assert_eq!(message.msg_type(), crate::protocol::VERSION); @@ -1153,10 +1176,9 @@ mod tests { }); let (result, elapsed) = block_on(async { - let (connection, _theirs) = - super::handshake(&super::Destination::Address(peer), &mut chain) - .await - .unwrap(); + let (connection, _theirs) = super::handshake(&destination(peer), &mut chain) + .await + .unwrap(); tokio::time::pause(); let start = tokio::time::Instant::now(); let result = connection.sync().await; @@ -1213,10 +1235,9 @@ mod tests { }); let result = block_on(async { - let (connection, _theirs) = - super::handshake(&super::Destination::Address(peer), &mut chain) - .await - .unwrap(); + let (connection, _theirs) = super::handshake(&destination(peer), &mut chain) + .await + .unwrap(); connection.sync().await }); peer_thread.join().unwrap(); @@ -1275,10 +1296,9 @@ mod tests { }); let result = block_on(async { - let (connection, _theirs) = - super::handshake(&super::Destination::Address(peer), &mut chain) - .await - .unwrap(); + let (connection, _theirs) = super::handshake(&destination(peer), &mut chain) + .await + .unwrap(); connection.sync().await }); let expected = [ @@ -1322,10 +1342,9 @@ mod tests { }); let (error, elapsed) = block_on(async { - let (connection, _theirs) = - super::handshake(&super::Destination::Address(peer), &mut chain) - .await - .unwrap(); + let (connection, _theirs) = super::handshake(&destination(peer), &mut chain) + .await + .unwrap(); let start = tokio::time::Instant::now(); let (synced, _tip) = connection.sync().await.unwrap(); tokio::time::pause(); @@ -1380,10 +1399,9 @@ mod tests { }); let (synced_tip, next_tip) = block_on(async { - let (connection, _theirs) = - super::handshake(&super::Destination::Address(peer), &mut chain) - .await - .unwrap(); + let (connection, _theirs) = super::handshake(&destination(peer), &mut chain) + .await + .unwrap(); let (synced, synced_tip) = connection.sync().await.unwrap(); let (_synced, next_tip) = synced.next_tip().await.unwrap(); (synced_tip, next_tip) @@ -1425,10 +1443,9 @@ mod tests { }); let (error, elapsed) = block_on(async { - let (connection, _theirs) = - super::handshake(&super::Destination::Address(peer), &mut chain) - .await - .unwrap(); + let (connection, _theirs) = super::handshake(&destination(peer), &mut chain) + .await + .unwrap(); let start = tokio::time::Instant::now(); let (synced, _tip) = connection.sync().await.unwrap(); tokio::time::pause(); @@ -1465,10 +1482,9 @@ mod tests { let peer_thread = std::thread::spawn(move || accept_handshake(&listener)); let (result, elapsed) = block_on(async { - let (connection, _theirs) = - super::handshake(&super::Destination::Address(peer), &mut chain) - .await - .unwrap(); + let (connection, _theirs) = super::handshake(&destination(peer), &mut chain) + .await + .unwrap(); // The peer thread ends when it has sent its `verack`, so this wait blocks nothing. // The stream stays open, and nothing reads it. let _stream = peer_thread.join().unwrap(); @@ -1510,10 +1526,7 @@ mod tests { stream.write_all(&frame[..frame.len() - 1]).unwrap(); }); - let result = block_on(super::handshake( - &super::Destination::Address(peer), - &mut chain, - )); + let result = block_on(super::handshake(&destination(peer), &mut chain)); peer_thread.join().unwrap(); assert!( matches!(result, Err(super::HandshakeError::Closed)), @@ -1592,10 +1605,9 @@ mod tests { }); let result = block_on(async { - let (connection, _theirs) = - super::handshake(&super::Destination::Address(peer), &mut chain) - .await - .unwrap(); + let (connection, _theirs) = super::handshake(&destination(peer), &mut chain) + .await + .unwrap(); connection.sync().await }); let pong = peer_thread.join().unwrap(); @@ -1617,10 +1629,7 @@ mod tests { .unwrap() .local_addr() .unwrap(); - let result = block_on(super::handshake( - &super::Destination::Address(peer), - &mut chain, - )); + let result = block_on(super::handshake(&destination(peer), &mut chain)); let Err(error) = result else { panic!("{result:?}"); }; @@ -1650,6 +1659,7 @@ mod tests { .local_addr() .unwrap(); for addresses in [[refused, listening], [listening, refused]] { + let addresses = peer_addresses(&addresses); let (address, _stream) = block_on(super::connect_first(&addresses)).unwrap(); assert_eq!(address, listening, "{addresses:?}"); } @@ -1664,7 +1674,7 @@ mod tests { let addresses = [first.local_addr().unwrap(), last.local_addr().unwrap()]; drop((first, last)); - let result = block_on(super::connect_first(&addresses)); + let result = block_on(super::connect_first(&peer_addresses(&addresses))); let Err(error) = result else { panic!("{result:?}"); }; @@ -1689,6 +1699,7 @@ mod tests { std::net::SocketAddr::from(([0, 0, 0, 0], 1)), std::net::SocketAddr::from((std::net::Ipv6Addr::UNSPECIFIED, 1)), std::net::SocketAddr::from((std::net::Ipv4Addr::UNSPECIFIED.to_ipv6_mapped(), 1)), + std::net::SocketAddr::from(([127, 0, 0, 1], 0)), ]; let result = super::dial_order(unspecified.into_iter()); assert!( @@ -1703,17 +1714,17 @@ mod tests { .collect(); let mut kept = super::dial_order(unspecified.into_iter().chain(answers.iter().copied())).unwrap(); - kept.sort_unstable(); - assert_eq!(kept, answers[..super::ADDRESSES_COUNT_MAX]); + kept.sort_unstable_by_key(|address| address.0); + assert_eq!(kept, peer_addresses(&answers[..super::ADDRESSES_COUNT_MAX])); } // The resolver of the OS reads `localhost` from its hosts file, with no name server. #[test] fn lookup_gives_the_addresses_of_a_name_with_the_port() { let name = super::Name::new("localhost").unwrap(); - let addresses = block_on(super::lookup(&name, 1)).unwrap(); + let addresses = block_on(super::lookup(&name, std::num::NonZeroU16::MIN)).unwrap(); assert!(!addresses.is_empty()); - for address in addresses { + for super::PeerAddress(address) in addresses { assert!(address.ip().is_loopback(), "{address}"); assert_eq!(address.port(), 1, "{address}"); } @@ -1726,7 +1737,7 @@ mod tests { let longest = format!("{}.", &labels[..super::NAME_LENGTH_MAX]); let destination = super::Destination::Name { name: super::Name::new(&longest).unwrap(), - port: u16::MAX, + port: std::num::NonZeroU16::MAX, }; assert_eq!(destination.to_string().len(), super::DESTINATION_LENGTH_MAX); } diff --git a/tests/bitcoind.rs b/tests/bitcoind.rs index 8891f5f..4e4668e 100644 --- a/tests/bitcoind.rs +++ b/tests/bitcoind.rs @@ -168,7 +168,7 @@ fn handshake_with_bitcoind_returns_its_version() { let mut chain = elo::chain::Chain::new(elo::chainparams::Network::Regtest); let (_connection, version) = runtime .block_on(elo::net::handshake( - &elo::net::Destination::Address(bitcoind.peer), + &elo::net::Destination::Address(elo::net::PeerAddress::new(bitcoind.peer).unwrap()), &mut chain, )) .unwrap(); From 1e46612e3243a5c264936cdddfdc1d49b6377edc Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Sat, 14 Nov 2026 11:13:39 -0300 Subject: [PATCH 4/6] refactor: give each dial at least one address by its type, with `Addresses { before, last }` (#44) - `net::Addresses` holds the addresses of one dial: `before`, then `last`. `connect_first` takes it, so its `panic!` for no address goes away. - `dial_order` takes `last` with a `pop`. No address is `LookupError::Empty` there, in place of the check of an empty list. - `HandshakeError::Connect.addresses_count` is `before.len() + 1`, so it is at least 1. - `connect_first` still asserts the bound of `ADDRESSES_COUNT_MAX`, on `before`. --- src/net.rs | 73 +++++++++++++++++++++++++++++++++--------------------- 1 file changed, 45 insertions(+), 28 deletions(-) diff --git a/src/net.rs b/src/net.rs index 2aa407e..593c08a 100644 --- a/src/net.rs +++ b/src/net.rs @@ -364,7 +364,10 @@ pub async fn handshake<'a>( chain: &'a mut crate::chain::Chain, ) -> Result<(Connection<'a>, crate::protocol::Version), HandshakeError> { let addresses = match destination { - Destination::Address(address) => vec![*address], + Destination::Address(address) => Addresses { + before: Vec::new(), + last: *address, + }, Destination::Name { name, port } => { lookup(name, *port).await.map_err(HandshakeError::Lookup)? } @@ -373,8 +376,16 @@ pub async fn handshake<'a>( handshake_stream(address, stream, chain).await } +/// The addresses that one dial tries, in order: each one of `before`, then `last`. So a dial has +/// at least one address, with no check. +#[derive(Debug)] +struct Addresses { + before: Vec, + last: PeerAddress, +} + /// The addresses of `name` at `port`, as `dial_order` gives them. -async fn lookup(name: &Name, port: std::num::NonZeroU16) -> Result, LookupError> { +async fn lookup(name: &Name, port: std::num::NonZeroU16) -> Result { let answers = tokio::net::lookup_host((name.0.as_str(), port.get())); match tokio::time::timeout(LOOKUP_TIMEOUT, answers).await { Ok(Ok(answers)) => dial_order(answers), @@ -388,45 +399,39 @@ async fn lookup(name: &Name, port: std::num::NonZeroU16) -> Result, -) -> Result, LookupError> { +) -> Result { // Some resolvers give `0.0.0.0` or `::` for a name that they block. - let mut addresses: Vec = answers + let mut before: Vec = answers .filter_map(PeerAddress::new) .take(ADDRESSES_COUNT_MAX) .collect(); - if addresses.is_empty() { - return Err(LookupError::Empty); - } let random = std::hash::RandomState::new(); - addresses.sort_by_cached_key(|address| random.hash_one(address)); - Ok(addresses) + before.sort_by_cached_key(|address| random.hash_one(address)); + let Some(last) = before.pop() else { + return Err(LookupError::Empty); + }; + Ok(Addresses { before, last }) } /// The TCP connect to the first of `addresses` that takes it. Each try takes at most /// `CONNECT_TIMEOUT`, and `ADDRESSES_COUNT_MAX` bounds the tries, so the time of a dial is /// bounded. When each try fails, the error has the last address, its error, and the count. async fn connect_first( - addresses: &[PeerAddress], + addresses: &Addresses, ) -> Result<(std::net::SocketAddr, tokio::net::TcpStream), HandshakeError> { - // `dial_order` keeps at most `ADDRESSES_COUNT_MAX`, and gives no empty list. - assert!( - addresses.len() <= ADDRESSES_COUNT_MAX, - "{}", - addresses.len() - ); - let Some((&last, before)) = addresses.split_last() else { - panic!("no address to dial"); - }; + let Addresses { before, last } = addresses; + // `dial_order` keeps at most `ADDRESSES_COUNT_MAX`, with `last`. + assert!(before.len() < ADDRESSES_COUNT_MAX, "{}", before.len()); for &address in before { if let Ok(stream) = connect(address).await { return Ok((address.0, stream)); } } - match connect(last).await { + match connect(*last).await { Ok(stream) => Ok((last.0, stream)), Err(error) => Err(HandshakeError::Connect { address: last.0, - addresses_count: addresses.len(), + addresses_count: before.len() + 1, error, }), } @@ -991,6 +996,20 @@ mod tests { addresses.iter().copied().map(peer_address).collect() } + /// `addresses` in their order, with the last one as `last`. + fn dial(addresses: &[std::net::SocketAddr]) -> super::Addresses { + let mut before = peer_addresses(addresses); + let last = before.pop().unwrap(); + super::Addresses { before, last } + } + + /// The addresses of a dial, in their order. + fn dialed(addresses: super::Addresses) -> Vec { + let super::Addresses { mut before, last } = addresses; + before.push(last); + before + } + /// Reads one frame on the peer's side of the socket. fn read_frame(stream: &mut std::net::TcpStream) -> Vec { read_frame_on(stream, crate::chainparams::Network::Regtest) @@ -1659,8 +1678,7 @@ mod tests { .local_addr() .unwrap(); for addresses in [[refused, listening], [listening, refused]] { - let addresses = peer_addresses(&addresses); - let (address, _stream) = block_on(super::connect_first(&addresses)).unwrap(); + let (address, _stream) = block_on(super::connect_first(&dial(&addresses))).unwrap(); assert_eq!(address, listening, "{addresses:?}"); } } @@ -1674,7 +1692,7 @@ mod tests { let addresses = [first.local_addr().unwrap(), last.local_addr().unwrap()]; drop((first, last)); - let result = block_on(super::connect_first(&peer_addresses(&addresses))); + let result = block_on(super::connect_first(&dial(&addresses))); let Err(error) = result else { panic!("{result:?}"); }; @@ -1712,8 +1730,8 @@ mod tests { let answers: Vec = (1..=super::ADDRESSES_COUNT_MAX + 1) .map(|port| std::net::SocketAddr::from(([127, 0, 0, 1], u16::try_from(port).unwrap()))) .collect(); - let mut kept = - super::dial_order(unspecified.into_iter().chain(answers.iter().copied())).unwrap(); + let kept = super::dial_order(unspecified.into_iter().chain(answers.iter().copied())); + let mut kept = dialed(kept.unwrap()); kept.sort_unstable_by_key(|address| address.0); assert_eq!(kept, peer_addresses(&answers[..super::ADDRESSES_COUNT_MAX])); } @@ -1723,8 +1741,7 @@ mod tests { fn lookup_gives_the_addresses_of_a_name_with_the_port() { let name = super::Name::new("localhost").unwrap(); let addresses = block_on(super::lookup(&name, std::num::NonZeroU16::MIN)).unwrap(); - assert!(!addresses.is_empty()); - for super::PeerAddress(address) in addresses { + for super::PeerAddress(address) in dialed(addresses) { assert!(address.ip().is_loopback(), "{address}"); assert_eq!(address.port(), 1, "{address}"); } From 3789d11f7d8192453aa5cabcf879204f5efbb450 Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Sat, 14 Nov 2026 11:14:11 -0300 Subject: [PATCH 5/6] fix: try each address of a lookup one time in a dial (#44) - `dial_order` drops an address that the lookup gives again, before the random order. A hosts file can have the same name and address on two lines, and a second try of a dead address costs up to the connect timeout of 5 s again. The count of `connect to
, the last of N addresses` also counted it two times. - The bound of 256 is on the answers before the drop, so it still bounds the work of the lookup. - Test: `dial_order_keeps_each_address_one_time`. --- src/net.rs | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/net.rs b/src/net.rs index 593c08a..639014a 100644 --- a/src/net.rs +++ b/src/net.rs @@ -394,9 +394,9 @@ async fn lookup(name: &Name, port: std::num::NonZeroU16) -> Result, ) -> Result { @@ -405,6 +405,10 @@ fn dial_order( .filter_map(PeerAddress::new) .take(ADDRESSES_COUNT_MAX) .collect(); + // A hosts file can have the same name and address on two lines. A second try of an address + // costs up to `CONNECT_TIMEOUT` again. + before.sort_unstable_by_key(|address| address.0); + before.dedup(); let random = std::hash::RandomState::new(); before.sort_by_cached_key(|address| random.hash_one(address)); let Some(last) = before.pop() else { @@ -1736,6 +1740,16 @@ mod tests { assert_eq!(kept, peer_addresses(&answers[..super::ADDRESSES_COUNT_MAX])); } + #[test] + fn dial_order_keeps_each_address_one_time() { + let first = std::net::SocketAddr::from(([127, 0, 0, 1], 1)); + let second = std::net::SocketAddr::from(([127, 0, 0, 1], 2)); + let addresses = super::dial_order([first, second, first, first].into_iter()).unwrap(); + let mut kept = dialed(addresses); + kept.sort_unstable_by_key(|address| address.0); + assert_eq!(kept, peer_addresses(&[first, second])); + } + // The resolver of the OS reads `localhost` from its hosts file, with no name server. #[test] fn lookup_gives_the_addresses_of_a_name_with_the_port() { From 33bdb71cd74325c024549208a54be35b73ec55a8 Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Sat, 14 Nov 2026 11:14:58 -0300 Subject: [PATCH 6/6] fix: give the destination of an `end` line its own key, so `peer` is always the address of a connection (#44) - The `end` line has `destination=`, in place of `peer=`. `Event::End.peer` is now `Event::End.destination`. - Before, `peer` was an address on the `version` and `tip` lines and the name on the `end` line. A log query that joins an `end` to its `version` by `peer` got the join right for an IP address and wrong for a name. - README: the `end` row and the example line. --- README.md | 4 ++-- src/logging.rs | 21 +++++++++++++-------- src/main.rs | 2 +- tests/bitcoind.rs | 4 ++-- 4 files changed, 18 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 2c550fa..87aac2f 100644 --- a/README.md +++ b/README.md @@ -74,7 +74,7 @@ container runtime, reads stdout and adds the time. elo sends nothing to a log se ```text level=info event=version peer=127.0.0.1:18444 version=70016 services=0000000000000c09 user_agent=/Satoshi:31.1.0/ start_height=0 relay=true level=info event=tip peer=127.0.0.1:18444 height=0 hash=0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206 work=0000000000000000000000000000000000000000000000000000000000000002 -level=warn event=end peer=127.0.0.1:18444 reason="the peer closed the connection" wait_ms=5000 +level=warn event=end destination=127.0.0.1:18444 reason="the peer closed the connection" wait_ms=5000 level=info event=stop signal=SIGTERM ``` @@ -82,7 +82,7 @@ level=info event=stop signal=SIGTERM | --- | --- | --- | | `version` | `info` | `peer` `version` `services` `user_agent` `start_height` `relay` | | `tip` | `info` | `peer` `height` `hash` `work` | -| `end` | `warn` | `peer` `reason` `wait_ms`: elo dials the peer again after `wait_ms`. `peer` is the peer of the command line, also a name | +| `end` | `warn` | `destination` `reason` `wait_ms`: elo dials `destination` again after `wait_ms`. `destination` is the peer of the command line, also a name. `peer` is always the address of a connection | | `exit` | `error` | `reason`: a fault of this host, and elo exits with 1 | | `stop` | `info` | `signal`: elo exits with 0 | | `panic` | `error` | `reason`: a bug, and elo exits with 101 | diff --git a/src/logging.rs b/src/logging.rs index 65ace40..95203e5 100644 --- a/src/logging.rs +++ b/src/logging.rs @@ -8,7 +8,7 @@ use std::fmt::Write; /// The most bytes of a value before its escapes. A longer value is cut, and ends with `...`. So /// a peer that sends a long string cannot make a long line. The longest destination of the -/// command line fits, so the `peer` of an `end` line is never cut. +/// command line fits, so the `destination` of an `end` line is never cut. const VALUE_LENGTH_MAX: usize = 260; const _: () = assert!(crate::net::DESTINATION_LENGTH_MAX <= VALUE_LENGTH_MAX); @@ -55,10 +55,11 @@ pub enum Event<'a> { peer: std::net::SocketAddr, tip: &'a crate::chain::Tip, }, - /// The connection to `peer` ended for `reason`, and elo dials it again after `wait`. `peer` is - /// the destination of the command line: an IP address, or a name that elo looks up again. + /// The connection to `destination` ended for `reason`, and elo dials it again after `wait`. + /// `destination` is the peer of the command line: an IP address, or a name that elo looks up + /// again. It has its own key, so `peer` is always the address of a connection. End { - peer: &'a crate::net::Destination, + destination: &'a crate::net::Destination, reason: &'a dyn std::fmt::Display, wait: std::time::Duration, }, @@ -116,8 +117,12 @@ impl Event<'_> { line.field("hash", tip.hash_display()); line.field("work", tip.work()); } - Event::End { peer, reason, wait } => { - line.field("peer", peer); + Event::End { + destination, + reason, + wait, + } => { + line.field("destination", destination); line.field("reason", reason); line.field("wait_ms", wait.as_millis()); } @@ -306,13 +311,13 @@ mod tests { ), ( super::Event::End { - peer: &crate::net::Destination::Address( + destination: &crate::net::Destination::Address( crate::net::PeerAddress::new(PEER).unwrap(), ), reason: &"the peer closed the connection", wait: std::time::Duration::from_secs(5), }, - "level=warn event=end peer=127.0.0.1:18444 \ + "level=warn event=end destination=127.0.0.1:18444 \ reason=\"the peer closed the connection\" wait_ms=5000", ), ( diff --git a/src/main.rs b/src/main.rs index 37a09ac..ba9dc6f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -82,7 +82,7 @@ async fn run( // The destination of the command line, and not the address of the connection: the next // dial looks up a name again. let logged = log(&elo::logging::Event::End { - peer: &destination, + destination: &destination, reason: &end, wait: RECONNECT_WAIT, }); diff --git a/tests/bitcoind.rs b/tests/bitcoind.rs index 4e4668e..0d75ca8 100644 --- a/tests/bitcoind.rs +++ b/tests/bitcoind.rs @@ -277,7 +277,7 @@ fn our_ping_gets_a_pong_from_bitcoind() { assert_eq!( end, format!( - "level=warn event=end peer={} reason=\"the peer closed the connection\" wait_ms=5000", + "level=warn event=end destination={} reason=\"the peer closed the connection\" wait_ms=5000", bitcoind.peer ) ); @@ -330,7 +330,7 @@ fn peer_with_a_name_gets_a_lookup_and_a_dial_to_its_address() { bitcoind.cli(&["-named", "disconnectnode", "nodeid=0"]); let end = elo.event("end", END_TIMEOUT); assert!( - end.starts_with(&format!("level=warn event=end peer={named} ")), + end.starts_with(&format!("level=warn event=end destination={named} ")), "{end}" ); }