Skip to content

Commit

Permalink
chore(clap): read address from user (#276)
Browse files Browse the repository at this point in the history
* parse address from user

* tests

* set default test port

* update readme
  • Loading branch information
sdaveas authored Feb 28, 2022
1 parent 018b60e commit 3f4fcd8
Show file tree
Hide file tree
Showing 7 changed files with 56 additions and 7 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ FLAGS:
-V, --version Prints version information

OPTIONS:
-a, --address <ip> [default: 0.0.0.0]
-d, --directory <directory> [env: TOFND_HOME=] [default: .tofnd]
-m, --mnemonic <mnemonic> [default: existing] [possible values: existing, create, import, export]
-p, --port <port> [default: 50051]]
Expand Down
16 changes: 16 additions & 0 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use anyhow::anyhow;
const DEFAULT_PATH_ROOT: &str = ".tofnd";
const TOFND_HOME_ENV_VAR: &str = "TOFND_HOME";
const DEFAULT_MNEMONIC_CMD: &str = "existing";
const DEFAULT_IP: &str = "0.0.0.0";
const DEFAULT_PORT: u16 = 50051;
const AVAILABLE_MNEMONIC_CMDS: [&str; 4] = ["existing", "create", "import", "export"];

Expand All @@ -19,6 +20,7 @@ use malicious::*;
// TODO: move to types.rs
#[derive(Clone, Debug)]
pub struct Config {
pub ip: String,
pub port: u16,
pub safe_keygen: bool,
pub mnemonic_cmd: Cmd,
Expand All @@ -30,6 +32,7 @@ pub struct Config {
impl Default for Config {
fn default() -> Self {
Config {
ip: DEFAULT_IP.to_string(),
port: DEFAULT_PORT,
safe_keygen: true,
mnemonic_cmd: Cmd::Existing,
Expand All @@ -43,11 +46,19 @@ impl Default for Config {

pub fn parse_args() -> TofndResult<Config> {
// need to use let to avoid dropping temporary value
let ip = &DEFAULT_IP.to_string();
let port = &DEFAULT_PORT.to_string();

let app = App::new("tofnd")
.about("A threshold signature scheme daemon")
.version(crate_version!())
.arg(
Arg::new("ip")
.long("address")
.short('a')
.required(false)
.default_value(ip),
)
.arg(
Arg::new("port")
.long("port")
Expand Down Expand Up @@ -110,6 +121,10 @@ pub fn parse_args() -> TofndResult<Config> {

let matches = app.get_matches();

let ip = matches
.value_of("ip")
.ok_or_else(|| anyhow!("ip value"))?
.to_string();
let port = matches
.value_of("port")
.ok_or_else(|| anyhow!("port value"))?
Expand All @@ -130,6 +145,7 @@ pub fn parse_args() -> TofndResult<Config> {
};

Ok(Config {
ip,
port,
safe_keygen,
mnemonic_cmd,
Expand Down
10 changes: 7 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ fn warn_for_unsafe_execution() {
#[tokio::main(flavor = "multi_thread")]
async fn main() -> TofndResult<()> {
let cfg = parse_args()?;
let socket_address = addr(&cfg.ip, cfg.port)?;

// immediately read an encryption password from stdin
let password = cfg.password_method.execute()?;
Expand All @@ -69,7 +70,7 @@ async fn main() -> TofndResult<()> {
let main_span = span!(Level::INFO, "main");
let _enter = main_span.enter();

let incoming = TcpListener::bind(addr(cfg.port)).await?;
let incoming = TcpListener::bind(socket_address).await?;
info!(
"tofnd listen addr {:?}, use ctrl+c to shutdown",
incoming.local_addr()?
Expand Down Expand Up @@ -101,8 +102,11 @@ async fn main() -> TofndResult<()> {
Ok(())
}

fn addr(port: u16) -> SocketAddr {
SocketAddr::from(([0, 0, 0, 0], port)) // ipv4
fn addr(ip: &str, port: u16) -> TofndResult<SocketAddr> {
let socket_addr = format!("{}:{}", ip, port);
socket_addr
.parse::<SocketAddr>()
.map_err(|err| anyhow::anyhow!(err))
}

// graceful shutdown https://hyper.rs/guides/server/graceful-shutdown/
Expand Down
11 changes: 9 additions & 2 deletions src/multisig/tests.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
use crate::{addr, encrypted_sled::get_test_password, kv_manager::KvManager};
use crate::{
addr,
encrypted_sled::get_test_password,
kv_manager::KvManager,
tests::{DEFAULT_TEST_IP, DEFAULT_TEST_PORT},
};
use tokio::{
self,
net::TcpListener,
Expand Down Expand Up @@ -38,7 +43,9 @@ async fn spin_test_service_and_client() -> (MultisigClient<Channel>, Sender<()>)
let service = MultisigServer::new(service);

// create incoming tcp server for service
let incoming = TcpListener::bind(addr(0)).await.unwrap(); // use port 0 and let the OS decide
let incoming = TcpListener::bind(addr(DEFAULT_TEST_IP, DEFAULT_TEST_PORT).unwrap())
.await
.unwrap();

// create shutdown channels
let (shutdown_sender, shutdown_receiver) = channel::<()>();
Expand Down
3 changes: 3 additions & 0 deletions src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ mod malicious;
use malicious::{MaliciousData, PartyMaliciousData};

mod mnemonic;
mod socket_address;

use crate::mnemonic::Cmd::{self, Create};
use proto::message_out::CriminalList;
Expand All @@ -47,6 +48,8 @@ lazy_static::lazy_static! {
}
const SLEEP_TIME: u64 = 1;
const MAX_TRIES: u32 = 3;
pub const DEFAULT_TEST_IP: &str = "0.0.0.0";
pub const DEFAULT_TEST_PORT: u16 = 0; // use port 0 and let the OS decide

struct TestCase {
uid_count: usize,
Expand Down
13 changes: 13 additions & 0 deletions src/tests/socket_address.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
//! socket address convertion tests
use crate::addr;

#[test]
fn test_ips() {
let valid_ips = ["0.0.0.0", "127.0.0.1"];
let invalid_ips = ["256.0.0.0"];
let ports = [0, 65535]; // no need to check for invalid ports because 0 <= u16 <= 65535

valid_ips.map(|a| ports.map(|p| assert!(addr(a, p).is_ok())));
invalid_ips.map(|a| ports.map(|p| assert!(addr(a, p).is_err())));
}
9 changes: 7 additions & 2 deletions src/tests/tofnd_party.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
// produces less friction in the code. Should implement a beeter solution soon.

use super::{
mock::SenderReceiver, Deliverer, GrpcKeygenResult, GrpcSignResult, InitParty, Party, MAX_TRIES,
mock::SenderReceiver, Deliverer, GrpcKeygenResult, GrpcSignResult, InitParty, Party,
DEFAULT_TEST_IP, DEFAULT_TEST_PORT, MAX_TRIES,
};
use crate::{
addr,
Expand Down Expand Up @@ -53,13 +54,17 @@ impl TofndParty {
// start server
let (server_shutdown_sender, shutdown_receiver) = oneshot::channel::<()>();

let incoming = TcpListener::bind(addr(0)).await.unwrap(); // use port 0 and let the OS decide
let incoming = TcpListener::bind(addr(DEFAULT_TEST_IP, DEFAULT_TEST_PORT).unwrap())
.await
.unwrap();
let server_addr = incoming.local_addr().unwrap();
let server_ip = server_addr.ip();
let server_port = server_addr.port();
info!("new party bound to port [{:?}]", server_port);

let cfg = Config {
mnemonic_cmd,
ip: server_ip.to_string(),
port: server_port,
safe_keygen: false,
tofnd_path: tofnd_path.to_string(),
Expand Down

0 comments on commit 3f4fcd8

Please sign in to comment.