And Iroh inspired WebRTC experiment
README.md

Hori #

Experimental native Rust transport. The API and wire protocol may change. Browser interoperability, post-quantum encryption, and production deployment have not been validated.

Iroh-inspired Rust endpoints, streams, messages, and datagrams over WebRTC data channels, with end-to-end encrypted WebSocket relays and live path migration.

For real file transfers and side-by-side iroh comparisons, see Hori Sendme. It uses the same iroh-blobs Bao verification, collections, and resumable storage over either transport, with direct/relay/auto scenarios and JSON timing/throughput reports.

Hori reuses iroh-base's stable Ed25519 keys and endpoint IDs. Its connection engine is new: it does not use iroh's QUIC transport or speak the iroh wire protocol.

use hori::{Endpoint, RelayMode, Result};

# async fn example(remote_id: hori::EndpointId) -> Result<()> {
let endpoint = Endpoint::builder()
    .alpns(vec![b"my-app/1".to_vec()])
    .relay_mode(RelayMode::Custom("ws://127.0.0.1:3340/".parse()?))
    .bind()
    .await?;

let connection = endpoint.connect(remote_id, b"my-app/1").await?;
let (mut send, mut recv) = connection.open_bi().await?;
send.write_all(b"hello").await?;
send.finish()?;
let response = recv.read_to_end(1024).await?;
# Ok(())
# }

On the other endpoint:

# async fn example(endpoint: hori::Endpoint) -> hori::Result<()> {
while let Some(incoming) = endpoint.accept().await {
    let connection = incoming.await?;
    let (mut send, mut recv) = connection.accept_bi().await?;
    let request = recv.read_to_end(1024).await?;
    send.write_all(&request).await?;
    send.finish()?;
    // Keep the connection alive until your application has finished with its streams.
}
# Ok(())
# }

Run the local reference service #

Terminal 1:

cargo run --example relay -- 127.0.0.1:3340

Terminal 2 (two local endpoints; relay first, direct ICE in the background):

cargo run --example ping

To force and verify encrypted WebSocket relaying:

cargo run --example ping -- --relay-only

For clients in separate processes, run:

cargo run --example echo -- listen

Copy the printed endpoint ID into another terminal:

cargo run --example echo -- connect <endpoint-id> "hello"

The echo example accepts HORI_RELAY_URL, HORI_STUN_URL, HORI_SECRET_KEY (a persisted iroh-compatible secret key), and HORI_RELAY_ONLY=1. Peers need a shared signaling service for offer/answer exchange. EndpointAddr can provide a remote relay URL and optional direct-address hints; an AddressLookup implementation can resolve these from an endpoint ID. Across NATs, configure a STUN server you operate or trust. There is no hardcoded public STUN or relay dependency.

The reference service binds to loopback by default. For remote use, configure a reachable listener and terminate TLS at a reverse proxy, using a wss:// client URL. It exposes /signal for signaling and /relay/<session>/<side> for paired data connections. All sockets require a fresh challenge signed by the endpoint key. Application traffic remains encrypted even with local ws:// connections; signaling metadata is protected in transit only when using WSS.

Connection setup #

  1. Each endpoint registers its ID with the WebSocket service and proves possession of its private key using a fresh server challenge.
  2. Peers exchange signed, expiring offers and answers bound to endpoint identities, ALPN, and a random session ID. With a shared relay, this foreground exchange does not wait for STUN gathering or the direct-path timeout.
  3. The relay path establishes immediately. An authenticated, stable Noise session carries application traffic while direct ICE runs in the background.
  4. Background SDP and trickled ICE candidates travel in authenticated session controls. Only host and STUN candidates are supported; TURN is rejected.
  5. When direct data channels open and authenticate, the session retransmits any outstanding ciphertext on the new path, suppresses duplicates, and orders each reliable lane independently. Application streams retain their state.
  6. A warm relay supports failover. Relay sockets reconnect; interface-address changes trigger ICE restart. Endpoint::network_change can also request a restart. Recovery is bounded by recovery_timeout, independently of endpoint shutdown.

A manual offer/answer API remains available; it gathers candidates into SDP so an application can exchange just an offer and answer without implementing trickling. Without a shared relay, direct setup uses the configured direct timeout.

Direct stack:

Hori streams/messages → stable Noise packet encryption → per-lane session delivery
 → authenticated path encryption → SCTP channel pool → DTLS → ICE/UDP

Relay stack:

Hori streams/messages → stable Noise packet encryption → per-lane session delivery
 → authenticated path encryption → WebSocket → [TLS for WSS] → TCP

There are 16 reliable stream lanes, one reliable message/control lane, and a separate unordered data channel with zero retransmissions for datagrams. Streams sharing a lane share ordering; all channels share SCTP association congestion and fragment scheduling. Relaying still shares the underlying TCP connection. This does not promise QUIC-equivalent behavior under packet loss.

The relay service routes signaling and opaque ciphertext. Unlike iroh, WebRTC needs an explicit SDP offer/answer exchange. DNS cannot replace that exchange. Hori currently uses the configured service to locate online IDs, rather than public DNS discovery. A custom signal::Signaling implementation can replace this signaling backend; signal::MemoryNetwork is included for in-process signaling. For manual signaling, use create_offer, accept_offer, and the pending connections' finish methods.

Encryption #

  • WebRTC explicitly selects its AWS-LC provider and restricts DTLS to ECDHE-ECDSA with AES-128-GCM, avoiding upstream CBC/CCM fallback implementations.
  • WSS explicitly configures rustls's AWS-LC provider and validates server certificates.
  • Both data paths additionally run the standard Noise_NN_25519_AESGCM_SHA256 handshake using a Snow resolver backed by aws-lc-rs for X25519, SHA-256, AES-256-GCM, and random generation. No default Snow crypto resolver is enabled.
  • Following Noise, each endpoint proves its stable Ed25519 identity by signing the handshake transcript. The Noise prologue binds the exact signed offer and answer, including both IDs, protocol, and session. Application data is released only after the expected peer's proof has been verified. Ephemeral session keys provide forward secrecy independently of the endpoint's long-term key.
  • Packet encryption uses Snow's stateless transport mode with explicit nonces: separate per-lane counters form unique nonces, and authenticated receive windows reject replay. The connection session persists across path changes; each physical path has separately authenticated ephemeral keys. Retransmission reuses cached connection ciphertext, without encrypting new plaintext under an old nonce.
  • Ed25519 identity/signaling signatures reuse iroh's iroh-base implementation (ed25519-dalek); encryption and key exchange use AWS-LC.

There is no QUIC protocol implementation in the dependency tree. webrtc does use quinn-udp, a UDP socket utility; this does not implement QUIC. Its upstream ICE implementation also links a TURN support crate, but Hori never configures TURN and rejects TURN relay candidates.

API compatibility and current limits #

Implemented familiar interfaces: Endpoint::builder, secret_key, alpns, async bind, id, connect(id, alpn), accept, awaitable Incoming, remote_id, open_bi, accept_bi, open_uni, accept_uni, SendStream::write_all/finish/reset/stopped, RecvStream::read_to_end/stop, connection close/closed, and endpoint close/closed. Stream halves also implement Tokio AsyncRead/AsyncWrite. Connection::send/recv add reliable message delivery. send_datagram/read_datagram provide best-effort messages up to MAX_DATAGRAM_SIZE (1200 bytes). Datagram queues are bounded and may discard packets; sending can fail immediately when the local command queue is full. Over a relay, TCP itself remains reliable and ordered even though Hori does not retransmit datagrams.

protocol::Router dispatches ALPNs to concurrent ProtocolHandler implementations. discovery::AddressLookup supports application directories; MemoryLookup is included. Connection::watch_state, selected_path, and stats expose transport changes, selected ICE candidates, byte/recovery counters, and measured heartbeat RTT. Direct-address hints supplement ICE after SDP exchange; an IP address alone does not replace signaling or ICE credentials.

Native defaults use a bounded two-thread WebRTC reactor pool and request 4 MiB UDP socket buffers, subject to OS limits. --no-default-features disables these I/O settings. Stream credit remains 64 KiB with 16 KiB chunks. Optional engine/window experiments and measured iroh comparisons are documented in the native benchmark notes.

The local webrtc driver fork enables UDP batching for Hori's normal record sizes. Default session ACKs follow the data's source path and avoid redundant arrival/delivery broadcasts. Encryption remains unchanged.

This is a working foundation, not full iroh parity:

  • Stream lanes are pooled, rather than one data channel per application stream. SCTP association congestion/fragment scheduling and relay TCP can still cause stalls.
  • Interface detection currently polls interface addresses. Broader operating-system, NAT, and network-switch coverage requires the optional network harness.
  • Native Rust clients are supported. Browser interop requires implementing Hori's signing, Noise authentication, and stream framing on the browser side.
  • No QUIC-specific options, iroh DNS discovery, multi-relay federation, or compatibility with existing iroh peers.
  • A connection permits 64 active streams, with per-stream byte and packet windows. There can be 16 unaccepted streams of each kind. Reliable message payloads are limited to 1 MiB, fragmented into 16 KiB chunks, with four buffered incoming messages, one partial reassembly, and a 4 MiB outbound message budget. Applications must drain message and incoming-stream queues; exceeding these bounds closes the connection instead of growing memory.
  • Connection::send queues a message without acknowledging application delivery. SendStream::finish queues FIN after buffered bytes; stopped().await returns Ok(None) once the peer acknowledges receipt of all bytes and FIN, or Ok(Some(code)) if the receiver stops it. This confirms transport receipt, not application processing. Slow readers can delay acknowledgment because receive buffering is bounded.
  • SendStream::reset(code) abandons one sending direction. RecvStream::stop(code) abandons one receiving direction and wakes the remote writer. The reverse direction and other streams remain usable. Dropping an unfinished reader sends STOP(0); dropping a sender implicitly finishes its buffered data.
  • Connection::closed() returns a typed ConnectionError: local close, remote ApplicationClosed { error_code, reason }, or transport loss. Pending accept/read/write/ message operations are woken. Close is immediate for local callers, with a background peer notification bounded to one second. Close reasons are limited to 16 KiB; the first close wins. Abrupt transport loss cannot guarantee application-close delivery.
  • Closing an endpoint cancels pending setup and closes all its established connections with code 0 and reason endpoint closed, waiting for their bounded close exchanges. Endpoint clones share this lifetime. Endpoint::closed reports the shutdown signal; await Endpoint::close to wait for teardown.
  • The reference server has bounded connections/queues and pairing/handshake timeouts. It is a local development service, without production rate policies, persistent presence, operational metrics, clustering, or a security audit.

Performance and remaining work #

See the benchmark investigation for measured performance, remaining bottlenecks, and environment-dependent validation.

Validation #

cargo test --all-targets
cargo clippy --all-targets -- -D warnings
cargo fmt --all -- --check

Tests exercise direct WebRTC, forced relaying, automatic fallback, 1 MB stream transfers, streams opened by both peers, concurrent streams and stream reclamation, identity/signaling tampering, offer replay, protocol rejection, TURN rejection, truncated streams, and AWS-LC X25519/AES-GCM known-answer vectors.

tests/iroh_compat.rs adds 21 API behavior cases adapted from the upstream iroh suite and four cancellation regressions. These cover both direct WebRTC and relayed connections, including simultaneous dialing, successive connections, streaming echo, ALPN selection, and close/accept behavior. See the provenance and compatibility matrix for original test names and unsupported assertions.

tests/shutdown_streams.rs adds 22 tests over both paths for close-code/reason equality, retained pending futures, endpoint teardown, directional reset/stop, saturated writers, abandoned reader reclamation, slow readers alongside unrelated streams, delivery-wait cancellation, unidirectional streams from both peers, and manual-setup cancellation.

Optional local upstream checkouts belong in the ignored reference/ directory. The published iroh-base crate is the core transport's only reused iroh dependency; the separate comparison tool also uses iroh and iroh-blobs. Editing the reference clone is unnecessary.

License and credits #

Licensed under either Apache 2.0 or MIT. See third-party notices for upstream code and test provenance.

This project was developed with assistance from AI coding agents.