🚀

Getting Started #

Set up your development environment and establish your first connection to Tor's control port. This guide covers prerequisites, configuration, and basic authentication methods.

Beginner Setup Authentication
1 Prerequisites

Before using stem, ensure you have Tor installed and configured with a control port. The control port allows external applications to communicate with the Tor process.

🔧 Tor Installation

Install Tor via your package manager or from torproject.org

⚙️ Control Port

Enable the control port in your torrc configuration file

🦀 Rust Toolchain

Rust 1.88+ (edition 2024) with the Tokio runtime

2 Tor Configuration
torrc

Add the following lines to your torrc file to enable the control port:

/etc/tor/torrc
# Enable the control port for local connections
ControlPort 9051

# Cookie authentication (recommended for local use)
CookieAuthentication 1

# Alternative: Password authentication
# HashedControlPassword 16:872860B76453A77D60CA2BB8C1A7042072093276A3D701AD684053EC4C
💡
Security Recommendation

Cookie authentication is preferred for local connections as it doesn't require storing passwords. The cookie file is automatically created with restricted permissions.

3 Add Dependencies
Cargo.toml
Cargo.toml
[dependencies]
stem = "2"
tokio = { version = "1", features = ["full"] }
4 Basic Connection
Rust

Establish a connection to Tor and authenticate. The controller automatically detects the best authentication method available.

main.rs
use stem::{ConnectOptions, connect};

#[tokio::main]
async fn main() -> stem::Result<()> {
    let controller = connect(ConnectOptions::default()).await?;
    println!("Connected to Tor {}", controller.get_version().await?);
    Ok(())
}
Output
Connected to Tor 0.4.9.12
5 Authentication Methods

stem supports all standard Tor authentication methods:

MethodDescriptionConfiguration
SAFECOOKIEChallenge-response authentication (most secure)CookieAuthentication 1
COOKIEFile-based authentication tokenCookieAuthentication 1
HASHEDPASSWORDPassword-based authenticationHashedControlPassword ...
NULLNo authentication (not recommended)Default when no auth configured
Password Authentication
use stem::{ConnectOptions, connect};

#[tokio::main]
async fn main() -> stem::Result<()> {
    let options = ConnectOptions {
        password: Some("your_password".to_string()),
        ..ConnectOptions::default()
    };
    let controller = connect(options).await?;
    println!(
        "Authenticated against tor {}",
        controller.get_version().await?
    );
    Ok(())
}
Unix Socket Connection
use stem::{ConnectOptions, connect};

#[tokio::main]
async fn main() -> stem::Result<()> {
    let options = ConnectOptions {
        control_port: None,
        control_socket: Some("/var/run/tor/control".into()),
        ..ConnectOptions::default()
    };
    let controller = connect(options).await?;
    println!("Tor process ID: {}", controller.get_pid().await?);
    Ok(())
}
📊

Relay Monitoring #

Monitor your Tor relay's performance and traffic statistics. Learn to query bandwidth usage, connection counts, and other operational metrics in real-time.

Relay Operators Metrics get_info
1 Traffic Statistics

Query cumulative traffic statistics from your relay. These values represent total bytes transferred since Tor started.

traffic_monitor.rs
use stem::{ConnectOptions, connect};

#[tokio::main]
async fn main() -> stem::Result<()> {
    let controller = connect(ConnectOptions::default()).await?;
    let bytes_read = controller.get_info("traffic/read").await?;
    let bytes_written = controller.get_info("traffic/written").await?;

    println!("Traffic Statistics:");
    println!("  Downloaded: {bytes_read} bytes");
    println!("  Uploaded:   {bytes_written} bytes");
    Ok(())
}
Output
Traffic Statistics:
  Downloaded: 7856100 bytes
  Uploaded:   725006 bytes
2 Available Metrics

The get_info method provides access to numerous Tor metrics:

KeyDescriptionType
traffic/readTotal bytes downloadedInteger
traffic/writtenTotal bytes uploadedInteger
versionTor version stringString
circuit-statusActive circuit informationMulti-line
stream-statusActive stream informationMulti-line
addressBest guess at external IPIP Address
fingerprintRelay fingerprint (if relay)Hex String
3 Comprehensive Relay Monitor

A complete example that queries multiple metrics and formats them for display:

relay_dashboard.rs
use stem::{ConnectOptions, connect};

fn format_bytes(bytes: u64) -> String {
    const KB: f64 = 1024.0;
    const MB: f64 = KB * 1024.0;
    const GB: f64 = MB * 1024.0;

    match bytes as f64 {
        size if size >= GB => format!("{:.2} GB", size / GB),
        size if size >= MB => format!("{:.2} MB", size / MB),
        size if size >= KB => format!("{:.2} KB", size / KB),
        _ => format!("{bytes} B"),
    }
}

async fn traffic(controller: &stem::Controller, direction: &str) -> stem::Result<u64> {
    let total = controller.get_info(&format!("traffic/{direction}")).await?;
    Ok(total.trim().parse().unwrap_or(0))
}

#[tokio::main]
async fn main() -> stem::Result<()> {
    let controller = connect(ConnectOptions::default()).await?;
    let version = controller.get_version().await?;
    let pid = controller.get_pid().await?;
    let read = traffic(&controller, "read").await?;
    let written = traffic(&controller, "written").await?;

    println!("Version:    {version}");
    println!("Process ID: {pid}");
    println!("Downloaded: {}", format_bytes(read));
    println!("Uploaded:   {}", format_bytes(written));
    Ok(())
}
🌍

Geographic Exit Selection #

Configure Tor to route traffic through specific countries. Useful for accessing geo-restricted content, testing localization, or bypassing regional censorship.

Exit Nodes Country Codes SOCKS Proxy
1 Configuring Exit Nodes

Use the ExitNodes configuration option to specify which countries Tor should exit through. Country codes follow the ISO 3166-1 alpha-2 standard enclosed in braces.

exit_selection.rs
use stem::enumerations::Signal;
use stem::{ConnectOptions, connect};

#[tokio::main]
async fn main() -> stem::Result<()> {
    let controller = connect(ConnectOptions::default()).await?;

    controller.set_conf("ExitNodes", "{de}").await?;
    controller.signal(&Signal::Newnym).await?;
    println!("New circuits will exit through Germany");

    controller.reset_conf(&["ExitNodes"]).await?;
    Ok(())
}
⚠️
Privacy Consideration

Restricting exit nodes reduces anonymity by limiting the pool of available relays. Use this feature only when geographic location is essential for your use case.

2 Common Country Codes
CodeCountryCodeCountry
{us}United States{de}Germany
{gb}United Kingdom{fr}France
{nl}Netherlands{ch}Switzerland
{se}Sweden{jp}Japan
3 Making HTTP Requests Through Tor

Combine stem with an HTTP client that supports SOCKS5 proxies to make requests through Tor:

Cargo.toml (additional dependencies)
[dependencies]
reqwest = { version = "0.13", features = ["socks"] }
tor_http_client.rs
use std::time::Duration;

use stem::enumerations::Signal;
use stem::{ConnectOptions, connect};

const SOCKS_PROXY: &str = "socks5h://127.0.0.1:9050";

async fn query_through_tor(url: &str) -> Result<String, reqwest::Error> {
    let client = reqwest::Client::builder()
        .proxy(reqwest::Proxy::all(SOCKS_PROXY)?)
        .timeout(Duration::from_secs(30))
        .build()?;
    client.get(url).send().await?.text().await
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let controller = connect(ConnectOptions::default()).await?;
    controller.set_conf("ExitNodes", "{de}").await?;
    controller.signal(&Signal::Newnym).await?;
    tokio::time::sleep(Duration::from_secs(5)).await;

    let response = query_through_tor("https://check.torproject.org/api/ip").await?;
    println!("Exit IP information: {response}");
    Ok(())
}
4 Multi-Country Rotation

Iterate through multiple countries for testing or data collection:

country_rotation.rs
use std::time::Duration;

use stem::enumerations::Signal;
use stem::{ConnectOptions, connect};

const COUNTRIES: [(&str, &str); 4] = [
    ("{us}", "United States"),
    ("{de}", "Germany"),
    ("{jp}", "Japan"),
    ("{nl}", "Netherlands"),
];

#[tokio::main]
async fn main() -> stem::Result<()> {
    let controller = connect(ConnectOptions::default()).await?;

    for (code, name) in COUNTRIES {
        println!("Switching to {name} ({code})");
        controller.set_conf("ExitNodes", code).await?;
        controller.signal(&Signal::Newnym).await?;
        tokio::time::sleep(Duration::from_secs(3)).await;
    }

    controller.reset_conf(&["ExitNodes"]).await?;
    println!("Reset to the default exit selection");
    Ok(())
}
5 Manual Circuit Management

For advanced use cases, you can inspect and manage circuits directly:

circuit_management.rs
use std::time::Duration;

use stem::enumerations::CircStatus;
use stem::{ConnectOptions, connect};

#[tokio::main]
async fn main() -> stem::Result<()> {
    let controller = connect(ConnectOptions::default()).await?;

    for circuit in controller.get_circuits().await? {
        if circuit.status != CircStatus::Built {
            continue;
        }
        println!("Circuit {} ({} hops):", circuit.id, circuit.path.len());
        for (fingerprint, nickname) in &circuit.path {
            println!("  {fingerprint:?} {nickname:?}");
        }
    }

    let timeout = Some(Duration::from_secs(30));
    let circuit_id = controller.new_circuit(None, None, true, timeout).await?;
    println!("Created circuit {circuit_id}");

    controller.close_circuit(&circuit_id, "").await?;
    println!("Closed circuit {circuit_id}");
    Ok(())
}
📡

Asynchronous Event Handling #

Subscribe to real-time events from Tor including bandwidth updates, circuit changes, stream activity, and log messages. Build responsive monitoring applications.

Events Async Monitoring
1 Available Event Types

Tor emits various events that you can subscribe to. Each event type provides different information about Tor's operation:

EventDescriptionFrequency
BwBandwidth usage (bytes read/written)Every second
CircCircuit status changesOn change
StreamStream status changesOn change
NoticeNotice-level log messagesOn occurrence
WarnWarning-level log messagesOn occurrence
ErrError-level log messagesOn occurrence
2 Real-Time Bandwidth Monitor

Monitor Tor's bandwidth usage in real-time. Bandwidth events are emitted every second with the bytes transferred:

bandwidth_monitor.rs
use stem::events::{EventData, EventType};
use stem::{ConnectOptions, connect};

#[tokio::main]
async fn main() -> stem::Result<()> {
    let controller = connect(ConnectOptions::default()).await?;
    let (_, mut events) = controller.subscribe(&[EventType::Bw]).await?;

    let (mut total_read, mut total_written) = (0, 0);
    while let Some(event) = events.recv().await {
        let EventData::Bandwidth(bandwidth) = event.data else {
            continue;
        };
        total_read += bandwidth.read;
        total_written += bandwidth.written;
        println!(
            "down {:>8} B/s  up {:>8} B/s  total: down {total_read} up {total_written}",
            bandwidth.read, bandwidth.written
        );
    }
    Ok(())
}
Output
down        0 B/s  up      536 B/s  total: down 0 up 536
down     1608 B/s  up     1608 B/s  total: down 1608 up 2144
down        0 B/s  up      536 B/s  total: down 1608 up 2680
3 Circuit Event Monitoring

Track circuit lifecycle events including creation, extension, and closure:

circuit_monitor.rs
use stem::enumerations::CircStatus;
use stem::events::{EventData, EventType};
use stem::{ConnectOptions, connect};

#[tokio::main]
async fn main() -> stem::Result<()> {
    let controller = connect(ConnectOptions::default()).await?;
    let (_, mut events) = controller.subscribe(&[EventType::Circ]).await?;

    while let Some(event) = events.recv().await {
        let EventData::Circuit(circuit) = event.data else {
            continue;
        };
        let label = match circuit.status {
            CircStatus::Launched => "LAUNCHED",
            CircStatus::Built => "BUILT",
            CircStatus::Extended => "EXTENDED",
            CircStatus::Failed => "FAILED",
            CircStatus::Closed => "CLOSED",
            _ => "OTHER",
        };
        println!(
            "{label} circuit {} ({} hops)",
            circuit.id,
            circuit.path.len()
        );
    }
    Ok(())
}
4 Multi-Event Handler

subscribe returns a channel receiver. Combine it with tokio::select! to handle several events and shutdown signals in one task:

multi_event_handler.rs
use stem::events::{EventData, EventType};
use stem::{ConnectOptions, connect};

#[tokio::main]
async fn main() -> stem::Result<()> {
    let controller = connect(ConnectOptions::default()).await?;
    let (_, mut events) = controller
        .subscribe(&[EventType::Bw, EventType::Circ, EventType::Notice])
        .await?;

    loop {
        tokio::select! {
            _ = tokio::signal::ctrl_c() => break,
            Some(event) = events.recv() => match event.data {
                EventData::Bandwidth(bandwidth) if bandwidth.read + bandwidth.written > 0 => {
                    println!("[BW] down {} up {}", bandwidth.read, bandwidth.written);
                }
                EventData::Circuit(circuit) => {
                    println!("[CIRC] {} {:?}", circuit.id, circuit.status);
                }
                EventData::Log(log) => println!("[{:?}] {}", log.runlevel, log.message),
                _ => {}
            },
        }
    }
    controller.close().await;
    Ok(())
}
🧅

Onion Services (Hidden Services) #

Create and manage Tor hidden services programmatically. Host services accessible only through the Tor network without exposing your server's IP address.

Onion Services ED25519-V3 Ephemeral
1 Ephemeral Hidden Service

Ephemeral hidden services exist only in memory and are the recommended approach for programmatic service creation. They don't persist to disk and are automatically cleaned up.

📝
V3 Onion Services

Always use ED25519-V3 for new services. V2 onion services (RSA-based) are deprecated and no longer supported by the Tor network.

ephemeral_service.rs
use std::time::Duration;

use stem::onion_services::{EphemeralServiceOptions, OnionPorts};
use stem::{ConnectOptions, connect};

#[tokio::main]
async fn main() -> stem::Result<()> {
    let controller = connect(ConnectOptions::default()).await?;

    let ports = OnionPorts::Map(vec![(80, "127.0.0.1:8080".to_string())]);
    let options = EphemeralServiceOptions {
        await_publication: true,
        timeout: Some(Duration::from_secs(120)),
        ..EphemeralServiceOptions::default()
    };
    let service = controller
        .create_ephemeral_hidden_service(&ports, &options)
        .await?;
    let service_id = service.service_id.unwrap_or_default();
    println!("Address: {service_id}.onion");
    println!("Key type: {:?}", service.private_key_type);

    tokio::time::sleep(Duration::from_secs(60)).await;
    controller
        .remove_ephemeral_hidden_service(&service_id)
        .await?;
    println!("Hidden service removed");
    Ok(())
}
2 Persistent Key Storage

To maintain the same .onion address across restarts, save and restore the private key:

persistent_service.rs
use std::path::Path;

use stem::onion_services::{EphemeralServiceOptions, OnionPorts};
use stem::{ConnectOptions, connect};

const KEY_FILE: &str = "hidden_service.key";

fn saved_options() -> std::io::Result<EphemeralServiceOptions> {
    let Ok(saved) = std::fs::read_to_string(KEY_FILE) else {
        return Ok(EphemeralServiceOptions::default());
    };
    let (key_type, key_content) = saved
        .trim()
        .split_once(':')
        .ok_or_else(|| std::io::Error::other("invalid key file"))?;
    Ok(EphemeralServiceOptions {
        key_type: key_type.to_string(),
        key_content: key_content.to_string(),
        ..EphemeralServiceOptions::default()
    })
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let controller = connect(ConnectOptions::default()).await?;
    let ports = OnionPorts::Map(vec![(80, "127.0.0.1:8080".to_string())]);

    let service = controller
        .create_ephemeral_hidden_service(&ports, &saved_options()?)
        .await?;
    if let (Some(key_type), Some(key)) = (&service.private_key_type, &service.private_key)
        && !Path::new(KEY_FILE).exists()
    {
        std::fs::write(KEY_FILE, format!("{key_type}:{key}"))?;
    }

    let service_id = service.service_id.unwrap_or_default();
    println!("Hidden service: {service_id}.onion");
    tokio::signal::ctrl_c().await?;
    controller
        .remove_ephemeral_hidden_service(&service_id)
        .await?;
    Ok(())
}
3 Multi-Port Hidden Service

A single hidden service can expose multiple ports, each mapping to different local services:

multi_port_service.rs
use stem::onion_services::{EphemeralServiceOptions, OnionPorts};
use stem::{ConnectOptions, connect};

#[tokio::main]
async fn main() -> stem::Result<()> {
    let controller = connect(ConnectOptions::default()).await?;

    let ports = OnionPorts::Map(vec![
        (80, "127.0.0.1:8080".to_string()),
        (443, "127.0.0.1:8443".to_string()),
        (22, "127.0.0.1:2222".to_string()),
    ]);
    let options = EphemeralServiceOptions {
        detached: true,
        ..EphemeralServiceOptions::default()
    };
    let service = controller
        .create_ephemeral_hidden_service(&ports, &options)
        .await?;

    println!("Address: {}.onion", service.service_id.unwrap_or_default());
    println!("Ports 80, 443 and 22 map to 8080, 8443 and 2222");
    Ok(())
}
4 Complete Web Server with Hidden Service

A production-ready example combining an HTTP server with a hidden service:

Cargo.toml (additional dependencies)
[dependencies]
axum = "0.8"
onion_web_server.rs
use axum::Router;
use axum::routing::get;
use stem::onion_services::{EphemeralServiceOptions, OnionPorts};
use stem::{ConnectOptions, connect};

async fn index() -> &'static str {
    "Welcome to the hidden service!"
}

async fn health() -> &'static str {
    "OK"
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let app = Router::new()
        .route("/", get(index))
        .route("/health", get(health));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:8080").await?;
    let server = tokio::spawn(async move { axum::serve(listener, app).await });

    let controller = connect(ConnectOptions::default()).await?;
    let ports = OnionPorts::Map(vec![(80, "127.0.0.1:8080".to_string())]);
    let service = controller
        .create_ephemeral_hidden_service(&ports, &EphemeralServiceOptions::default())
        .await?;
    let service_id = service.service_id.unwrap_or_default();
    println!("Service available at http://{service_id}.onion");

    tokio::signal::ctrl_c().await?;
    controller
        .remove_ephemeral_hidden_service(&service_id)
        .await?;
    server.abort();
    Ok(())
}
📄

Network Descriptors #

Parse and analyze Tor network descriptors. Access relay metadata, consensus documents, bandwidth statistics, and build network analysis tools.

Consensus Server Descriptors Microdescriptors
1 Descriptor Types

The Tor network publishes several types of descriptors containing relay information:

📋
Server Descriptor
Full relay metadata including keys, policies, and bandwidth
📝
Microdescriptor
Compact client-side info for circuit building
📊
Consensus
Network status document listing all relays
📈
Extra-Info
Bandwidth statistics and additional metrics
🧅
Hidden Service
Onion service descriptors (v3)
2 Downloading the Network Consensus

The consensus is the authoritative document listing all relays in the network:

consensus_analysis.rs
use stem::descriptor::Descriptor;
use stem::descriptor::remote::DescriptorDownloader;

#[tokio::main]
async fn main() -> stem::Result<()> {
    let downloader = DescriptorDownloader::new();
    let documents = downloader.get_consensus_validated(None, false).await?;

    for document in documents {
        let Descriptor::NetworkStatusV3(consensus) = document else {
            continue;
        };
        println!("Valid after: {:?}", consensus.valid_after);
        println!("Valid until: {:?}", consensus.valid_until);
        println!("Total relays: {}", consensus.routers.len());

        for flag in ["Guard", "Exit", "Fast", "Stable"] {
            let count = consensus
                .routers
                .values()
                .filter(|router| router.common().flags.iter().any(|name| name == flag))
                .count();
            println!("{flag}: {count}");
        }
    }
    Ok(())
}
Output
Valid after: Some(2026-10-01T23:00:00)
Valid until: Some(2026-10-02T02:00:00)
Total relays: 9463
Guard: 5229
Exit: 3071
Fast: 9104
Stable: 8120
3 Finding High-Bandwidth Exit Relays

Analyze server descriptors to find the highest-bandwidth exit relays:

top_exits.rs
use stem::descriptor::Descriptor;
use stem::descriptor::remote::DescriptorDownloader;

#[tokio::main]
async fn main() -> stem::Result<()> {
    let descriptors = DescriptorDownloader::new()
        .get_server_descriptors(&[])?
        .run()
        .await?;

    let mut exits = Vec::new();
    for descriptor in descriptors {
        let Descriptor::RelayServer(relay) = descriptor else {
            continue;
        };
        let server = &relay.common;
        if !server.exit_policy.is_exiting_allowed() {
            continue;
        }
        let bandwidths = [
            server.average_bandwidth,
            server.burst_bandwidth,
            server.observed_bandwidth,
        ];
        let advertised = bandwidths.into_iter().flatten().min().unwrap_or(0);
        exits.push((server.nickname.clone().unwrap_or_default(), advertised));
    }

    exits.sort_by_key(|exit| std::cmp::Reverse(exit.1));
    for (rank, (nickname, bandwidth)) in exits.iter().take(10).enumerate() {
        let megabytes = *bandwidth as f64 / (1024.0 * 1024.0);
        println!("{:>2}. {nickname} - {megabytes:.2} MB/s", rank + 1);
    }
    Ok(())
}
4 Parsing Local Descriptor Files

Parse descriptors from Tor's cached files or your own archives:

parse_local.rs
use stem::descriptor::{Descriptor, DigestEncoding, DigestHash, DocumentHandler, parse_path};

fn main() -> stem::Result<()> {
    let path = "/var/lib/tor/cached-descriptors".as_ref();
    for file in parse_path(path, None, false, DocumentHandler::Entries)? {
        let Descriptor::RelayServer(relay) = file.descriptor else {
            continue;
        };
        let server = &relay.common;
        println!("Nickname: {:?}", server.nickname);
        println!("Address: {:?}:{:?}", server.address, server.or_port);
        println!("Published: {:?}", server.published);
        println!(
            "Digest: {}",
            relay.digest(DigestHash::Sha1, DigestEncoding::Hex)?
        );
        println!(
            "Allows exiting: {}",
            server.exit_policy.is_exiting_allowed()
        );
        println!("Summary: {}", server.exit_policy.summary());
    }
    Ok(())
}
🔧

Utility Functions #

Helper functions for working with Tor data including exit policy evaluation, version comparison, validation utilities, and digest computation.

Exit Policy Version Validation
1 Exit Policy Evaluation

Parse and evaluate exit policies to determine what traffic a relay allows:

exit_policy.rs
use stem::exit_policy::{ExitPolicy, ExitPolicyRule, MicroExitPolicy};

fn main() -> stem::Result<()> {
    let policy = ExitPolicy::new(&[
        "accept *:80",
        "accept *:443",
        "accept *:8080-8090",
        "reject *:*",
    ])?;

    for port in [80, 443, 22, 8085] {
        let allowed = policy.can_exit_to(Some("93.184.216.34"), Some(port), false)?;
        println!(
            "Port {port}: {}",
            if allowed { "allowed" } else { "blocked" }
        );
    }
    println!("Summary: {}", policy.summary());
    println!("Allows exiting: {}", policy.is_exiting_allowed());

    let rule = ExitPolicyRule::new("reject 10.0.0.0/8:*")?;
    println!("Rule accepts: {}", rule.is_accept);

    let micro = MicroExitPolicy::new("accept 80,443,8080-8090")?;
    println!("Micro policy: {micro}");
    Ok(())
}
Output
Port 80: allowed
Port 443: allowed
Port 22: blocked
Port 8085: allowed
Summary: accept 80, 443, 8080-8090
Allows exiting: true
Rule accepts: false
Micro policy: accept 80,443,8080-8090
2 Version Parsing and Comparison

Parse Tor version strings and compare them for feature detection:

version_check.rs
use stem::Version;

fn main() -> stem::Result<()> {
    let current = Version::new("0.4.7.10")?;
    let newer = Version::new("0.4.8.0")?;
    let development = Version::new("0.4.7.10-dev")?;

    println!("{current} < {newer}: {}", current < newer);
    println!("{current} == {development}: {}", current == development);
    println!(
        "{current} >= 0.4.0.0: {}",
        current >= Version::new("0.4.0.0")?
    );

    if current >= Version::new("0.3.2.1")? {
        println!("Tor {current} supports v3 onion services");
    }
    Ok(())
}
3 Validation Utilities

Validate Tor-specific identifiers like fingerprints and nicknames:

validation.rs
use stem::validation::{is_valid_fingerprint, is_valid_nickname};

fn main() {
    for fingerprint in [
        "9695DFC35FFEB861329B9F1AB04C46397020CE31",
        "not-a-fingerprint",
    ] {
        println!(
            "{fingerprint}: {}",
            is_valid_fingerprint(fingerprint, false)
        );
    }
    for nickname in ["MyRelay123", "way-too-long-nickname-for-tor"] {
        println!("{nickname}: {}", is_valid_nickname(nickname));
    }
}
4 Digest Computation

Compute cryptographic digests used by Tor for descriptor identification:

digests.rs
use stem::descriptor::{DigestEncoding, DigestHash, encode_digest, hash_bytes};

fn main() {
    let content = b"Example descriptor content";

    let sha1 = hash_bytes(DigestHash::Sha1, content);
    println!(
        "SHA-1 hex:    {}",
        encode_digest(&sha1, DigestEncoding::Hex)
    );
    println!(
        "SHA-1 base64: {}",
        encode_digest(&sha1, DigestEncoding::Base64)
    );

    let sha256 = hash_bytes(DigestHash::Sha256, content);
    println!(
        "SHA-256 hex:  {}",
        encode_digest(&sha256, DigestEncoding::Hex)
    );
}
5 Configuration Management

Read and modify Tor's runtime configuration:

config_management.rs
use stem::{ConnectOptions, connect};

#[tokio::main]
async fn main() -> stem::Result<()> {
    let controller = connect(ConnectOptions::default()).await?;

    let socks_port = controller.get_conf("SocksPort").await?;
    println!("Current SOCKS port: {socks_port:?}");

    controller.set_conf("MaxCircuitDirtiness", "600").await?;
    controller.reset_conf(&["MaxCircuitDirtiness"]).await?;
    Ok(())
}
6 Stream and Circuit Inspection

List and inspect active streams and circuits:

inspect_connections.rs
use stem::enumerations::{CircStatus, StreamStatus};
use stem::{ConnectOptions, connect};

#[tokio::main]
async fn main() -> stem::Result<()> {
    let controller = connect(ConnectOptions::default()).await?;

    println!("Streams:");
    for stream in controller.get_streams().await? {
        let succeeded = stream.status == StreamStatus::Succeeded;
        println!(
            "  {} {} -> {}:{} (circuit {:?}, succeeded: {succeeded})",
            stream.id, stream.target, stream.target_address, stream.target_port, stream.circ_id
        );
    }

    println!("Circuits:");
    for circuit in controller.get_circuits().await? {
        let built = circuit.status == CircStatus::Built;
        println!(
            "  {} ({} hops, built: {built})",
            circuit.id,
            circuit.path.len()
        );
    }
    Ok(())
}