Skip to main content

hightower_node/
lib.rs

1pub mod context;
2
3use context::CommonContext;
4use hightower_client::HightowerConnection;
5use tracing::{debug, error};
6
7pub async fn run(context: &CommonContext) -> Result<HightowerConnection, String> {
8    // Get gateway URL from context or use default
9    let gateway_url = context
10        .kv
11        .get_bytes(context::GATEWAY_URL_KEY)
12        .ok()
13        .flatten()
14        .and_then(|bytes| String::from_utf8(bytes).ok())
15        .unwrap_or_else(|| "http://127.0.0.1:8008".to_string());
16
17    // Get auth token from context
18    let auth_token = context
19        .kv
20        .get_bytes(context::HT_AUTH_KEY)
21        .map_err(|e| format!("Failed to get auth token: {:?}", e))?
22        .ok_or_else(|| "Auth token not found in context".to_string())?;
23
24    let auth_token = String::from_utf8(auth_token)
25        .map_err(|e| format!("Invalid auth token encoding: {:?}", e))?;
26
27    debug!(gateway_url = %gateway_url, "Connecting to gateway");
28
29    // Connect using hightower-client - handles everything:
30    // - Keypair generation
31    // - Transport server creation
32    // - IP discovery via STUN
33    // - Gateway registration
34    // - Peer management
35    // - Persistence
36    let connection = HightowerConnection::connect(&gateway_url, &auth_token)
37        .await
38        .map_err(|e| {
39            error!(error = ?e, "Failed to connect to gateway");
40            format!("Failed to connect to gateway: {:?}", e)
41        })?;
42
43    debug!(
44        node_id = %connection.node_id(),
45        assigned_ip = %connection.assigned_ip(),
46        "Connected to gateway"
47    );
48
49    // Ping gateway to verify WireGuard connectivity
50    if let Err(e) = connection.ping_gateway().await {
51        error!(error = ?e, "Failed to ping gateway over WireGuard");
52    } else {
53        debug!("Successfully pinged gateway over WireGuard");
54    }
55
56    Ok(connection)
57}
58
59pub async fn deregister(connection: HightowerConnection) -> Result<(), String> {
60    connection
61        .disconnect()
62        .await
63        .map_err(|e| format!("Failed to disconnect: {:?}", e))
64}