Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions crates/launcher/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,11 @@ pub async fn probe_daemon(addr: &str) -> bool {
use transferd_api::Empty;

let channel = match tonic::transport::Channel::from_shared(addr.to_owned()) {
Ok(e) => e
.connect_timeout(Duration::from_millis(300))
.connect()
.await,
Ok(e) => {
e.connect_timeout(Duration::from_millis(300))
.connect()
.await
}
Err(_) => return false,
};

Expand Down
48 changes: 25 additions & 23 deletions crates/launcher/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,23 @@
//! 6. Launch `transferd-ui`, forwarding the daemon address.
//! 7. When the UI exits, exit the launcher with the same status code.

use launcher_lib::{daemon_addr, probe_daemon, spawn_daemon, wait_for_daemon};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::Duration;
use launcher_lib::{daemon_addr, probe_daemon, spawn_daemon, wait_for_daemon};

const LOG_DIR: &str = "logs";
const LOG_DIR: &str = "logs";
const LOG_BASE: &str = "launcher_log";
const MAX_LOGS: u32 = 10;
const MAX_LOGS: u32 = 10;

/// Append `.exe` on Windows.
fn exe(name: &str) -> String {
if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() }
if cfg!(windows) {
format!("{name}.exe")
} else {
name.to_owned()
}
}

/// Shift existing log files and return the path for the new index-0 file.
Expand All @@ -45,14 +49,11 @@ fn rotate_logs(base: &Path) -> PathBuf {
/// Initialise env_logger writing to a rotated file in `base/logs/`.
fn init_logging(base: &Path) {
let log_path = rotate_logs(base);
let file = fs::File::create(&log_path)
.expect("failed to create launcher log file");
env_logger::Builder::from_env(
env_logger::Env::default().default_filter_or("info"),
)
.format_timestamp_millis()
.target(env_logger::Target::Pipe(Box::new(file)))
.init();
let file = fs::File::create(&log_path).expect("failed to create launcher log file");
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info"))
.format_timestamp_millis()
.target(env_logger::Target::Pipe(Box::new(file)))
.init();
log::info!("launcher started — log: {}", log_path.display());
}

Expand All @@ -68,11 +69,15 @@ fn sibling_binary(name: &str) -> PathBuf {
.and_then(|p| p.parent().map(PathBuf::from))
.unwrap_or_else(|| PathBuf::from("."));

let in_bin = exe_dir.join("bin").join(exe(name));
let in_bin = exe_dir.join("bin").join(exe(name));
let in_root = exe_dir.join(exe(name));

if in_bin.exists() { return in_bin; }
if in_root.exists() { return in_root; }
if in_bin.exists() {
return in_bin;
}
if in_root.exists() {
return in_root;
}

launcher_lib::find_binary(name).unwrap_or_else(|| {
log::error!("'{name}' not found in bin/, next to launcher, or on PATH");
Expand All @@ -94,7 +99,7 @@ async fn main() {
log::info!("daemon address: {addr}");

let daemon_bin = sibling_binary("transferd");
let ui_bin = sibling_binary("transferd-ui");
let ui_bin = sibling_binary("transferd-ui");

// ── Step 1: ensure daemon is running ─────────────────────────────────────
if !probe_daemon(&addr).await {
Expand Down Expand Up @@ -123,13 +128,10 @@ async fn main() {
if let Some(token) = transferd_api::auth::resolve_token() {
cmd.env("TRANSFERD_TOKEN", token);
}
let status = cmd
.stdin(Stdio::null())
.status()
.unwrap_or_else(|e| {
log::error!("could not launch UI: {e}");
std::process::exit(1);
});
let status = cmd.stdin(Stdio::null()).status().unwrap_or_else(|e| {
log::error!("could not launch UI: {e}");
std::process::exit(1);
});

log::info!("UI exited with status: {status}");
std::process::exit(status.code().unwrap_or(0));
Expand Down
25 changes: 19 additions & 6 deletions crates/launcher/tests/launcher_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
//! Tests that require a live daemon start an in-process tonic server on a
//! random port — no filesystem or process spawning needed.

use launcher_lib::{daemon_addr, find_binary, probe_daemon, wait_for_daemon, DEFAULT_DAEMON_ADDR};
use std::net::SocketAddr;
use std::time::Duration;
use tokio::net::TcpListener;
use tonic::transport::Server;
use launcher_lib::{probe_daemon, wait_for_daemon, find_binary, daemon_addr, DEFAULT_DAEMON_ADDR};
use transferd_lib::{grpc::add_all_services, new_state};

// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -38,7 +38,10 @@ async fn test_probe_daemon_not_running_returns_false() {
// Nothing is listening on a random ephemeral port.
let nothing = "http://127.0.0.1:19999";
let result = probe_daemon(nothing).await;
assert!(!result, "probe should return false when daemon is not running");
assert!(
!result,
"probe should return false when daemon is not running"
);
}

#[tokio::test]
Expand Down Expand Up @@ -81,7 +84,7 @@ async fn test_wait_for_daemon_retries_until_ready() {
// We start the server with a small intentional delay.
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let url = format!("http://{addr}");
let url = format!("http://{addr}");
let state = new_state();

tokio::spawn(async move {
Expand Down Expand Up @@ -144,7 +147,10 @@ fn test_find_binary_sibling_takes_priority() {
std::env::set_var("PATH", &old_path);
fs::remove_file(&fake).ok();

assert!(found.is_some(), "should find fake transferd-ui on injected PATH");
assert!(
found.is_some(),
"should find fake transferd-ui on injected PATH"
);
}

// ---------------------------------------------------------------------------
Expand All @@ -155,12 +161,19 @@ fn test_find_binary_sibling_takes_priority() {
fn test_daemon_addr_default_and_override() {
// Run both sub-cases in the same test to avoid parallel env-var races.
std::env::remove_var("TRANSFERD_ADDR");
assert_eq!(daemon_addr(), DEFAULT_DAEMON_ADDR, "should return default when env var absent");
assert_eq!(
daemon_addr(),
DEFAULT_DAEMON_ADDR,
"should return default when env var absent"
);

std::env::set_var("TRANSFERD_ADDR", "http://10.0.0.1:9090");
let addr = daemon_addr();
std::env::remove_var("TRANSFERD_ADDR");
assert_eq!(addr, "http://10.0.0.1:9090", "should reflect env var when set");
assert_eq!(
addr, "http://10.0.0.1:9090",
"should reflect env var when set"
);
}

// ---------------------------------------------------------------------------
Expand Down
7 changes: 2 additions & 5 deletions crates/relayd/benches/protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,8 @@ fn bench_protocol_encode_decode(c: &mut Criterion) {

c.bench_function("relay_encode_forward_msg", |b| {
b.iter(|| {
let encoded = relayd::protocol::encode(
relayd::protocol::Tag::Forward,
black_box(&msg),
)
.unwrap();
let encoded =
relayd::protocol::encode(relayd::protocol::Tag::Forward, black_box(&msg)).unwrap();
black_box(encoded)
})
});
Expand Down
30 changes: 24 additions & 6 deletions crates/relayd/examples/gen_ghost_vectors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,33 @@ fn hex(bytes: &[u8]) -> String {
}

fn main() {
let path = std::env::args().nth(1).unwrap_or_else(|| "vectors/ghost.json".into());
let path = std::env::args()
.nth(1)
.unwrap_or_else(|| "vectors/ghost.json".into());

let issuer = Issuer::generate("test relay", "supporter", 2048).expect("a 2048-bit issuer key");
let me = GhostKey::generate();
let (blinded, state) = me.blind_request(&issuer.public).expect("blind");
let blind_sig = issuer.sign_blinded(&blinded).expect("the issuer signs the blinded value");
let cert = me.finish(&issuer.public, state, &blind_sig).expect("unblind and check");
cert.verify(&issuer.public).expect("the certificate verifies");
let blind_sig = issuer
.sign_blinded(&blinded)
.expect("the issuer signs the blinded value");
let cert = me
.finish(&issuer.public, state, &blind_sig)
.expect("unblind and check");
cert.verify(&issuer.public)
.expect("the certificate verifies");

let token: [u8; 32] = std::array::from_fn(|i| (i as u8).wrapping_mul(13).wrapping_add(5));
let (pow_nonce, seq) = (7u64, 3u32);
let msg = ghost_register(RegisterMsg { session_token: token, pow_nonce, seq }, &cert, &me);
let msg = ghost_register(
RegisterMsg {
session_token: token,
pow_nonce,
seq,
},
&cert,
&me,
);
let body = bincode::serialize(&msg).expect("the registration serialises");
let cert_bytes = bincode::serialize(&cert).expect("the certificate serialises");
let bound = binding(&token, seq);
Expand Down Expand Up @@ -64,7 +79,10 @@ fn main() {
body = hex(&body),
);

if let Some(dir) = std::path::Path::new(&path).parent().filter(|d| !d.as_os_str().is_empty()) {
if let Some(dir) = std::path::Path::new(&path)
.parent()
.filter(|d| !d.as_os_str().is_empty())
{
std::fs::create_dir_all(dir).expect("create the vectors directory");
}
std::fs::write(&path, json).expect("write the ghost vectors");
Expand Down
52 changes: 40 additions & 12 deletions crates/relayd/src/bin/relayd-ws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,23 @@
//! `RELAYD_WS_MAX_MB_PER_DAY|WEEK|MONTH`; ghost key admission: `RELAYD_GHOST_ISSUERS`, `RELAYD_REQUIRE_GHOST`,
//! `RELAYD_GHOST_SESSIONS` (as relayd).

use relayd::ws::{WsRelay, handle_connection, maintenance_loop};
use relayd::ws::{handle_connection, maintenance_loop, WsRelay};
use std::sync::Arc;
use tokio::net::TcpListener;
use tokio::sync::Mutex;

fn env_u32(name: &str, default: u32) -> u32 {
std::env::var(name).ok().and_then(|v| v.parse().ok()).unwrap_or(default)
std::env::var(name)
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(default)
}

fn env_u64(name: &str, default: u64) -> u64 {
std::env::var(name).ok().and_then(|v| v.parse().ok()).unwrap_or(default)
std::env::var(name)
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(default)
}

#[tokio::main]
Expand All @@ -33,12 +39,22 @@ async fn main() -> std::io::Result<()> {

let mut core = WsRelay::with_limits(difficulty, ttl_secs, limits);
let issuers: Vec<String> = std::env::var_os("RELAYD_GHOST_ISSUERS")
.map(|v| std::env::split_paths(&v).map(|p| p.display().to_string()).collect())
.map(|v| {
std::env::split_paths(&v)
.map(|p| p.display().to_string())
.collect()
})
.unwrap_or_default();
let require_ghost = std::env::var("RELAYD_REQUIRE_GHOST").map(|v| v == "1" || v.eq_ignore_ascii_case("true")).unwrap_or(false);
let require_ghost = std::env::var("RELAYD_REQUIRE_GHOST")
.map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
.unwrap_or(false);
if !issuers.is_empty() || require_ghost {
core.ghost = relayd::ghost::GhostPolicy::from_files(&issuers, require_ghost, env_u64("RELAYD_GHOST_SESSIONS", 8) as usize)
.map_err(std::io::Error::other)?;
core.ghost = relayd::ghost::GhostPolicy::from_files(
&issuers,
require_ghost,
env_u64("RELAYD_GHOST_SESSIONS", 8) as usize,
)
.map_err(std::io::Error::other)?;
}
let relay = Arc::new(Mutex::new(core));
tokio::spawn(maintenance_loop(relay.clone()));
Expand All @@ -47,10 +63,22 @@ async fn main() -> std::io::Result<()> {
println!(
"relayd-ws: listening on {addr} (difficulty={difficulty}, ttl={ttl_secs}s, \
max_blob={} day={} week={} month={})",
limits.max_blob_bytes.map(relayd::limits::format_bytes).unwrap_or_else(|| "unlimited".into()),
limits.daily_bytes.map(relayd::limits::format_bytes).unwrap_or_else(|| "unlimited".into()),
limits.weekly_bytes.map(relayd::limits::format_bytes).unwrap_or_else(|| "unlimited".into()),
limits.monthly_bytes.map(relayd::limits::format_bytes).unwrap_or_else(|| "unlimited".into()),
limits
.max_blob_bytes
.map(relayd::limits::format_bytes)
.unwrap_or_else(|| "unlimited".into()),
limits
.daily_bytes
.map(relayd::limits::format_bytes)
.unwrap_or_else(|| "unlimited".into()),
limits
.weekly_bytes
.map(relayd::limits::format_bytes)
.unwrap_or_else(|| "unlimited".into()),
limits
.monthly_bytes
.map(relayd::limits::format_bytes)
.unwrap_or_else(|| "unlimited".into()),
);

loop {
Expand All @@ -65,4 +93,4 @@ async fn main() -> std::io::Result<()> {
handle_connection(ws, peer, relay).await;
});
}
}
}
Loading
Loading