iroh README

The project's README from github.com/n0-computer/iroh. As one markdown file: README.md.

iroh

less net work for networks

Documentation Crates.io downloads Chat Youtube License: MIT License: Apache 2.0 CI

Docs Site | Rust Docs


What is iroh?

Iroh gives you an API for dialing by public key. You say “connect to that phone”, iroh will find & maintain the fastest connection for you, regardless of where it is.

Hole-punching

The fastest route is a direct connection, so if necessary, iroh tries to hole-punch. Should this fail, it can fall back to an open ecosystem of public relay servers. To ensure these connections are as fast as possible, we continuously measure iroh.

Built on QUIC

Iroh uses noq to establish QUIC connections between endpoints. This way you get authenticated encryption, concurrent streams with stream priorities, a datagram transport and avoid head-of-line-blocking out of the box.

Compose Protocols

Use pre-existing protocols built on iroh instead of writing your own:

Getting Started

Rust Library

It's easiest to use iroh from rust. Install it using cargo add iroh, then on the connecting side:

const ALPN: &[u8] = b"iroh-example/echo/0";

let endpoint = Endpoint::bind().await?;

// Open a connection to the accepting endpoint
let conn = endpoint.connect(addr, ALPN).await?;

// Open a bidirectional QUIC stream
let (mut send, mut recv) = conn.open_bi().await?;

// Send some data to be echoed
send.write_all(b"Hello, world!").await?;
send.finish()?;

// Receive the echo
let response = recv.read_to_end(1000).await?;
assert_eq!(&response, b"Hello, world!");

// As the side receiving the last application data - say goodbye
conn.close(0u32.into(), b"bye!");

// Close the endpoint and all its connections
endpoint.close().await;

And on the accepting side:

let endpoint = Endpoint::bind().await?;

let router = Router::builder(endpoint)
    .accept(ALPN.to_vec(), Arc::new(Echo))
    .spawn()
    .await?;

// The protocol definition:
#[derive(Debug, Clone)]
struct Echo;

impl ProtocolHandler for Echo {
    async fn accept(&self, connection: Connection) -> Result<()> {
        let (mut send, mut recv) = connection.accept_bi().await?;

        // Echo any bytes received back directly.
        let bytes_sent = tokio::io::copy(&mut recv, &mut send).await?;

        send.finish()?;
        connection.closed().await;

        Ok(())
    }
}

The full example code with more comments can be found at echo.rs.

Or use one of the pre-existing protocols, e.g. iroh-blobs or iroh-gossip.

Other Languages

If you want to use iroh from other languages, make sure to check out iroh-ffi, the repository for FFI bindings.

Repository Structure

This repository contains a workspace of crates:

License

Copyright 2025 N0, INC.

This project is licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this project by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

iroh (n0-computer/iroh)

Searching Database…

12.8K ·GitHub
Что это?Iroh — это библиотека Rust, которая позволяет подключаться к другим устройствам по их публичному ключу, а не по IP-адресу. Она сама находит и поддерживает самое быстрое соединение: прямое через hole-punching или через ретранслятор, если прямое не получается. Построена на QUIC.
Это полноценный сетевой стек или просто библиотека для соединений?Это основная библиотека Rust, которая отвечает за подключение конечных точек (hole-punching и ретрансляторы). Отдельные библиотеки протоколов, такие как iroh-blobs, iroh-gossip и iroh-docs, построены поверх неё для передачи файлов, публикации и подписки (pub-sub) и хранения данных в виде пар «ключ-значение».
Как добавить это в проект на Rust?Выполните cargo add iroh, затем на стороне, которая подключается, устанавливайте соединение по публичному ключу, а на другой стороне принимайте подключения. Полностью работающий пример находится в echo.rs.
Можно ли использовать iroh из языков, отличных от Rust?Да, через репозиторий iroh-ffi, который предоставляет FFI-привязки, чтобы iroh можно было использовать из других языков.
Всегда ли получается прямое соединение?Не всегда. Iroh сначала пытается установить прямой путь через hole-punching, но если это не получается, переходит на открытую экосистему публичных ретрансляторов, чтобы сохранить соединение.
Для чего нужна библиотека iroh-relay?Это реализация клиента и сервера ретрансляторов. N0 использует её в продакшене для публичных ретрансляторов, и её также можно развернуть у себя.
Как защищены соединения?Iroh строит QUIC-соединения с помощью библиотеки noq, которые сразу дают аутентифицированное шифрование, параллельные потоки с приоритетами и транспорт датаграмм.
Что такое iroh-dns-server?Это реализация DNS-сервера, который обеспечивает поиск адресов по DNS/Pkarr для EndpointIds. Он работает в продакшене на dns.iroh.link.
Может ли iroh эффективно передавать большие объёмы данных?Протокол iroh-blobs обеспечивает передачу больших блоков данных, которые адресуются по их содержимому и основаны на BLAKE3. Он масштабируется от килобайт до терабайт.
Size
366.5 MB
Stars
12.8K
Age
4y
Commits · 90 Days