DEV Community

Cover image for Building a P2P Chat over Tor with Rust's arti-client
Matías Denda
Matías Denda

Posted on

Building a P2P Chat over Tor with Rust's arti-client

Post 5 of 6 on Anyhide. This post is about peer discovery and session setup over Tor.


There's a surprising amount of work between "I have a cryptographic protocol" and "two people can talk to each other." This post is about that work.

The protocol from Post 4 assumes Alice and Bob can send each other bytes. It does not explain how they find each other in the first place, how they agree on a session, or what happens when the network drops messages. For Anyhide's chat, the answer to all three questions involves Tor hidden services, and I'd never written a line of Tor code before starting.

I used arti-client, the Rust-native Tor implementation from the Tor Project. Most content about Tor integration assumes you're running tor as a separate daemon and talking to its SOCKS port. Arti is different: it's a library you embed directly. You get a real Tor client inside your process, running on your runtime, with circuits you can open and hidden services you can host.

It's also marked experimental by the Tor Project, which I'll come back to.

Why hidden services and not just a relay

The first question you'd ask: "Can't Alice just host a regular TCP server and let Bob connect through a Tor circuit?" Yes, but it doesn't give you what you want. A regular server has a public IP and a DNS name. The fact that Bob is anonymous to Alice doesn't help if Alice's server is indexed somewhere.

Hidden services (officially "onion services") flip the model: both endpoints are anonymous. The service has a .onion address, not an IP address. Clients connect through the Tor network to a rendezvous point, where the server is waiting via its own circuit. Neither side learns the other's IP. Neither side has to open a port on their router.

For a two-person chat where both participants want privacy, that's the only model that makes sense.

The .onion address, by hand

Arti gives you an HsId when you create a hidden service — it's a 32-byte Ed25519 public key. But humans expect an address string like abcdef123...onion. Arti doesn't hand you that directly, so I wrote the conversion. It's a nice little exercise:

// src/chat/transport/tor.rs

/// Convert an HsId to its .onion address string.
fn hsid_to_onion_address(hsid: &HsId) -> String {
    // HsId is a 32-byte ed25519 public key
    // The .onion address is: base32(PUBKEY | CHECKSUM | VERSION)
    // where CHECKSUM = SHA3_256(".onion checksum" | PUBKEY | VERSION)[:2]
    // and VERSION = 0x03

    use sha3::{Digest, Sha3_256};

    let pubkey: &[u8; 32] = hsid.as_ref();
    let version: u8 = 0x03;

    let mut hasher = Sha3_256::new();
    hasher.update(b".onion checksum");
    hasher.update(pubkey);
    hasher.update([version]);
    let checksum = hasher.finalize();

    let mut combined = [0u8; 35];
    combined[..32].copy_from_slice(pubkey);
    combined[32..34].copy_from_slice(&checksum[..2]);
    combined[34] = version;

    let encoded = base32_encode(&combined);
    format!("{}.onion", encoded.to_lowercase())
}
Enter fullscreen mode Exit fullscreen mode

Some things worth calling out:

The checksum uses SHA3-256, not SHA-256. This got me on the first try. Tor v3 addresses were designed when SHA3 was still new and the spec authors wanted a Keccak-family hash. If you use SHA-256 here, you get an address that looks right but won't resolve through the network.

The string ".onion checksum" includes no null terminator, no trailing whitespace. Literal bytes. I spent a good twenty minutes debugging my first attempt because I had copied the string from a spec PDF and picked up an invisible character.

Base32 encoding is RFC 4648 with no padding, lowercase output. There are at least three base32 variants in the wild; using the wrong one gives you an address that parses but doesn't match.

These aren't bugs in arti — the library is doing the right thing. They're bugs in my first implementation because I treated "convert a pubkey to an onion address" as trivial. It's not. The Tor v3 spec is specific for a reason.

Starting the Tor client

Bootstrapping arti looks like this:

use arti_client::{TorClient, TorClientConfig};
use tor_rtcompat::PreferredRuntime;

pub struct AnyhideTorClient {
    client: TorClient<PreferredRuntime>,
}

impl AnyhideTorClient {
    pub async fn new() -> Result<Self, ChatError> {
        Self::with_profile(None).await
    }

    pub async fn with_profile(profile: Option<&str>) -> Result<Self, ChatError> {
        // build config, possibly with a profile-specific state dir
        // ...
        let config = TorClientConfig::builder().build()?;
        let client = TorClient::create_bootstrapped(config).await?;
        Ok(AnyhideTorClient { client })
    }
}
Enter fullscreen mode Exit fullscreen mode

The first create_bootstrapped call is slow. It downloads the Tor network consensus, picks relays, builds initial circuits. On my laptop it takes 20-60 seconds depending on network quality.

The profile parameter was added because I wanted to run multiple Anyhide identities on the same laptop without them sharing circuit state. Each profile gets its own ~/.local/share/anyhide/tor/<name>/ directory for persistent state. This matters: if two identities share Tor state, an observer with the right vantage could correlate them.

Hosting a hidden service

Once the client is up, creating a hidden service is a handful of lines:

use tor_hsservice::{config::OnionServiceConfigBuilder, HsNickname};

let nickname = HsNickname::new("anyhide-alice".to_string())?;
let svc_config = OnionServiceConfigBuilder::default()
    .nickname(nickname)
    .build()?;

let (service, request_stream) = self.client
    .launch_onion_service(svc_config)?;

let hsid = service.onion_name().ok_or(...)?;
let onion_addr = hsid_to_onion_address(&hsid);
println!("Listening on: {}", onion_addr);
Enter fullscreen mode Exit fullscreen mode

The request_stream is an async stream of incoming rendezvous requests. You drive it in a loop: each request becomes a DataStream (basically a TCP stream, but over Tor) that you hand off to the chat session handler.

Connecting to a hidden service is the dual:

let (stream, _) = self.client
    .connect((onion_addr.as_str(), 80))
    .await?;
Enter fullscreen mode Exit fullscreen mode

That's it. Arti handles circuit building, rendezvous, all the Tor-specific machinery. You get a stream, you read and write bytes on it.

Bidirectional connection racing

Here's a design decision I'm not sure was right.

In a classic client/server model, one party listens and the other connects. Clean, obvious. But "who's the server" introduces an asymmetry I didn't like: the server has to be online first, the client has to know the server's address, and you end up with one side structurally more burdensome than the other.

I went a different way. In Anyhide chat, both parties are equal. Both host hidden services. Both know each other's .onion addresses. When Alice wants to talk to Bob, she simultaneously:

  1. Listens on her own hidden service for incoming connections from Bob.
  2. Dials out to Bob's hidden service.

Whichever succeeds first wins. The other attempt is cancelled. Both parties do this symmetrically, so it's a race between four potential connections collapsed down to one.

Pros:

  • Nobody has to be "the server."
  • You can kick off a chat without coordinating who goes first.
  • It works when both parties are behind NATs (Tor handles that for you).

Cons:

  • Double the circuits being built. On a cold Tor client, that means double the bootstrapping latency for the initial attempt.
  • The logic for "is this incoming stream the one we're expecting?" got hairy. A stranger can still try to connect to my hidden service — I have to figure out whether to accept based on whether I recognize their identity keys in the handshake.

I think on balance it was worth it. The UX is much more pleasant: you open the chat tab and it "just connects," regardless of who opened theirs first. But if I did it again I'd at least prototype the server model first to see whether the symmetry is worth the complexity.

The handshake

Once a stream is established, the two sides need to agree on a session. Anyhide uses a three-message handshake:

Initiator --[HandshakeInit]--> Responder
         <--[HandshakeResponse]--
         --[HandshakeComplete]-->
Enter fullscreen mode Exit fullscreen mode

Each message carries ephemeral public keys, identity public keys, and an Ed25519 signature over the contents. The struct:

// src/chat/protocol/handshake.rs

/// Handshake initiation message (Initiator -> Responder).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HandshakeInit {
    pub version: u8,
    pub ephemeral_public: [u8; 32],
    pub identity_public: [u8; 32],
    pub config: ChatConfig,
    pub i_know_you: bool,
    pub signature: Vec<u8>,
}
Enter fullscreen mode Exit fullscreen mode

The i_know_you field is interesting. It's a hint: the initiator tells the responder "I have you as a contact." The responder uses this to decide how to label the incoming connection in the UI (a known face vs. a stranger — which ties into the request/accept flow in Post 6).

The signature covers everything, binding the ephemeral key to the identity key. An attacker can't swap the ephemeral key mid-stream and re-use the signature, because the signed blob is the concatenation of everything that matters.

After the responder's HandshakeResponse, both sides have enough material to derive the session keys from Post 4. The third message — HandshakeComplete — exists mostly to acknowledge the carriers and finalize the state transition before real messages start flowing. It's not strictly required for key establishment, but it gives both sides a clear "we're done with setup, switch to message mode" signal.

What arti gives you, and what it doesn't

Arti is really good at:

  • Building and managing Tor circuits.
  • Hosting and connecting to hidden services.
  • Handling stream multiplexing.
  • Integrating with Tokio/async-std runtimes.

What it isn't yet:

  • Fully feature-parity with C-Tor for advanced use cases.
  • Marked "stable for security-critical workloads." The docs are explicit: arti's onion services are experimental and not as secure as C-Tor. I put that warning at the top of my transport module too.

For a side project like Anyhide, this trade-off is fine. For something handling real dissident traffic or journalism, you probably want C-Tor and a more battle-tested stack. Arti is going to get there — the Tor Project has been iterating hard — but at the time of writing it's a caveat that needs disclosing.

Async migration notes

Anyhide started as a synchronous CLI tool. Adding Tor meant going async, which meant either partitioning the codebase or going all-in on Tokio. I went all-in, which had one specific lesson I'll share:

Don't leak async into your crypto primitives. The kdf_chain function from Post 4 is synchronous. It takes bytes, returns bytes, does no I/O. Keep it that way. The moment your crypto is async, you start thinking about cancellation safety, and cancellation safety in crypto is how you end up with partial state bugs that compromise security.

The seam I drew was: transport (Tor, TCP) is async. Session state (the ratchet, the keys) is sync, wrapped in Mutex when shared across tasks. The chat session's main loop is async and does select! on incoming messages, user input, and timers, but the cryptographic work inside each branch is a normal function call.

This has worked out well. The parts of the code where async matters are small and localized. The parts where security matters are synchronous and testable.

What's next

Post 6 is the last in the series, and it's about the user interface: building a multi-contact terminal UI with ratatui. Tabs, a Doom-style command console, request-accept for incoming connections, and the UX decisions that go into making a TUI feel like a real app rather than a scripting exercise.

Repo: github.com/matutetandil/anyhide. If you've built on arti and want to compare, drop a comment — the ecosystem is small enough that everyone's insights matter.

Top comments (0)