Skip to content

Commit

Permalink
feat: Add support for both ip and hostname for peers
Browse files Browse the repository at this point in the history
It is convinent to be able to specify both IPs and hostnames as peers.
Especially, when you are building ephemeral testnets and want to specify
peers as

```
./snarkos start --peers "validator0:4130,client0:4130"
```

Where you can populate the `/etc/hosts` file with subnet hostnames.
  • Loading branch information
Raphexion committed Nov 8, 2024
1 parent 2cb5444 commit 21a4598
Showing 1 changed file with 51 additions and 6 deletions.
57 changes: 51 additions & 6 deletions cli/src/commands/start.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ use rand::{Rng, SeedableRng};
use rand_chacha::ChaChaRng;
use serde::{Deserialize, Serialize};
use std::{
net::SocketAddr,
net::{SocketAddr, ToSocketAddrs},
path::PathBuf,
sync::{Arc, atomic::AtomicBool},
};
Expand Down Expand Up @@ -228,11 +228,14 @@ impl Start {
false => Ok(self
.peers
.split(',')
.flat_map(|ip| match ip.parse::<SocketAddr>() {
Ok(ip) => Some(ip),
Err(e) => {
eprintln!("The IP supplied to --peers ('{ip}') is malformed: {e}");
None
.flat_map(|ip_or_hostname| {
let trimmed = ip_or_hostname.trim();
match trimmed.to_socket_addrs() {
Ok(mut addr) => addr.next(),
Err(e) => {
eprintln!("The IP supplied to --peers ('{trimmed}') is malformed: {e}");
None
}
}
})
.collect()),
Expand Down Expand Up @@ -1039,4 +1042,46 @@ mod tests {
panic!("Unexpected result of clap parsing!");
}
}

#[test]
fn parse_peers_when_ips() {
let arg_vec = vec!["snarkos", "start", "--peers", "127.0.0.1:3030,127.0.0.2:3030"];
let cli = CLI::parse_from(arg_vec);

if let Command::Start(start) = cli.command {
let peers = start.parse_trusted_peers();
assert!(peers.is_ok());
assert!(peers.unwrap().len() == 2, "Expected two peers");
} else {
panic!("Unexpected result of clap parsing!");
}
}

#[test]
fn parse_peers_when_hostnames() {
let arg_vec = vec!["snarkos", "start", "--peers", "www.example.com:4130,www.google.com:4130"];
let cli = CLI::parse_from(arg_vec);

if let Command::Start(start) = cli.command {
let peers = start.parse_trusted_peers();
assert!(peers.is_ok());
assert!(peers.unwrap().len() == 2, "Expected two peers");
} else {
panic!("Unexpected result of clap parsing!");
}
}

#[test]
fn parse_peers_when_mixed_and_with_whitespaces() {
let arg_vec = vec!["snarkos", "start", "--peers", " 127.0.0.1:3030, www.google.com:4130 "];
let cli = CLI::parse_from(arg_vec);

if let Command::Start(start) = cli.command {
let peers = start.parse_trusted_peers();
assert!(peers.is_ok());
assert!(peers.unwrap().len() == 2, "Expected two peers");
} else {
panic!("Unexpected result of clap parsing!");
}
}
}

0 comments on commit 21a4598

Please sign in to comment.