惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
News | PayPal Newsroom
云风的 BLOG
云风的 BLOG
GbyAI
GbyAI
Engineering at Meta
Engineering at Meta
B
Blog RSS Feed
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
The Register - Security
The Register - Security
L
LangChain Blog
A
About on SuperTechFans
S
Schneier on Security
博客园 - 三生石上(FineUI控件)
Stack Overflow Blog
Stack Overflow Blog
The Hacker News
The Hacker News
AWS News Blog
AWS News Blog
博客园 - 司徒正美
Scott Helme
Scott Helme
K
Kaspersky official blog
Cyberwarzone
Cyberwarzone
T
Tenable Blog
腾讯CDC
Recorded Future
Recorded Future
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
G
GRAHAM CLULEY
Security Latest
Security Latest
S
Securelist
D
Darknet – Hacking Tools, Hacker News & Cyber Security
aimingoo的专栏
aimingoo的专栏
Google DeepMind News
Google DeepMind News
V
Vulnerabilities – Threatpost
雷峰网
雷峰网
T
The Exploit Database - CXSecurity.com
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
V
V2EX
T
The Blog of Author Tim Ferriss
D
Docker
S
Security Affairs
F
Full Disclosure
Know Your Adversary
Know Your Adversary
N
News and Events Feed by Topic
N
News and Events Feed by Topic
T
Tor Project blog
Hugging Face - Blog
Hugging Face - Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Microsoft Security Blog
Microsoft Security Blog
Simon Willison's Weblog
Simon Willison's Weblog
Recent Announcements
Recent Announcements
博客园_首页
博客园 - 聂微东
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
S
Security @ Cisco Blogs

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Building a P2P Chat over Tor with Rust's arti-client
Matías Denda · 2026-06-23 · via DEV Community

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())
}

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 })
    }
}

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);

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?;

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]-->

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>,
}

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.