Skip to main content

basic/
basic.rs

1use iroh::{Endpoint, protocol::Router};
2use iroh_auth::Authenticator;
3
4#[derive(Debug)]
5struct MyProtocolHandler;
6
7impl iroh::protocol::ProtocolHandler for MyProtocolHandler {
8    async fn accept(
9        &self,
10        _connection: iroh::endpoint::Connection,
11    ) -> Result<(), iroh::protocol::AcceptError> {
12        // Handle the protocol-specific logic here
13        Ok(())
14    }
15}
16
17#[tokio::main]
18async fn main() -> Result<(), String> {
19    // 1. Create the authenticator with a shared secret
20    let auth = Authenticator::new("my-super-secret-password");
21
22    // 2. Build the endpoint with the auth hooks
23    let endpoint = Endpoint::builder()
24        .hooks(auth.clone())
25        .bind()
26        .await.map_err(|e| e.to_string())?;
27
28    // 3. The authenticator needs a reference to the bound endpoint 
29    // to initiate authentication handshakes.
30    auth.set_endpoint(&endpoint);
31
32    // 4. Register the auth protocol handler
33    let router = Router::builder(endpoint)
34        .accept(Authenticator::ALPN, auth.clone())
35
36        // Register your actual application protocols here
37        .accept(b"/my-app/1.0", MyProtocolHandler)
38        .spawn();
39    
40    // ... run your application
41    router.shutdown().await.map_err(|e| e.to_string())?;
42    Ok(())
43}