iroh

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 20, 2026 License: MIT Imports: 32 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package iroh provides peer-to-peer QUIC connectivity between endpoints identified by ed25519 public keys, interoperable with the Rust iroh project (https://github.com/n0-computer/iroh).

An Endpoint is the entry point: it binds a UDP socket, holds the endpoint's secret key, and dials and accepts QUIC connections authenticated with TLS 1.3 raw public keys (RFC 7250). A peer is addressed by its key.EndpointID plus an netaddr.EndpointAddr (direct UDP addresses and/or a home relay); the connection's transport may be a direct path or a relay.

Connections are Conn values wrapping a QUIC connection; streams and datagrams follow the quic-go model. The remote peer's verified endpoint id is available as Conn.RemoteID.

ALPN is Application-Layer Protocol Negotiation, the TLS mechanism used by QUIC peers to agree on the application protocol carried by a connection. go-iroh uses the negotiated ALPN to route incoming connections. ALPN values are strings, matching crypto/tls and quic-go. Printable ASCII such as "my/1" is common, but strings may contain arbitrary bytes.

ep, err := iroh.Bind(ctx, iroh.WithSecretKey(sk), iroh.WithALPNs("my/1"))
conn, err := ep.Connect(ctx, peerAddr, "my/1")
s, err := conn.OpenStreamSync(ctx)

This package wraps a fork of quic-go (internal/qng) that drives a vendored crypto/tls with RFC 7250 support (internal/itls/tls).

The Go API is not stable before v1 and may change in any v0 release.

Index

Examples

Constants

View Source
const (
	// N0DNSPkarrRelayProd is the number0 production pkarr relay, which also
	// serves the records over DNS.
	N0DNSPkarrRelayProd = "https://dns.iroh.link/pkarr"
	// N0DNSPkarrRelayStaging is the number0 staging pkarr relay.
	N0DNSPkarrRelayStaging = "https://staging-dns.iroh.link/pkarr"

	// DefaultPkarrTTL is the default record TTL, in seconds, of published pkarr
	// signed packets.
	DefaultPkarrTTL uint32 = 30
	// DefaultRepublishInterval is how often the publisher republishes the
	// endpoint info even when unchanged.
	DefaultRepublishInterval = 5 * time.Minute
)

pkarr relay URLs and publishing defaults.

iroh/src/address_lookup/pkarr.rs.

View Source
const (
	// HeartbeatInterval is the QUIC keep-alive / path keep-alive interval.
	// iroh/src/socket.rs HEARTBEAT_INTERVAL.
	HeartbeatInterval = 5 * time.Second

	// PathMaxIdleTimeout is the idle timeout for a non-relay (direct) path.
	// iroh/src/socket.rs PATH_MAX_IDLE_TIMEOUT.
	PathMaxIdleTimeout = socket.PathMaxIdleTimeout

	// RelayPathMaxIdleTimeout is the idle timeout for a relay path.
	// iroh/src/socket.rs RELAY_PATH_MAX_IDLE_TIMEOUT.
	RelayPathMaxIdleTimeout = socket.RelayPathMaxIdleTimeout

	// MaxMultipathPaths is the QUIC multipath path limit (transport parameter).
	// iroh/src/socket.rs MAX_MULTIPATH_PATHS.
	MaxMultipathPaths = 8

	// MaxQNTAddresses is the maximum number of remote NAT-traversal addresses
	// (transport parameter). iroh/src/socket.rs MAX_QNT_ADDRESSES.
	MaxQNTAddresses = 32
)
View Source
const ConnectTimeout = 10 * time.Second

ConnectTimeout bounds a single Connect call when no reachable address succeeds. iroh/src/endpoint.rs documents a 10s connect timeout.

View Source
const DNSProvenance = "dns"

DNSProvenance is the provenance string for DNSAddressLookup items.

View Source
const MemoryProvenance = "memory_lookup"

MemoryProvenance is the default provenance string for MemoryLookup items.

View Source
const NetReportTimeout = 5 * time.Second

NetReportTimeout is the timeout for a complete network report.

View Source
const PkarrProvenance = "pkarr"

PkarrProvenance is the provenance string for PkarrResolver items.

View Source
const StaticProvenance = "static_lookup"

StaticProvenance is the default provenance string for StaticLookup items.

Variables

View Source
var (
	// ErrNoServiceConfigured is reported when resolution is attempted with no
	// services registered.
	ErrNoServiceConfigured = errors.New("no address lookup configured")
	// ErrNoResults is reported when every configured service finished without
	// yielding an item. The per-service errors, if any, are joined into it.
	ErrNoResults = errors.New("all address lookup services failed or produced no results")
)

Errors returned by AddressLookupServices.Resolve when no service produces a result.

View Source
var ErrConnClosedDuringHandshake = errors.New("iroh: connection closed during handshake")

ErrConnClosedDuringHandshake is returned when an incoming connection attempt dies before completing its handshake (for example, a handshake timeout). Endpoint.Accept skips such attempts and keeps accepting.

View Source
var ErrConnectRejected = errors.New("iroh: connect rejected by hook")

ErrConnectRejected is returned when an endpoint hook rejects a dial before any packet is sent.

View Source
var ErrEndpointAcceptLoopInUse = errors.New("iroh: endpoint accept loop in use")

ErrEndpointAcceptLoopInUse is returned when an operation would start or reconfigure an endpoint accept loop while another accept owner is active.

View Source
var ErrEndpointClosed = errors.New("iroh: endpoint closed")

ErrEndpointClosed is returned by operations on a closed Endpoint.

View Source
var ErrHandshakeRejected = errors.New("iroh: handshake rejected by hook")

ErrHandshakeRejected is returned when an endpoint hook rejects a completed handshake.

View Source
var ErrNoAddress = errors.New("iroh: no reachable address for endpoint")

ErrNoAddress is returned when an netaddr.EndpointAddr has no usable address: no direct IP and no relay URL (or relays are disabled on this endpoint).

View Source
var ErrNoRelay = errors.New("iroh: no relays configured")

ErrNoRelay is returned by Endpoint.Online when the endpoint has no relays configured (relays disabled), so it can never come online via a relay.

View Source
var ErrSelfConnect = errors.New("iroh: cannot connect to self")

ErrSelfConnect is returned by Endpoint.Connect when asked to dial the endpoint's own id.

Functions

func IPOnlyFilter

func IPOnlyFilter(addrs []netaddr.TransportAddr) []netaddr.TransportAddr

IPOnlyFilter keeps only direct IP and custom addresses, dropping relays.

func RejectHandshake

func RejectHandshake(code uint64, reason string) error

RejectHandshake rejects a completed handshake with code and reason.

func RelayOnlyFilter

func RelayOnlyFilter(addrs []netaddr.TransportAddr) []netaddr.TransportAddr

RelayOnlyFilter keeps only relay addresses. It is the default filter for PkarrPublisher, avoiding leaking direct IP addresses to a public pkarr relay.

func ServerName

func ServerName(id key.EndpointID) string

ServerName returns the TLS server name (SNI) iroh uses to address id: BASE32_DNSSEC(id) + ".iroh.invalid". A dialing endpoint puts this in its ClientHello; the accepting endpoint proves it holds id by presenting id as its raw public key. Deriving the name from the id (rather than a constant) also keeps per-peer 0-RTT session tickets in separate cache buckets.

Types

type Accepting

type Accepting struct {
	// contains filtered or unexported fields
}

Accepting is an accepted incoming connection whose handshake may still be in progress. Call Connection to wait for the verified Conn.

func (*Accepting) ALPN

func (a *Accepting) ALPN(ctx context.Context) (string, error)

ALPN waits for the handshake to complete and returns the negotiated ALPN.

func (*Accepting) Connection

func (a *Accepting) Connection(ctx context.Context) (*Conn, error)

Connection waits for the handshake, verifies the peer id, registers the connection with the endpoint, runs handshake hooks, and returns an established Conn.

func (*Accepting) Into0RTT

func (a *Accepting) Into0RTT() (*Conn, error)

Into0RTT returns a Conn that may receive 0-RTT early data from the peer before the handshake completes. The accept side is infallible: if the peer did not send 0-RTT data the connection simply behaves as 1-RTT.

The peer's identity is not authenticated until the handshake completes. The returned Conn's RemoteID and ALPN are not meaningful until Conn.RemoteID's underlying handshake finishes; wait on Conn.HandshakeComplete before relying on them. 0-RTT data is vulnerable to replay and must not drive non-idempotent operations until the handshake completes.

func (*Accepting) RemoteAddr

func (a *Accepting) RemoteAddr() net.Addr

RemoteAddr returns the transport address of the connection.

type AcceptingHandler

type AcceptingHandler interface {
	OnAccepting(ctx context.Context, accepting *Accepting) (*Conn, error)
}

AcceptingHandler is an optional interface a ProtocolHandler may implement to intercept an incoming connection before it is converted to a verified Conn. The default behavior is Accepting.Connection.

type AddrFilter

type AddrFilter func(addrs []netaddr.TransportAddr) []netaddr.TransportAddr

AddrFilter selects and orders the transport addresses published to a lookup service. It receives the full address set and returns the subset to publish, in priority order. A nil AddrFilter publishes all addresses unchanged.

It is the Go analog of iroh's address_lookup::AddrFilter.

type AddressLookupServices

type AddressLookupServices struct {
	// contains filtered or unexported fields
}

AddressLookupServices is the registry of address lookup services for an Endpoint. It publishes the endpoint's own info to every publisher and merges resolver streams.

The zero value is an empty, ready-to-use registry. It is safe for concurrent use.

It is the Go analog of iroh's AddressLookupServices.

Example

ExampleAddressLookupServices combines several lookup services and resolves an endpoint id across all of them, acting on the first usable result.

package main

import (
	"context"
	"fmt"

	"github.com/tmc/go-iroh/dns"
	"github.com/tmc/go-iroh/iroh"
	"github.com/tmc/go-iroh/key"
	"github.com/tmc/go-iroh/netaddr"
)

func main() {
	sk, _ := key.GenerateSecretKey()
	id := sk.Public().EndpointID()
	relay, _ := netaddr.ParseRelayURL("https://relay.example/")

	mem := iroh.NewMemoryLookup()
	mem.AddEndpointInfo(dns.EndpointInfo{
		ID:   id,
		Data: dns.NewEndpointData(netaddr.RelayAddr{URL: relay}),
	})

	var services iroh.AddressLookupServices
	services.AddResolver(mem)

	for item, err := range services.Resolve(context.Background(), id) {
		if err != nil {
			continue
		}
		fmt.Println(item.Addr().RelayURLs())
		break
	}
}
Output:
[https://relay.example/]

func (*AddressLookupServices) AddPublisher

func (s *AddressLookupServices) AddPublisher(publisher AddressPublisher)

AddPublisher registers a publisher. If data has already been published, it is published to the new service immediately.

func (*AddressLookupServices) AddResolver

func (s *AddressLookupServices) AddResolver(resolver AddressResolver)

AddResolver registers a resolver.

func (*AddressLookupServices) Clear

func (s *AddressLookupServices) Clear()

Clear removes all registered publishers and resolvers.

func (*AddressLookupServices) IsEmpty

func (s *AddressLookupServices) IsEmpty() bool

IsEmpty reports whether no publishers or resolvers are registered.

func (*AddressLookupServices) Len

func (s *AddressLookupServices) Len() int

Len returns the number of registered publishers and resolvers.

func (*AddressLookupServices) Publish

func (s *AddressLookupServices) Publish(data dns.EndpointData)

Publish publishes data on every registered publisher, applying the registry's address filter first, and records it for services added later.

func (*AddressLookupServices) Resolve

Resolve looks up id across all registered services concurrently, merging their streams into the returned sequence. Each successful Item is yielded as it is produced, letting the caller act on the first usable address while slower services run.

A per-service error is yielded inline and does not end the sequence. If every configured service finishes without yielding an item, a final ErrNoResults wrapping the per-service errors is yielded. If no services are registered, ErrNoServiceConfigured is yielded once.

Cancel ctx to stop all services and end the sequence.

func (*AddressLookupServices) SetAddrFilter

func (s *AddressLookupServices) SetAddrFilter(f AddrFilter)

SetAddrFilter sets a filter applied to all data before publishing to any service, ensuring consistent filtering across services.

type AddressPublisher

type AddressPublisher interface {
	// Publish records endpoint data with the service. It is fire-and-forget:
	// the call must not block, starting any background work itself.
	Publish(data dns.EndpointData)
}

AddressPublisher publishes the endpoint's addressing information.

type AddressPublisherFunc

type AddressPublisherFunc func(data dns.EndpointData)

AddressPublisherFunc adapts a function to AddressPublisher.

func (AddressPublisherFunc) Publish

func (f AddressPublisherFunc) Publish(data dns.EndpointData)

Publish calls f(data).

type AddressResolver

type AddressResolver interface {
	// Resolve looks up addressing information for id. It returns a sequence of
	// discovered [Item] values and per-service errors. Cancel ctx to stop
	// pending work.
	Resolve(ctx context.Context, id key.EndpointID) iter.Seq2[Item, error]
}

AddressResolver resolves the addressing information of a key.EndpointID. It lets an Endpoint connect to a peer knowing only its id, by looking up a netaddr.EndpointAddr (a relay URL and/or direct addresses) through one or more lookup services.

Multiple implementations coexist: pkarr-relay (PkarrResolver), DNS (DNSAddressLookup), and in-memory (MemoryLookup). An Endpoint combines them with AddressLookupServices.

It is the Go analog of iroh's address lookup resolution path.

type AddressResolverFunc

type AddressResolverFunc func(ctx context.Context, id key.EndpointID) iter.Seq2[Item, error]

AddressResolverFunc adapts a function to AddressResolver.

func (AddressResolverFunc) Resolve

Resolve calls f(ctx, id).

type AdvertisingCustomTransport

type AdvertisingCustomTransport interface {
	CustomTransport

	// LocalCustomAddrs returns the local custom addresses this endpoint should
	// advertise. The returned slice is copied by the endpoint.
	LocalCustomAddrs(context.Context) ([]netaddr.CustomAddr, error)
}

AdvertisingCustomTransport is a custom transport that can publish local addresses in Endpoint.Addr and Endpoint.WatchAddr.

Existing CustomTransport implementations do not need to implement this interface. Transports that do implement it must return only address material that peers can dial through the same transport id.

type ApplicationError

type ApplicationError struct {
	// Code is the application-defined close code.
	Code uint64
	// Reason is the application-defined close reason.
	Reason string
	// Remote reports whether the peer sent the close.
	Remote bool
}

ApplicationError is an application-defined connection close error.

func AsApplicationError

func AsApplicationError(err error) (*ApplicationError, bool)

AsApplicationError returns the application close error in err, if any.

Example
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()

const alpn = "iroh-application-error-example/0"
srvKey, _ := key.GenerateSecretKey()
server, _ := Bind(ctx, WithSecretKey(srvKey), WithALPNs(alpn),
	WithBindAddr(netip.AddrPortFrom(netip.IPv6Loopback(), 0)))
defer server.Shutdown(ctx)
client, _ := Bind(ctx, WithBindAddr(netip.AddrPortFrom(netip.IPv6Loopback(), 0)))
defer client.Shutdown(ctx)

accepted := make(chan *Conn, 1)
go func() {
	conn, _ := server.Accept(ctx)
	accepted <- conn
}()

addr := netaddr.NewEndpointAddr(server.ID()).WithIP(server.LocalAddr())
conn, err := client.Connect(ctx, addr, alpn)
if err != nil {
	fmt.Println("connect:", err)
	return
}
defer conn.CloseWithError(0, "")

peer := <-accepted
peer.CloseWithError(7, "done")
<-conn.Context().Done()

appErr, ok := AsApplicationError(context.Cause(conn.Context()))
fmt.Println(ok, appErr.Code, appErr.Reason, appErr.Remote)
Output:
true 7 done true

func (*ApplicationError) Error

func (e *ApplicationError) Error() string

Error returns a human-readable close error.

func (*ApplicationError) Unwrap

func (e *ApplicationError) Unwrap() error

Unwrap returns net.ErrClosed.

type BiasedRttPathSelector

type BiasedRttPathSelector struct{}

BiasedRttPathSelector is the default PathSelector. It sorts paths by (tier, biased RTT): direct IP and custom paths beat relay paths, and within a tier the lowest biased RTT wins. IPv6 paths receive a 3ms RTT advantage. Switching within a tier requires the candidate's biased RTT to be at least 5ms better than the current path.

The zero value is ready to use.

Example
package main

import (
	"fmt"
	"net/netip"
	"time"

	"github.com/tmc/go-iroh/iroh"
	"github.com/tmc/go-iroh/netaddr"
)

func main() {
	selector := iroh.BiasedRttPathSelector{}
	candidates := []iroh.PathCandidate{
		{Addr: netaddr.RelayAddr{URL: mustRelayURL("https://relay.example/")}, RTT: time.Millisecond},
		{Addr: netaddr.IPAddr{Addr: netip.MustParseAddrPort("127.0.0.1:1000")}, RTT: 20 * time.Millisecond},
	}
	selected, ok := selector.Select(nil, candidates)
	fmt.Println(ok, selected.Network())
}

func mustRelayURL(s string) netaddr.RelayURL {
	u, err := netaddr.ParseRelayURL(s)
	if err != nil {
		panic(err)
	}
	return u
}
Output:
true ip

func (BiasedRttPathSelector) Select

Select implements PathSelector.

type BindOpts

type BindOpts struct {
	PrefixLen      uint8
	IsRequired     bool
	IsDefaultRoute *bool
}

BindOpts configures how a bound IP socket participates in route selection.

PrefixLen is the network prefix length matched by this socket. IsRequired keeps parity with Rust's bind options: a required bind fails the endpoint when the socket cannot be opened, which is also the behavior of this single-socket Go build. IsDefaultRoute marks the socket as a default route when non-nil.

The zero value is usable and means "host route, required, default inferred".

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

Conn is an established connection to a remote iroh endpoint. The peer's identity is authenticated by the RFC 7250 handshake and available via Conn.RemoteID.

func (*Conn) ALPN

func (c *Conn) ALPN() string

ALPN returns the negotiated ALPN protocol. For a connection obtained from Accepting.Into0RTT it is empty until the handshake completes.

func (*Conn) AcceptStream

func (c *Conn) AcceptStream(ctx context.Context) (*Stream, error)

AcceptStream accepts the next bidirectional stream opened by the peer.

func (*Conn) AcceptStreamConn

func (c *Conn) AcceptStreamConn(ctx context.Context) (net.Conn, error)

AcceptStreamConn accepts the next bidirectional stream and returns it as a net.Conn.

func (*Conn) AcceptUniStream

func (c *Conn) AcceptUniStream(ctx context.Context) (*ReceiveStream, error)

AcceptUniStream accepts the next unidirectional stream opened by the peer.

func (*Conn) Close

func (c *Conn) Close() error

Close closes the connection with application error code 0 and an empty reason. Use Conn.CloseWithError to send an application-specific close code.

func (*Conn) CloseWithError

func (c *Conn) CloseWithError(code uint64, reason string) error

CloseWithError closes the connection with an application error code and reason.

Example

ExampleConn_CloseWithError closes a loopback connection with an application code and reads it back from the connection context cause.

ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()

const alpn = "iroh-close-example/0"
srvKey, _ := key.GenerateSecretKey()
server, _ := Bind(ctx, WithSecretKey(srvKey), WithALPNs(alpn),
	WithBindAddr(netip.AddrPortFrom(netip.IPv6Loopback(), 0)))
defer server.Shutdown(ctx)
client, _ := Bind(ctx, WithBindAddr(netip.AddrPortFrom(netip.IPv6Loopback(), 0)))
defer client.Shutdown(ctx)

go server.Accept(ctx)

addr := netaddr.NewEndpointAddr(server.ID()).WithIP(server.LocalAddr())
conn, err := client.Connect(ctx, addr, alpn)
if err != nil {
	fmt.Println("connect:", err)
	return
}

conn.CloseWithError(42, "done")
<-conn.Context().Done()

var appErr *quic.ApplicationError
if errors.As(context.Cause(conn.Context()), &appErr) {
	fmt.Println("close code:", appErr.ErrorCode)
}
Output:
close code: 42

func (*Conn) Context

func (c *Conn) Context() context.Context

Context returns a context that is cancelled when the connection is closed.

func (*Conn) HandshakeComplete

func (c *Conn) HandshakeComplete() <-chan struct{}

HandshakeComplete returns a channel closed when the TLS handshake finishes. For a 0-RTT dial, Endpoint.Connect may return before this fires; waiting on it and then checking Conn.Used0RTT tells whether the 0-RTT attempt was accepted or fell back to a full handshake.

func (*Conn) KeyExchangeGroup

func (c *Conn) KeyExchangeGroup() string

KeyExchangeGroup returns the TLS named group negotiated for this connection. It is empty until the handshake completes.

func (*Conn) LocalAddr

func (c *Conn) LocalAddr() net.Addr

LocalAddr returns the local transport address, if known.

func (*Conn) MaxDatagramSize

func (c *Conn) MaxDatagramSize() (n int, ok bool)

MaxDatagramSize returns the largest payload that can currently be passed to Conn.SendDatagram. The size may change over the connection lifetime as the path MTU estimate changes. The ok result is false if datagrams were not negotiated.

func (*Conn) MultipathNegotiated

func (c *Conn) MultipathNegotiated() bool

MultipathNegotiated reports whether both endpoints negotiated the QUIC multipath extension on this connection.

func (*Conn) OpenStreamConn

func (c *Conn) OpenStreamConn(ctx context.Context) (net.Conn, error)

OpenStreamConn opens a bidirectional stream and returns it as a net.Conn.

func (*Conn) OpenStreamSync

func (c *Conn) OpenStreamSync(ctx context.Context) (*Stream, error)

OpenStreamSync opens a new bidirectional stream, blocking until the peer's flow control permits it or ctx is done.

func (*Conn) OpenUniStreamSync

func (c *Conn) OpenUniStreamSync(ctx context.Context) (*SendStream, error)

OpenUniStreamSync opens a new unidirectional (send) stream.

func (*Conn) Paths

func (c *Conn) Paths() []PathInfo

Paths returns a snapshot of the connection's currently open network paths.

Example

ExampleConn_Paths prints whether a loopback connection has a selected path.

ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()

const alpn = "iroh-paths-example/0"
srvKey, _ := key.GenerateSecretKey()
server, _ := Bind(ctx, WithSecretKey(srvKey), WithALPNs(alpn),
	WithBindAddr(netip.AddrPortFrom(netip.IPv6Loopback(), 0)))
defer server.Shutdown(ctx)
client, _ := Bind(ctx, WithBindAddr(netip.AddrPortFrom(netip.IPv6Loopback(), 0)))
defer client.Shutdown(ctx)

go server.Accept(ctx)

addr := netaddr.NewEndpointAddr(server.ID()).WithIP(server.LocalAddr())
conn, err := client.Connect(ctx, addr, alpn)
if err != nil {
	fmt.Println("connect:", err)
	return
}
defer conn.CloseWithError(0, "")

for _, path := range conn.Paths() {
	if path.Selected {
		fmt.Println(path.HasAddr, path.Relayed)
		break
	}
}
Output:
true false

func (*Conn) ReadDatagram

func (c *Conn) ReadDatagram(ctx context.Context) ([]byte, error)

ReadDatagram receives the next unreliable datagram.

func (*Conn) RemoteAddr

func (c *Conn) RemoteAddr() net.Addr

RemoteAddr returns the remote transport address, if known.

func (*Conn) RemoteID

func (c *Conn) RemoteID() key.EndpointID

RemoteID returns the verified endpoint id of the peer. For a connection obtained from Accepting.Into0RTT it is the zero id until the handshake completes; wait on Conn.HandshakeComplete before relying on it.

func (*Conn) SendDatagram

func (c *Conn) SendDatagram(b []byte) error

SendDatagram sends an unreliable datagram.

func (*Conn) Side

func (c *Conn) Side() Side

Side reports whether this connection was dialed or accepted.

func (*Conn) StableID

func (c *Conn) StableID() uint64

StableID returns an endpoint-local identifier for this connection. It is fixed for the connection lifetime, even when the transport path changes.

func (*Conn) Stats

func (c *Conn) Stats() ConnStats

Stats returns a snapshot of connection statistics.

Example

ExampleConn_Stats prints whether a loopback connection has recorded traffic.

ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()

const alpn = "iroh-stats-example/0"
srvKey, _ := key.GenerateSecretKey()
server, _ := Bind(ctx, WithSecretKey(srvKey), WithALPNs(alpn),
	WithBindAddr(netip.AddrPortFrom(netip.IPv6Loopback(), 0)))
defer server.Shutdown(ctx)
client, _ := Bind(ctx, WithBindAddr(netip.AddrPortFrom(netip.IPv6Loopback(), 0)))
defer client.Shutdown(ctx)

go server.Accept(ctx)

addr := netaddr.NewEndpointAddr(server.ID()).WithIP(server.LocalAddr())
conn, err := client.Connect(ctx, addr, alpn)
if err != nil {
	fmt.Println("connect:", err)
	return
}
defer conn.CloseWithError(0, "")

stats := conn.Stats()
fmt.Println(stats.BytesSent > 0)
Output:
true

func (*Conn) Used0RTT

func (c *Conn) Used0RTT() bool

Used0RTT reports whether the connection's early data was sent as 0-RTT and accepted by the peer. On the dialing side it is meaningful only after the handshake completes (see Conn.HandshakeComplete); a value of false means the peer rejected 0-RTT and any early data must be resent. It is always false for accepted connections that did not resume a prior session.

func (*Conn) WatchPaths

func (c *Conn) WatchPaths(ctx context.Context) (<-chan []PathInfo, error)

WatchPaths returns a stream of path snapshots for this connection.

The first value is the current snapshot. Later values are sent when the endpoint observes a path change for the peer. The stream ends when ctx is done, the connection closes, or path observation is unavailable.

Example

ExampleConn_WatchPaths prints whether the initial path snapshot is usable.

ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()

const alpn = "iroh-watch-paths-example/0"
srvKey, _ := key.GenerateSecretKey()
server, _ := Bind(ctx, WithSecretKey(srvKey), WithALPNs(alpn),
	WithBindAddr(netip.AddrPortFrom(netip.IPv6Loopback(), 0)))
defer server.Shutdown(ctx)
client, _ := Bind(ctx, WithBindAddr(netip.AddrPortFrom(netip.IPv6Loopback(), 0)))
defer client.Shutdown(ctx)

go server.Accept(ctx)

addr := netaddr.NewEndpointAddr(server.ID()).WithIP(server.LocalAddr())
conn, err := client.Connect(ctx, addr, alpn)
if err != nil {
	fmt.Println("connect:", err)
	return
}
defer conn.CloseWithError(0, "")

watch, err := conn.WatchPaths(ctx)
if err != nil {
	fmt.Println("watch:", err)
	return
}
paths := <-watch
fmt.Println(len(paths) > 0)
Output:
true

type ConnStats

type ConnStats struct {
	// MinRTT is the minimum RTT observed on the active path.
	MinRTT time.Duration
	// LatestRTT is the most recent RTT sample observed on the active path.
	LatestRTT time.Duration
	// SmoothedRTT is an exponentially weighted moving average of RTT samples.
	SmoothedRTT time.Duration
	// MeanDeviation estimates variation in RTT samples.
	MeanDeviation time.Duration

	// BytesSent is the number of bytes sent on the underlying connection,
	// including retransmissions.
	BytesSent uint64
	// PacketsSent is the number of packets sent on the underlying connection,
	// including packets later declared lost.
	PacketsSent uint64
	// BytesReceived is the number of bytes received on the underlying
	// connection, including duplicate stream data.
	BytesReceived uint64
	// PacketsReceived is the number of packets received on the underlying
	// connection, including packets that were not processable.
	PacketsReceived uint64
	// BytesLost is the number of bytes declared lost on the underlying
	// connection. It may decrease if packets declared lost are later received.
	BytesLost uint64
	// PacketsLost is the number of packets declared lost on the underlying
	// connection. It may decrease if packets declared lost are later received.
	PacketsLost uint64
}

ConnStats is a snapshot of connection statistics.

type Connecting

type Connecting struct {
	// contains filtered or unexported fields
}

Connecting is an in-progress outgoing connection whose handshake may not be complete. It is returned by Endpoint.ConnectEarly.

Await Connecting.Connection for the verified Conn (the blocking, fully-authenticated path that Endpoint.Connect returns), or call Connecting.Into0RTT to obtain a connection usable for 0-RTT early data before the handshake completes.

A Connecting is not safe for concurrent use, and may be consumed only once: after Into0RTT succeeds or Connection returns, it must not be used again.

func (*Connecting) ALPN

func (c *Connecting) ALPN() string

ALPN returns the application protocol negotiated for the connection.

func (*Connecting) Connection

func (c *Connecting) Connection(ctx context.Context) (*Conn, error)

Connection waits for the handshake, registers the connection with the endpoint, runs the AfterHandshake hooks, and returns the established Conn. This is the blocking, fully-authenticated path and is exactly what Endpoint.Connect returns.

func (*Connecting) Into0RTT

func (c *Connecting) Into0RTT() (conn *Conn, ok bool)

Into0RTT attempts to convert the dial into a 0-RTT-capable Conn.

If the session cache held a resumable ticket for the peer, the QUIC stack restored the session and the returned Conn is ready for 0-RTT early data before the handshake completes; ok is true. Otherwise the dial fell through to a full handshake and ok is false; the returned Conn is a normal 1-RTT connection equivalent to the one Connecting.Connection would return, so no fallback round trip is needed.

0-RTT early data is sent before the peer's identity is authenticated: the Conn carries the dialed addr.ID as an asserted-but-not-yet-verified identity, and 0-RTT data is vulnerable to replay, so it must never trigger non-idempotent operations. The RFC 7250 VerifyConnection check and the AfterHandshake hooks run at handshake completion; a hook rejection closes the Conn and discards any early data.

The server may accept the connection yet reject the 0-RTT data. Callers that sent early data wait on Conn.HandshakeComplete and then check Conn.Used0RTT: if it is false the early data was rejected and must be resent on the now-1-RTT connection (the QUIC stack resets the 0-RTT streams).

func (*Connecting) RemoteID

func (c *Connecting) RemoteID() key.EndpointID

RemoteID returns the asserted endpoint id of the peer being dialed. It is the dialed addr.ID; the RFC 7250 VerifyConnection check authenticates it once the handshake completes.

type CustomDatagram

type CustomDatagram struct {
	Remote   netaddr.CustomAddr
	Local    netaddr.CustomAddr
	HasLocal bool
	Data     []byte
}

CustomDatagram is one datagram received by a CustomTransport.

type CustomTransport

type CustomTransport interface {
	// Serve runs the transport until ctx is done. Each received datagram should
	// be passed to recv. recv reports false when the endpoint is shutting down or
	// its receive queue is full.
	Serve(ctx context.Context, recv func(CustomDatagram) bool)

	// Send sends p to remote. local is nil when qng did not select a specific
	// local custom address for the path.
	Send(remote netaddr.CustomAddr, local *netaddr.CustomAddr, p []byte) bool
}

CustomTransport is a pluggable endpoint transport for custom addresses. Implementations own their wire format and exchange datagrams using netaddr.CustomAddr values advertised in endpoint addresses.

type DNSAddressLookup

type DNSAddressLookup struct {
	// contains filtered or unexported fields
}

DNSAddressLookup resolves endpoint addressing information from DNS. It queries TXT records under "_iroh.<z32-endpoint-id>.<origin>" using the endpoint's DNS resolver, where <origin> is the discovery origin domain.

The zero value is not usable; create one with NewDNSAddressLookup or N0DNSAddressLookup.

It is the Go analog of iroh's DNSAddressLookup.

func N0DNSAddressLookup

func N0DNSAddressLookup(resolver *dns.Resolver) *DNSAddressLookup

N0DNSAddressLookup returns a DNSAddressLookup using the number0 production discovery origin (dns.N0DNSEndpointOriginProd).

func NewDNSAddressLookup

func NewDNSAddressLookup(origin string, resolver *dns.Resolver) *DNSAddressLookup

NewDNSAddressLookup returns a DNSAddressLookup querying origin (for example dns.N0DNSEndpointOriginProd) using resolver. If resolver is nil, a default dns.Resolver backed by the system DNS configuration is used.

func (*DNSAddressLookup) Resolve

Resolve looks up id in DNS, issuing staggered concurrent queries and yielding the first successful result or an error.

type Endpoint

type Endpoint struct {
	// contains filtered or unexported fields
}

Endpoint is a bound iroh node: it owns a secret key, a UDP socket, and the QUIC transport used to dial and accept connections. Create one with Bind.

An Endpoint is safe for concurrent use. Close it with Endpoint.Shutdown.

func Bind

func Bind(ctx context.Context, opts ...Option) (*Endpoint, error)

Bind binds a UDP socket and returns a ready Endpoint.

By default the endpoint enables qng datagrams and advertises the iroh multipath path limit. Direct UDP works without relays; relay transport, address discovery, and QNT hole-punching are separate connectivity features.

func (*Endpoint) Accept

func (e *Endpoint) Accept(ctx context.Context) (*Conn, error)

Accept blocks until an incoming connection completes its handshake, then returns it as a Conn. It returns an error if the endpoint is closed or has no configured ALPNs. ctx cancels the wait.

func (*Endpoint) AcceptIncoming

func (e *Endpoint) AcceptIncoming(ctx context.Context) (*Incoming, error)

AcceptIncoming blocks until an incoming connection attempt arrives. The returned Incoming can be accepted, refused, retried, or ignored.

func (*Endpoint) AddExternalAddr

func (e *Endpoint) AddExternalAddr(addr netip.AddrPort)

AddExternalAddr pins addr as an externally reachable address and advertises it as a QNT NAT traversal candidate until RemoveExternalAddr; net reports never drop it. Invalid, unspecified, or zero-port addresses are ignored.

func (*Endpoint) Addr

func (e *Endpoint) Addr() netaddr.EndpointAddr

Addr returns the endpoint's netaddr.EndpointAddr from currently-known local information: its id, the bound direct address, any custom transport addresses, and (when relays are enabled and a home relay is connected) its home relay URL. Later slices add reflexive addresses.

func (*Endpoint) Closed

func (e *Endpoint) Closed() <-chan struct{}

Closed returns a channel closed when the endpoint is closed.

func (*Endpoint) Connect

func (e *Endpoint) Connect(ctx context.Context, addr netaddr.EndpointAddr, alpn string) (*Conn, error)

Connect dials the endpoint identified by addr and negotiates alpn, returning an established Conn. It tries the direct IP addresses in addr in order, then (if relays are enabled) the relay URLs in addr. A relay path carries the QUIC handshake over a relay mapped address that routes through the relay transport.

Connect blocks until the handshake completes and the peer identity is verified. To send 0-RTT early data before the handshake completes, use Endpoint.ConnectEarly and Connecting.Into0RTT.

func (*Endpoint) ConnectEarly

func (e *Endpoint) ConnectEarly(ctx context.Context, addr netaddr.EndpointAddr, alpn string) (*Connecting, error)

ConnectEarly begins dialing the endpoint identified by addr for alpn and returns immediately with a Connecting handle, without waiting for the handshake. It tries the same dial targets as Endpoint.Connect.

Await Connecting.Connection for the verified Conn (the same result Endpoint.Connect returns), or call Connecting.Into0RTT to send 0-RTT early data before the handshake completes when a resumable session is cached.

func (*Endpoint) Dial

func (e *Endpoint) Dial(ctx context.Context, addr netaddr.EndpointAddr, alpn string) (net.Conn, error)

Dial dials addr, negotiates alpn, opens a bidirectional stream, and returns it as a net.Conn.

func (*Endpoint) HomeRelayStatus

func (e *Endpoint) HomeRelayStatus() watch.Observer[*RelayStatus]

HomeRelayStatus returns a watcher over the endpoint's home relay connection status. The watched value is nil until a home relay is selected; it updates whenever the home relay or its connection state changes. When relays are disabled the watcher always reports nil.

It is the Go analog of the Rust Endpoint::home_relay_status (iroh/src/endpoint.rs:1324).

Example

ExampleEndpoint_HomeRelayStatus observes the home relay connection status.

package main

import (
	"context"
	"fmt"

	"github.com/tmc/go-iroh/iroh"
	"github.com/tmc/go-iroh/relay"
)

func main() {
	ctx := context.Background()

	ep, err := iroh.Bind(ctx, iroh.WithRelayMode(relay.ModeDefault()))
	if err != nil {
		fmt.Println("bind:", err)
		return
	}
	defer ep.Shutdown(ctx)

	status := ep.HomeRelayStatus().Current()
	if status != nil && status.IsConnected() {
		fmt.Println("connected to", status.URL)
	}
}

func (*Endpoint) ID

func (e *Endpoint) ID() key.EndpointID

ID returns the endpoint's network identifier.

func (*Endpoint) InsertRelay

func (e *Endpoint) InsertRelay(url netaddr.RelayURL, cfg *RelayConfig) (*RelayConfig, error)

InsertRelay adds or replaces a relay server configuration. It returns the previous config for url when one existed.

func (*Endpoint) ListenStreams

func (e *Endpoint) ListenStreams() (*StreamListener, error)

ListenStreams returns a net.Listener view of e that accepts bidirectional streams as net.Conn values. The endpoint must already be configured with the ALPNs it should accept.

The listener consumes e's incoming accept loop. ListenStreams returns ErrEndpointAcceptLoopInUse if Endpoint.Accept, Endpoint.AcceptIncoming, another stream listener, or Router already owns that loop.

Closing the listener stops accepting new streams but does not close e or any net.Conn values already returned by StreamListener.Accept.

func (*Endpoint) LocalAddr

func (e *Endpoint) LocalAddr() netip.AddrPort

LocalAddr returns the bound UDP address.

func (*Endpoint) Metrics

func (e *Endpoint) Metrics() Metrics

Metrics returns a point-in-time snapshot of endpoint counters.

func (*Endpoint) NetReport

func (e *Endpoint) NetReport() (NetReport, bool)

NetReport returns the most recent network report applied to the endpoint. The boolean result is false when no report has completed yet.

func (*Endpoint) Online

func (e *Endpoint) Online(ctx context.Context) error

Online blocks until the endpoint has a connected home relay, or until ctx is done. It returns nil once connected, or ctx.Err() if the context ends first. When relays are disabled it returns ErrNoRelay immediately.

It is the Go analog of the Rust Endpoint::online (iroh/src/endpoint.rs:1295).

Example

ExampleEndpoint_Online binds an endpoint that uses the n0 staging relays and waits until it has a connected home relay before dialing.

package main

import (
	"context"
	"fmt"

	"github.com/tmc/go-iroh/iroh"
	"github.com/tmc/go-iroh/relay"
)

func main() {
	ctx := context.Background()

	ep, err := iroh.Bind(ctx, iroh.WithRelayMode(relay.ModeStaging()))
	if err != nil {
		fmt.Println("bind:", err)
		return
	}
	defer ep.Shutdown(ctx)

	// Block until a home relay connection is established (or ctx is done).
	if err := ep.Online(ctx); err != nil {
		fmt.Println("online:", err)
		return
	}

	// ep.Addr() now includes the home relay URL, so peers can reach this
	// endpoint over the relay.
	fmt.Println(len(ep.Addr().RelayURLs()) >= 0)
}

func (*Endpoint) RemoteInfo

func (e *Endpoint) RemoteInfo(remote key.EndpointID) (RemoteInfo, bool)

RemoteInfo returns a snapshot of known addressing information for remote. It returns false if the endpoint has no recent state for remote.

Example

ExampleEndpoint_RemoteInfo prints whether a direct loopback peer has an active known address.

package main

import (
	"context"
	"fmt"
	"net/netip"

	"github.com/tmc/go-iroh/iroh"
	"github.com/tmc/go-iroh/netaddr"
)

func main() {
	ctx := context.Background()
	const alpn = "iroh/remote-info/1"

	server, err := iroh.Bind(ctx,
		iroh.WithALPNs(alpn),
		iroh.WithBindAddr(netip.AddrPortFrom(netip.IPv6Loopback(), 0)),
	)
	if err != nil {
		fmt.Println("bind server:", err)
		return
	}
	defer server.Shutdown(ctx)

	client, err := iroh.Bind(ctx, iroh.WithBindAddr(netip.AddrPortFrom(netip.IPv6Loopback(), 0)))
	if err != nil {
		fmt.Println("bind client:", err)
		return
	}
	defer client.Shutdown(ctx)

	accepted := make(chan *iroh.Conn, 1)
	go func() {
		conn, _ := server.Accept(ctx)
		accepted <- conn
	}()

	addr := netaddr.NewEndpointAddr(server.ID()).WithIP(server.LocalAddr())
	conn, err := client.Connect(ctx, addr, alpn)
	if err != nil {
		fmt.Println("connect:", err)
		return
	}
	defer conn.CloseWithError(0, "")
	defer (<-accepted).CloseWithError(0, "")

	info, ok := client.RemoteInfo(server.ID())
	fmt.Println(ok, info.ID == server.ID(), len(info.Addrs) > 0)
}
Output:
true true true

func (*Endpoint) RemoveExternalAddr

func (e *Endpoint) RemoveExternalAddr(addr netip.AddrPort) bool

RemoveExternalAddr removes addr from the endpoint's externally reachable addresses and stops advertising it as a QNT NAT traversal candidate. It returns true if addr was present. Invalid, unspecified, or zero-port addresses are ignored.

func (*Endpoint) RemoveRelay

func (e *Endpoint) RemoveRelay(url netaddr.RelayURL) *RelayConfig

RemoveRelay removes a relay server configuration. It returns the removed config, or nil if url was not configured.

func (*Endpoint) SecretKey

func (e *Endpoint) SecretKey() key.SecretKey

SecretKey returns the endpoint's secret key.

func (*Endpoint) SetALPNs

func (e *Endpoint) SetALPNs(alpns []string) error

SetALPNs sets the ALPN protocols the endpoint accepts and begins (or continues) listening for incoming connections. It is the Go analog of the Rust Endpoint::set_alpns (iroh/src/endpoint.rs), used by [Router.Spawn] to register every protocol's ALPN at once.

SetALPNs replaces the accepted ALPN set. If a listener is already running, it is closed first; established connections are unaffected. SetALPNs returns an error while an accept loop owner such as Endpoint.Accept, Endpoint.AcceptIncoming, Endpoint.ListenStreams, or Router is active. Pass each ALPN as an arbitrary byte string represented as a Go string; see WithALPNs.

func (*Endpoint) Shutdown

func (e *Endpoint) Shutdown(ctx context.Context) error

Shutdown shuts down the endpoint: it stops accepting, closes the QUIC transport, and releases the UDP socket. In-flight connections are not forcibly closed.

func (*Endpoint) WatchAddr

func (e *Endpoint) WatchAddr() watch.Observer[netaddr.EndpointAddr]

WatchAddr returns a watcher over the endpoint's current advertised address. It updates when local external NAT candidates are added or replaced.

type EndpointHooks

type EndpointHooks interface {
	BeforeConnect(ctx context.Context, addr netaddr.EndpointAddr, alpn string) error
	AfterHandshake(ctx context.Context, conn *Conn) error
}

EndpointHooks observes and can reject outbound dials and completed handshakes.

type FilteredAddressPublisher

type FilteredAddressPublisher struct {
	// contains filtered or unexported fields
}

FilteredAddressPublisher wraps an AddressPublisher, applying an AddrFilter to the data before publishing it to the inner service.

The zero value is not usable; create one with NewFilteredAddressPublisher.

func NewFilteredAddressPublisher

func NewFilteredAddressPublisher(inner AddressPublisher, f AddrFilter) FilteredAddressPublisher

NewFilteredAddressPublisher wraps inner so that published data is filtered by f before reaching inner.

func (FilteredAddressPublisher) Inner

Inner returns the wrapped publisher.

func (FilteredAddressPublisher) Publish

func (f FilteredAddressPublisher) Publish(data dns.EndpointData)

Publish filters data and publishes it to the inner service.

type HandshakeRejectError

type HandshakeRejectError struct {
	Code   uint64
	Reason string
}

HandshakeRejectError rejects a completed handshake with an application close code and reason.

func (*HandshakeRejectError) Error

func (e *HandshakeRejectError) Error() string

Error implements error.

type Incoming

type Incoming struct {
	// contains filtered or unexported fields
}

Incoming is an incoming connection attempt accepted by an Endpoint. Call Accept to continue the handshake, or Refuse/Ignore to close it.

func (*Incoming) Accept

func (in *Incoming) Accept() (*Accepting, error)

Accept accepts the incoming connection and returns an Accepting handle.

func (*Incoming) Ignore

func (in *Incoming) Ignore()

Ignore closes the incoming connection without waiting for completion.

func (*Incoming) LocalAddr

func (in *Incoming) LocalAddr() net.Addr

LocalAddr returns the local transport address the incoming connection used.

func (*Incoming) Refuse

func (in *Incoming) Refuse()

Refuse closes the incoming connection.

func (*Incoming) RemoteAddr

func (in *Incoming) RemoteAddr() net.Addr

RemoteAddr returns the transport address of the incoming connection.

func (*Incoming) RemoteAddrValidated

func (in *Incoming) RemoteAddrValidated() bool

RemoteAddrValidated reports whether qng has validated the remote address.

type IncomingFilter

type IncomingFilter func(*Incoming) IncomingFilterOutcome

IncomingFilter decides whether to accept each incoming connection. Router evaluates FilterRetry at QUIC Initial admission time, before ALPN negotiation; other outcomes are evaluated in the accept loop after qng has an early connection. It mirrors the Rust IncomingFilter (iroh/src/protocol.rs).

type IncomingFilterOutcome

type IncomingFilterOutcome int

IncomingFilterOutcome is the decision an IncomingFilter returns for an incoming connection. It mirrors the Rust IncomingFilterOutcome (iroh/src/protocol.rs).

const (
	// FilterAccept accepts the connection and dispatches it to a handler.
	FilterAccept IncomingFilterOutcome = iota
	// FilterRetry asks the peer to retry. Router evaluates this outcome before
	// qng constructs a connection, so it emits a real QUIC Retry packet.
	FilterRetry
	// FilterReject refuses the connection.
	FilterReject
	// FilterIgnore closes the incoming connection without dispatching it.
	FilterIgnore
)

type Item

type Item struct {
	// contains filtered or unexported fields
}

Item is a single address-lookup result: the dns.EndpointInfo discovered for an endpoint plus metadata about the lookup source. It is the item carried in the streams returned by AddressResolver.Resolve.

It is the Go analog of iroh's address_lookup::Item.

func NewItem

func NewItem(info dns.EndpointInfo, provenance string, lastUpdated *uint64) Item

NewItem returns an Item for info from a lookup source identified by provenance. lastUpdated is microseconds since the unix epoch, or nil if the source does not track it.

func (Item) Addr

func (i Item) Addr() netaddr.EndpointAddr

Addr converts the item into a netaddr.EndpointAddr.

func (Item) EndpointID

func (i Item) EndpointID() key.EndpointID

EndpointID returns the id of the discovered endpoint.

func (Item) EndpointInfo

func (i Item) EndpointInfo() dns.EndpointInfo

EndpointInfo returns the discovered endpoint info.

func (Item) LastUpdated

func (i Item) LastUpdated() (uint64, bool)

LastUpdated returns the time the source last updated this info, in microseconds since the unix epoch, and whether the source tracks it.

func (Item) LastUpdatedTime

func (i Item) LastUpdatedTime() (time.Time, bool)

LastUpdatedTime returns the time the source last updated this info, and whether the source tracks it.

func (Item) Provenance

func (i Item) Provenance() string

Provenance returns a stable string identifying the lookup source that produced this item, such as "pkarr", "dns", or "memory_lookup".

func (Item) UserData

func (i Item) UserData() (dns.UserData, bool)

UserData returns the discovered user data, if set.

Example
sk, _ := key.GenerateSecretKey()
info := endpointInfoWithIP(sk.Public().EndpointID(), netip.MustParseAddrPort("127.0.0.1:1"))
ud, _ := dns.NewUserData("room=alpha")
info.Data.SetUserData(&ud)

item := NewItem(info, "memory", nil)
got, ok := item.UserData()
fmt.Println(ok, got.String())
Output:
true room=alpha

type KeyExchangePolicy

type KeyExchangePolicy uint8

KeyExchangePolicy selects the TLS key-exchange groups offered by an endpoint. The zero value uses the package default.

const (
	// KeyExchangeDefault uses the package default key-exchange groups.
	KeyExchangeDefault KeyExchangePolicy = iota
	// KeyExchangeClassical disables post-quantum key exchange.
	KeyExchangeClassical
	// KeyExchangePreferPQ prefers X25519MLKEM768 and retains classical fallback.
	KeyExchangePreferPQ
	// KeyExchangePQOnly requires X25519MLKEM768.
	KeyExchangePQOnly
)

type LookupError

type LookupError struct {
	Provenance string
	Err        error
}

LookupError reports a failed address lookup from a single service. The provenance identifies which service failed.

It is the Go analog of iroh's address_lookup::Error.

func (*LookupError) Error

func (e *LookupError) Error() string

Error implements error.

func (*LookupError) Unwrap

func (e *LookupError) Unwrap() error

Unwrap returns the wrapped error for use with errors.Is and errors.As.

type MemoryLookup

type MemoryLookup struct {
	// contains filtered or unexported fields
}

MemoryLookup is an in-memory AddressResolver for addressing information added out-of-band, such as from an endpoint ticket. Applications add and remove entries; resolution returns the stored info for an id.

The zero value is not usable; create one with NewMemoryLookup or NewMemoryLookupWithProvenance. A MemoryLookup is safe for concurrent use.

It is the Go analog of iroh's MemoryLookup.

Example

ExampleMemoryLookup resolves addressing information added out-of-band, such as from an endpoint ticket.

package main

import (
	"context"
	"fmt"

	"github.com/tmc/go-iroh/iroh"
	"github.com/tmc/go-iroh/key"
	"github.com/tmc/go-iroh/netaddr"
)

func main() {
	sk, _ := key.GenerateSecretKey()
	id := sk.Public().EndpointID()

	lookup := iroh.NewMemoryLookup()
	relay, _ := netaddr.ParseRelayURL("https://relay.example/")
	lookup.AddEndpointAddr(netaddr.NewEndpointAddr(id).WithRelayURL(relay))

	for item, err := range lookup.Resolve(context.Background(), id) {
		if err != nil {
			fmt.Println("error:", err)
			continue
		}
		fmt.Println("provenance:", item.Provenance())
		fmt.Println("relays:", item.Addr().RelayURLs())
	}
}
Output:
provenance: memory_lookup
relays: [https://relay.example/]

func MemoryLookupFromInfo

func MemoryLookupFromInfo(infos ...dns.EndpointInfo) *MemoryLookup

MemoryLookupFromInfo returns a MemoryLookup pre-populated with infos.

func NewMemoryLookup

func NewMemoryLookup() *MemoryLookup

NewMemoryLookup returns an empty MemoryLookup using MemoryProvenance.

func NewMemoryLookupWithProvenance

func NewMemoryLookupWithProvenance(provenance string) *MemoryLookup

NewMemoryLookupWithProvenance returns an empty MemoryLookup whose resolved [Item]s report the given provenance.

func (*MemoryLookup) AddEndpointAddr

func (m *MemoryLookup) AddEndpointAddr(addr netaddr.EndpointAddr)

AddEndpointAddr is a convenience wrapper for MemoryLookup.AddEndpointInfo taking an netaddr.EndpointAddr.

func (*MemoryLookup) AddEndpointInfo

func (m *MemoryLookup) AddEndpointInfo(info dns.EndpointInfo)

AddEndpointInfo merges info into the stored entry for info.ID: new direct addresses are appended and the user data is overwritten. If no entry exists, one is created.

func (*MemoryLookup) GetEndpointInfo

func (m *MemoryLookup) GetEndpointInfo(id key.EndpointID) (dns.EndpointInfo, bool)

GetEndpointInfo returns the stored info for id and whether it exists.

func (*MemoryLookup) RemoveEndpointInfo

func (m *MemoryLookup) RemoveEndpointInfo(id key.EndpointID) (dns.EndpointInfo, bool)

RemoveEndpointInfo removes and returns the info for id, and whether it existed.

func (*MemoryLookup) Resolve

func (m *MemoryLookup) Resolve(ctx context.Context, id key.EndpointID) iter.Seq2[Item, error]

Resolve returns the stored info for id, or nil if there is no entry.

func (*MemoryLookup) SetEndpointInfo

func (m *MemoryLookup) SetEndpointInfo(info dns.EndpointInfo) (dns.EndpointData, bool)

SetEndpointInfo replaces all stored info for info.ID, returning the previous dns.EndpointData and whether an entry existed.

type Metrics

type Metrics struct {
	ConnectsStarted  uint64
	ConnectsAccepted uint64
	ConnectsFailed   uint64
	AcceptsStarted   uint64
	AcceptsAccepted  uint64
	AcceptsFailed    uint64
	Socket           SocketMetrics
	NetReport        NetReportMetrics
}

Metrics is a snapshot of endpoint counters.

func (Metrics) Snapshot

func (m Metrics) Snapshot() metrics.Snapshot

Snapshot returns m as named counter values for metrics.Registry.

func (Metrics) String

func (m Metrics) String() string

String implements expvar.Var, returning the metrics snapshot as JSON.

func (Metrics) WriteOpenMetrics

func (m Metrics) WriteOpenMetrics(w io.Writer) error

WriteOpenMetrics writes m in OpenMetrics text format under the "endpoint" prefix.

type NetReport

type NetReport struct {
	// UDPv4 reports whether a QAD IPv4 round trip completed and reported an
	// observed IPv4 address.
	UDPv4 bool
	// UDPv6 reports whether a QAD IPv6 round trip completed and reported an
	// observed IPv6 address.
	UDPv6 bool

	// MappingVariesByDestV4 reports whether the observed public IPv4 address
	// differs across relays, when known.
	MappingVariesByDestV4 *bool
	// MappingVariesByDestV6 reports whether the observed public IPv6 address
	// differs across relays, when known.
	MappingVariesByDestV6 *bool

	// PreferredRelay is the relay with the best recent latency, chosen with
	// hysteresis. It is the zero RelayURL when no relay responded.
	PreferredRelay netaddr.RelayURL
	// RelayLatencies is the lowest latency recorded for each relay.
	RelayLatencies map[netaddr.RelayURL]time.Duration

	// GlobalV4 is the host's public IPv4 address as seen by a relay.
	GlobalV4 netip.AddrPort
	// GlobalV6 is the host's public IPv6 address as seen by a relay.
	GlobalV6 netip.AddrPort

	// CaptivePortal reports whether a captive portal is intercepting HTTP, when
	// the check ran.
	CaptivePortal *bool
}

NetReport is the public snapshot of the endpoint's most recent network report. The active probing client remains internal.

func (NetReport) HasUDP

func (r NetReport) HasUDP() bool

HasUDP reports whether any QAD round trip succeeded.

type NetReportMetrics

type NetReportMetrics struct {
	Reports                       uint64
	ReportsFull                   uint64
	PortmapAttempts               uint64
	PortmapExternalAddressUpdated uint64
	ReportsFailed                 uint64
}

NetReportMetrics is a snapshot of endpoint net_report counters.

type Option

type Option func(*config) error

Option configures an Endpoint at Bind time.

func WithALPNs

func WithALPNs(alpns ...string) Option

WithALPNs sets the ALPN protocols this endpoint accepts on incoming connections. ALPN is Application-Layer Protocol Negotiation, the TLS extension QUIC uses to agree on the application protocol carried by a connection.

Each ALPN is an arbitrary byte string represented as a Go string, matching crypto/tls and quic-go. Printable ASCII such as "example/1" is common, but strings may contain arbitrary bytes.

func WithAddressLookup

func WithAddressLookup(s *AddressLookupServices) Option

WithAddressLookup sets the address-lookup services the endpoint uses to resolve additional addresses for a remote endpoint (pkarr, DNS, in-memory). The per-remote state machine consults them through its resolve hook. When unset, the endpoint does no lookup-driven address resolution and connects only to the addresses passed to Endpoint.Connect.

func WithBindAddr

func WithBindAddr(addr netip.AddrPort) Option

WithBindAddr sets the local UDP address to bind. The default is an OS-assigned port on the unspecified address.

func WithBindAddrOpts

func WithBindAddrOpts(addr netip.AddrPort, opts BindOpts) Option

WithBindAddrOpts sets the local UDP address to bind with route-selection metadata. PrefixLen must fit the address family: at most 32 for IPv4 and at most 128 for IPv6.

func WithCustomTransport

func WithCustomTransport(t CustomTransport) Option

WithCustomTransport adds a custom transport backend to the magic socket. Custom transports own their wire format and exchange datagrams using netaddr.CustomAddr values advertised in endpoint addresses.

func WithDNSResolver

func WithDNSResolver(r *dns.Resolver) Option

WithDNSResolver configures DNS endpoint discovery through the number0 production origin. It is a convenience wrapper around WithAddressLookup.

func WithHooks

func WithHooks(h EndpointHooks) Option

WithHooks registers endpoint hooks. Hooks run in registration order and may reject outgoing dials or completed handshakes.

func WithKeyExchangePolicy

func WithKeyExchangePolicy(policy KeyExchangePolicy) Option

WithKeyExchangePolicy selects the TLS key-exchange groups used for direct peer connections. The zero policy keeps the package default.

func WithKeyLogWriter

func WithKeyLogWriter(w io.Writer) Option

WithKeyLogWriter writes TLS traffic secrets for direct peer QUIC handshakes in NSS SSLKEYLOGFILE format. It is for debugging only; writing these secrets compromises connection confidentiality.

func WithNATPMP

func WithNATPMP(gateway netip.Addr) Option

WithNATPMP enables NAT-PMP UDP port mapping through gateway.

NAT-PMP does not define a portable default-gateway discovery mechanism; pass the IPv4 address of the gateway that should receive NAT-PMP requests.

func WithNetReport

func WithNetReport() Option

WithNetReport enables background net_report refreshes after Bind. When relays are configured, the report's QAD-derived global addresses are advertised as local QNT candidates for active remotes.

func WithPathSelector

func WithPathSelector(selector PathSelector) Option

WithPathSelector sets the policy used to choose among candidate network paths to a remote endpoint. When unset, the endpoint uses BiasedRttPathSelector.

func WithRelayFirstDial

func WithRelayFirstDial() Option

WithRelayFirstDial makes Connect try relay addresses before direct IP addresses when both are present. Direct IP addresses are still registered as QNT candidates after the handshake, so a connection can establish through a relay and then migrate ordinary traffic to a validated direct path.

func WithRelayMode

func WithRelayMode(mode relay.Mode) Option

WithRelayMode selects which relay servers the endpoint uses. The default is relay.ModeDisabled (no relays), matching this build's direct-only default. Pass relay.ModeDefault, relay.ModeStaging, or relay.ModeCustom to enable relay connectivity.

func WithSecretKey

func WithSecretKey(sk key.SecretKey) Option

WithSecretKey sets the endpoint's identity. If unset, Bind generates a random key.

func WithSourceAddressValidation

func WithSourceAddressValidation(f func(net.Addr) bool) Option

WithSourceAddressValidation sets the QUIC Retry policy for unvalidated incoming source addresses. The function receives the unvalidated remote address and returns true when qng should send a Retry packet before allowing the connection through to AcceptIncoming.

func WithTransportConfig

func WithTransportConfig(tc *QUICTransportConfig) Option

WithTransportConfig overrides stable QUIC transport settings. Unsupported qng internals remain private to the endpoint.

func WithoutIPTransports

func WithoutIPTransports() Option

WithoutIPTransports prevents the endpoint from binding, advertising, or dialing direct IP addresses. Relay and custom transports still use the magic connection machinery.

func WithoutRelayTransports

func WithoutRelayTransports() Option

WithoutRelayTransports disables relay connectivity.

type PathCandidate

type PathCandidate struct {
	// Addr is the path's transport address.
	Addr netaddr.TransportAddr
	// RTT is the smoothed round-trip time observed on the path.
	RTT time.Duration
}

PathCandidate is one path offered to a PathSelector.

type PathInfo

type PathInfo struct {
	// ID is the QUIC multipath PathID when known. The initial path has ID 0.
	ID uint32
	// Validated reports whether the path can carry non-probing application data.
	Validated bool
	// Addr is the path's transport address, when HasAddr is true.
	Addr netaddr.TransportAddr
	// HasAddr reports whether Addr is known.
	HasAddr bool
	// RTT is the path's smoothed round-trip time, when HasRTT is true.
	RTT time.Duration
	// HasRTT reports whether RTT was observed for this path.
	HasRTT bool
	// BytesInFlight is the path's current application-data bytes in flight,
	// when HasBytesInFlight is true.
	BytesInFlight uint64
	// HasBytesInFlight reports whether BytesInFlight was observed for this path.
	HasBytesInFlight bool
	// BytesSent is the cumulative 1-RTT/0-RTT application-data packet bytes
	// sent on this path, when HasBytesSent is true. It excludes
	// Initial/Handshake packets and UDP framing overhead.
	BytesSent uint64
	// HasBytesSent reports whether BytesSent was observed for this path.
	HasBytesSent bool
	// BytesReceived is the cumulative 1-RTT/0-RTT application-data packet bytes
	// received on this path, when HasBytesReceived is true. It excludes
	// Initial/Handshake packets and UDP framing overhead.
	BytesReceived uint64
	// HasBytesReceived reports whether BytesReceived was observed for this path.
	HasBytesReceived bool
	// CongestionWindow is the path's current congestion window, when
	// HasCongestionWindow is true.
	CongestionWindow uint64
	// HasCongestionWindow reports whether CongestionWindow was observed for this
	// path.
	HasCongestionWindow bool
	// LostPackets is the number of application-data packets declared lost on
	// this path, when HasLoss is true.
	LostPackets uint64
	// LostBytes is the number of application-data bytes declared lost on this
	// path, when HasLoss is true.
	LostBytes uint64
	// HasLoss reports whether LostPackets and LostBytes were observed for this
	// path.
	HasLoss bool
	// Selected reports whether this path is currently selected for application
	// data transmission.
	Selected bool
	// Relayed reports whether this path uses a relay server.
	Relayed bool
}

PathInfo is a snapshot of one currently open network path for a connection.

type PathSelector

type PathSelector interface {
	Select(current netaddr.TransportAddr, candidates []PathCandidate) (selected netaddr.TransportAddr, ok bool)
}

PathSelector chooses the preferred path among candidates for a remote endpoint. Implementations must not block.

Returning ok=false keeps the current selection unchanged. A nil current means no path is currently selected.

type PkarrPublisher

type PkarrPublisher struct {
	// contains filtered or unexported fields
}

PkarrPublisher publishes endpoint addressing information to a pkarr relay over HTTP. Pair it with a PkarrResolver or DNSAddressLookup to resolve.

Publishing is fire-and-forget: PkarrPublisher.Publish updates an internal value and returns immediately while a background goroutine performs the HTTP PUT. The publisher republishes every DefaultRepublishInterval even when the data is unchanged, and retries with backoff on failure. By default only relay addresses are published (see RelayOnlyFilter).

The zero value is not usable; create one with NewPkarrPublisher or N0PkarrPublisher. Stop the background goroutine with PkarrPublisher.Close.

It is the Go analog of iroh's PkarrPublisher.

func N0PkarrPublisher

func N0PkarrPublisher(secretKey key.SecretKey, cfg *PkarrPublisherConfig) (*PkarrPublisher, error)

N0PkarrPublisher creates a publisher using the number0 production pkarr relay (N0DNSPkarrRelayProd).

func NewPkarrPublisher

func NewPkarrPublisher(secretKey key.SecretKey, relayURL string, cfg *PkarrPublisherConfig) (*PkarrPublisher, error)

NewPkarrPublisher creates a publisher that signs packets with secretKey, publishes to the pkarr relay at relayURL, and starts its background publish goroutine.

func (*PkarrPublisher) Close

func (p *PkarrPublisher) Close() error

Close stops the background publish goroutine and waits for it to exit.

func (*PkarrPublisher) Publish

func (p *PkarrPublisher) Publish(data dns.EndpointData)

Publish records data to publish to the pkarr relay. It applies the publisher's address filter and returns immediately; the HTTP PUT runs in the background.

type PkarrPublisherConfig

type PkarrPublisherConfig struct {
	// TTL is the record TTL, in seconds, of published packets. If zero,
	// [DefaultPkarrTTL] is used.
	TTL uint32
	// RepublishInterval is how often packets are republished even when
	// unchanged. If zero, [DefaultRepublishInterval] is used.
	RepublishInterval time.Duration
	// AddrFilter controls which addresses are published. If nil,
	// [RelayOnlyFilter] is used. Use a filter that returns its input unchanged
	// to publish all addresses.
	AddrFilter AddrFilter
	// HTTPClient is used for relay requests. If nil, a client with a per-request
	// timeout is used.
	HTTPClient *http.Client
}

PkarrPublisherConfig configures a PkarrPublisher.

type PkarrResolver

type PkarrResolver struct {
	// contains filtered or unexported fields
}

PkarrResolver resolves endpoint addressing information from a pkarr relay over HTTP.

The zero value is not usable; create one with NewPkarrResolver or N0PkarrResolver.

It is the Go analog of iroh's PkarrResolver.

func N0PkarrResolver

func N0PkarrResolver(cfg *PkarrResolverConfig) (*PkarrResolver, error)

N0PkarrResolver creates a resolver using the number0 production pkarr relay (N0DNSPkarrRelayProd).

func NewPkarrResolver

func NewPkarrResolver(relayURL string, cfg *PkarrResolverConfig) (*PkarrResolver, error)

NewPkarrResolver creates a resolver that resolves from the pkarr relay at relayURL.

func (*PkarrResolver) Resolve

func (r *PkarrResolver) Resolve(ctx context.Context, id key.EndpointID) iter.Seq2[Item, error]

Resolve fetches the signed packet for id from the pkarr relay and decodes its endpoint info.

type PkarrResolverConfig

type PkarrResolverConfig struct {
	// HTTPClient is used for relay requests. If nil, a client with a per-request
	// timeout is used.
	HTTPClient *http.Client
}

PkarrResolverConfig configures a PkarrResolver.

type ProtocolHandler

type ProtocolHandler interface {
	// Accept handles an accepted connection. ctx is cancelled when the router
	// shuts down.
	Accept(ctx context.Context, conn *Conn) error
}

ProtocolHandler handles connections accepted for a single ALPN (Application-Layer Protocol Negotiation) value. A Router dispatches each incoming connection to the handler registered for its negotiated ALPN.

Accept is called in its own goroutine for every accepted connection; it should run for the lifetime of the connection and return when done. A returned error is logged. A handler must not panic; a panic is recovered and logged, closing only that connection while the router continues accepting. It is the Go analog of the Rust ProtocolHandler trait (iroh/src/protocol.rs:228).

type ProtocolHandlerFunc

type ProtocolHandlerFunc func(ctx context.Context, conn *Conn) error

ProtocolHandlerFunc adapts a function to ProtocolHandler.

func (ProtocolHandlerFunc) Accept

func (f ProtocolHandlerFunc) Accept(ctx context.Context, conn *Conn) error

Accept calls f(ctx, conn).

type QUICTransportConfig

type QUICTransportConfig struct {
	KeepAlivePeriod time.Duration
	MaxIdleTimeout  time.Duration
	// InitialPacketSize is the initial QUIC packet size in bytes.
	InitialPacketSize uint16
	// MaxIncomingStreams is the maximum number of concurrent bidirectional
	// streams accepted from a peer.
	MaxIncomingStreams int64
}

QUICTransportConfig configures stable QUIC transport settings used by endpoints. A zero field keeps the default.

type ReceiveStream

type ReceiveStream struct {
	// contains filtered or unexported fields
}

ReceiveStream is the receive half of a unidirectional stream.

func (*ReceiveStream) CancelRead

func (s *ReceiveStream) CancelRead(code uint64)

CancelRead aborts receiving on s with code.

func (*ReceiveStream) Read

func (s *ReceiveStream) Read(p []byte) (int, error)

Read reads data from s.

func (*ReceiveStream) SetReadDeadline

func (s *ReceiveStream) SetReadDeadline(t time.Time) error

SetReadDeadline sets the read deadline for s.

type RelayConfig

type RelayConfig = relay.Config

RelayConfig configures a relay server used by an endpoint.

type RelayStatus

type RelayStatus = socket.RelayStatus

RelayStatus is the connection status of the endpoint's home relay, observed through Endpoint.HomeRelayStatus.

type RemoteInfo

type RemoteInfo struct {
	ID    key.EndpointID
	Addrs []TransportAddrInfo
}

RemoteInfo is a snapshot of known addressing information for a remote endpoint.

type Router

type Router struct {
	// contains filtered or unexported fields
}

Router accepts incoming connections on an Endpoint and dispatches each to the ProtocolHandler registered for its negotiated ALPN. Start one with NewRouter; stop it with Router.Shutdown. It is the Go analog of the Rust Router (iroh/src/protocol.rs:97).

Dispatch is by exact ALPN string. One goroutine runs the accept loop; each accepted connection is handled in a child goroutine with a context derived from the router's. A panic in a handler goroutine is recovered, logged, and stops the accept loop.

Example

ExampleRouter runs an echo protocol over a direct loopback connection: a server registers the echo handler via a Router, and a client connects, sends a message on a stream, and reads the echo back.

package main

import (
	"context"
	"fmt"
	"io"
	"net/netip"

	"github.com/tmc/go-iroh/iroh"
	"github.com/tmc/go-iroh/key"
	"github.com/tmc/go-iroh/netaddr"
)

func echo(ctx context.Context, conn *iroh.Conn) error {
	s, err := conn.AcceptStream(ctx)
	if err != nil {
		return err
	}
	if _, err := io.Copy(s, s); err != nil {
		return err
	}
	return s.Close()
}

func main() {
	ctx := context.Background()
	const alpn = "iroh/echo/1"

	srvKey, _ := key.GenerateSecretKey()
	server, err := iroh.Bind(ctx, iroh.WithSecretKey(srvKey),
		iroh.WithBindAddr(netip.AddrPortFrom(netip.IPv6Loopback(), 0)))
	if err != nil {
		fmt.Println("bind server:", err)
		return
	}

	router, err := iroh.NewRouter(server, map[string]iroh.ProtocolHandler{
		alpn: iroh.ProtocolHandlerFunc(echo),
	}, nil)
	if err != nil {
		fmt.Println("router:", err)
		return
	}
	defer router.Shutdown(ctx)

	client, err := iroh.Bind(ctx, iroh.WithBindAddr(netip.AddrPortFrom(netip.IPv6Loopback(), 0)))
	if err != nil {
		fmt.Println("bind client:", err)
		return
	}
	defer client.Shutdown(ctx)

	addr := netaddr.NewEndpointAddr(server.ID()).WithIP(server.LocalAddr())
	conn, err := client.Connect(ctx, addr, alpn)
	if err != nil {
		fmt.Println("connect:", err)
		return
	}
	defer conn.CloseWithError(0, "")

	s, _ := conn.OpenStreamSync(ctx)
	s.Write([]byte("hello"))
	s.Close()
	got, _ := io.ReadAll(s)
	fmt.Printf("%s\n", got)
}
Output:
hello

func NewRouter

func NewRouter(ep *Endpoint, handlers map[string]ProtocolHandler, cfg *RouterConfig) (*Router, error)

NewRouter registers every handler ALPN on ep, starts the accept loop, and returns the running router. The endpoint must not already be listening (do not pass WithALPNs to Bind when using a Router).

The handlers map is keyed by exact ALPN string. ALPN values are opaque byte strings represented as Go strings; printable ASCII protocol names are conventional, but binary values compare byte-for-byte. NewRouter copies the map before returning.

func (*Router) Endpoint

func (r *Router) Endpoint() *Endpoint

Endpoint returns the endpoint the router accepts on.

func (*Router) IsShutdown

func (r *Router) IsShutdown() bool

IsShutdown reports whether the router has been shut down.

func (*Router) Shutdown

func (r *Router) Shutdown(ctx context.Context) error

Shutdown stops the router: it cancels the accept loop and all handler contexts, calls Shutdown on every registered handler that implements ShutdownHandler, closes the endpoint, and waits for the accept loop and handler goroutines to finish or ctx to be done. It is idempotent and the Go analog of the Rust Router::shutdown (iroh/src/protocol.rs:429).

type RouterConfig

type RouterConfig struct {
	// IncomingFilter is consulted for each incoming connection.
	IncomingFilter IncomingFilter
	// Logger records handler errors and recovered panics. If nil,
	// [slog.Default] is used.
	Logger *slog.Logger
}

RouterConfig configures a Router.

type SendStream

type SendStream struct {
	// contains filtered or unexported fields
}

SendStream is the send half of a unidirectional stream.

func (*SendStream) CancelWrite

func (s *SendStream) CancelWrite(code uint64)

CancelWrite aborts sending on s with code.

func (*SendStream) Close

func (s *SendStream) Close() error

Close closes s.

func (*SendStream) Context

func (s *SendStream) Context() context.Context

Context is cancelled when s is closed.

func (*SendStream) ReadFrom added in v0.0.2

func (s *SendStream) ReadFrom(r io.Reader) (int64, error)

ReadFrom implements io.ReaderFrom. It reads from r until EOF or error, writing to the stream in buffer-sized chunks under a single lock acquisition per chunk; io.Copy and every caller built on it picks this up with no signature change. Data is copied into stream-owned storage before each chunk write returns, so r's buffer is never retained.

func (*SendStream) SetWriteDeadline

func (s *SendStream) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the write deadline for s.

func (*SendStream) Write

func (s *SendStream) Write(p []byte) (int, error)

Write writes data to s.

func (*SendStream) Writev added in v0.0.2

func (s *SendStream) Writev(bufs *net.Buffers) (int64, error)

Writev writes the buffers in order as one write episode, amortizing the per-call lock and bookkeeping across the vector. It returns the total number of bytes written and advances bufs to reflect exactly what was consumed, including a partially written element, so the caller can resume after a short write. The stream copies data into owned storage before Writev returns; the caller may reuse the underlying slices immediately. The delivered byte stream is identical to the equivalent sequence of Write calls; per-vector atomicity is not promised.

To send a net.Buffers, call Writev directly: net.Buffers implements io.WriterTo, which io.Copy prefers over io.ReaderFrom, so io.Copy(stream, &bufs) degrades to one Write call per element and never batches.

Vectored submission measured at least as fast as the equivalent sequence of Write calls at every tested batch depth.

type SessionCache

type SessionCache struct {
	// contains filtered or unexported fields
}

SessionCache stores TLS 1.3 session tickets so a repeat dial to a peer can resume with 0-RTT early data instead of a fresh handshake. It wraps a tls.ClientSessionCache with an LRU eviction policy capped at [maxTLSTickets] entries.

Entries are bucketed by TLS server name. iroh derives a unique server name from each peer's endpoint id (see ServerName), so tickets for different peers never collide and resuming always targets the correct identity.

A SessionCache is safe for concurrent use. The zero value is not usable; call NewSessionCache.

func NewSessionCache

func NewSessionCache() *SessionCache

NewSessionCache returns a SessionCache that retains at most [maxTLSTickets] tickets, evicting the least-recently-used entry when full.

func (*SessionCache) Get

func (c *SessionCache) Get(sessionKey string) (*tls.ClientSessionState, bool)

Get implements tls.ClientSessionCache. It returns the cached session for sessionKey, if any.

func (*SessionCache) Len

func (c *SessionCache) Len() int

Len reports the number of distinct server names that have received at least one ticket. It is an upper bound on the buckets eligible for 0-RTT resumption and exists for tests and diagnostics.

func (*SessionCache) Put

func (c *SessionCache) Put(sessionKey string, cs *tls.ClientSessionState)

Put implements tls.ClientSessionCache. The TLS stack calls it when a server issues a session ticket. A nil session removes the entry, matching the tls.ClientSessionCache contract.

type ShutdownHandler

type ShutdownHandler interface {
	// Shutdown is called once when the router is shutting down.
	Shutdown(ctx context.Context)
}

ShutdownHandler is an optional interface a ProtocolHandler may implement to run cleanup when its Router shuts down. The router calls Shutdown on every registered handler that implements it before closing the endpoint, giving handlers a chance to close connections gracefully. It mirrors the Rust ProtocolHandler::shutdown hook (iroh/src/protocol.rs:284).

type Side

type Side int

Side reports whether a Conn was dialed locally or accepted from a peer.

const (
	// SideClient is a connection this endpoint dialed.
	SideClient Side = iota
	// SideServer is a connection this endpoint accepted.
	SideServer
)

func (Side) String

func (s Side) String() string

type SocketMetrics

type SocketMetrics struct {
	UpdateDirectAddrs           uint64
	SendIPv4                    uint64
	SendIPv6                    uint64
	SendRelay                   uint64
	SendCustom                  uint64
	SendEndpointID              uint64
	SendBlackholed              uint64
	RecvDataIPv4                uint64
	RecvDataIPv6                uint64
	RecvDataRelay               uint64
	RecvDataCustom              uint64
	RecvDatagrams               uint64
	RelayHomeChange             uint64
	HolepunchAttempts           uint64
	PathsDirect                 uint64
	PathsRelay                  uint64
	PathsCustom                 uint64
	NumConnsDirect              uint64
	NumConnsOpened              uint64
	NumConnsClosed              uint64
	TransportIPPathsAdded       uint64
	TransportIPPathsRemoved     uint64
	TransportRelayPathsAdded    uint64
	TransportRelayPathsRemoved  uint64
	TransportCustomPathsAdded   uint64
	TransportCustomPathsRemoved uint64
	ActorLinkChange             uint64
}

SocketMetrics is a snapshot of endpoint magic-socket datagram counters.

type StaticLookup

type StaticLookup struct {
	// contains filtered or unexported fields
}

StaticLookup is an immutable AddressResolver for addressing information fixed at construction time.

The zero value is not usable; create one with NewStaticLookup, NewStaticLookupWithProvenance, or StaticLookupFromAddrs. A StaticLookup is safe for concurrent use.

Example

ExampleStaticLookup resolves fixed addressing information built at construction time.

package main

import (
	"context"
	"fmt"

	"github.com/tmc/go-iroh/iroh"
	"github.com/tmc/go-iroh/key"
	"github.com/tmc/go-iroh/netaddr"
)

func main() {
	sk, _ := key.GenerateSecretKey()
	id := sk.Public().EndpointID()

	relay, _ := netaddr.ParseRelayURL("https://relay.example/")
	lookup := iroh.StaticLookupFromAddrs(netaddr.NewEndpointAddr(id).WithRelayURL(relay))

	for item, err := range lookup.Resolve(context.Background(), id) {
		if err != nil {
			fmt.Println("error:", err)
			continue
		}
		fmt.Println("provenance:", item.Provenance())
		fmt.Println("relays:", item.Addr().RelayURLs())
	}
}
Output:
provenance: static_lookup
relays: [https://relay.example/]

func NewStaticLookup

func NewStaticLookup(infos ...dns.EndpointInfo) *StaticLookup

NewStaticLookup returns a StaticLookup for infos using StaticProvenance.

func NewStaticLookupWithProvenance

func NewStaticLookupWithProvenance(provenance string, infos ...dns.EndpointInfo) *StaticLookup

NewStaticLookupWithProvenance returns a StaticLookup for infos whose resolved [Item]s report the given provenance.

func StaticLookupFromAddrs

func StaticLookupFromAddrs(addrs ...netaddr.EndpointAddr) *StaticLookup

StaticLookupFromAddrs returns a StaticLookup for endpoint addresses using StaticProvenance.

func (*StaticLookup) Resolve

func (s *StaticLookup) Resolve(ctx context.Context, id key.EndpointID) iter.Seq2[Item, error]

Resolve returns the static info for id, or nil if there is no entry.

type Stream

type Stream struct {
	// contains filtered or unexported fields
}

Stream is a bidirectional stream.

func (*Stream) CancelRead

func (s *Stream) CancelRead(code uint64)

CancelRead aborts receiving on s with code.

func (*Stream) CancelWrite

func (s *Stream) CancelWrite(code uint64)

CancelWrite aborts sending on s with code.

func (*Stream) Close

func (s *Stream) Close() error

Close closes the send side of s.

func (*Stream) Context

func (s *Stream) Context() context.Context

Context is cancelled when s is closed.

func (*Stream) Read

func (s *Stream) Read(p []byte) (int, error)

Read reads data from s.

func (*Stream) ReadFrom added in v0.0.2

func (s *Stream) ReadFrom(r io.Reader) (int64, error)

ReadFrom implements io.ReaderFrom. See SendStream.ReadFrom.

func (*Stream) SetDeadline

func (s *Stream) SetDeadline(t time.Time) error

SetDeadline sets the read and write deadlines for s.

func (*Stream) SetReadDeadline

func (s *Stream) SetReadDeadline(t time.Time) error

SetReadDeadline sets the read deadline for s.

func (*Stream) SetWriteDeadline

func (s *Stream) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the write deadline for s.

func (*Stream) Write

func (s *Stream) Write(p []byte) (int, error)

Write writes data to s.

func (*Stream) Writev added in v0.0.2

func (s *Stream) Writev(bufs *net.Buffers) (int64, error)

Writev writes the buffers in order as one write episode. See SendStream.Writev.

type StreamListener

type StreamListener struct {
	// contains filtered or unexported fields
}

StreamListener accepts bidirectional iroh streams as net.Conn values.

Each accepted net.Conn is one bidirectional QUIC stream. Multiple accepted net.Conn values may come from the same peer connection. Closing an accepted net.Conn closes only that stream; closing the StreamListener closes any peer connections it has accepted but does not close the underlying endpoint. An accepted net.Conn also exposes RemoteID and Used0RTT methods.

func NewStreamListener

func NewStreamListener() *StreamListener

NewStreamListener returns a net.Listener that accepts bidirectional streams from connections dispatched to its StreamListener.Handler. Register the handler with a Router to serve one ALPN as a net.Listener.

func (*StreamListener) Accept

func (l *StreamListener) Accept() (net.Conn, error)

Accept waits for and returns the next accepted bidirectional stream.

func (*StreamListener) Addr

func (l *StreamListener) Addr() net.Addr

Addr returns the endpoint's local UDP address.

func (*StreamListener) Close

func (l *StreamListener) Close() error

Close stops accepting new streams. It does not close the underlying endpoint.

func (*StreamListener) Handler

func (l *StreamListener) Handler() ProtocolHandler

Handler returns a ProtocolHandler that dispatches accepted connection streams to l.

type TransportAddrInfo

type TransportAddrInfo struct {
	Addr       netaddr.TransportAddr
	Usage      TransportAddrUsage
	Provenance string
}

TransportAddrInfo is a remote transport address plus usage metadata.

type TransportAddrUsage

type TransportAddrUsage int

TransportAddrUsage reports whether a remote transport address is active.

const (
	// TransportAddrInactive means the address is known but not currently used.
	TransportAddrInactive TransportAddrUsage = iota
	// TransportAddrActive means the address is currently used.
	TransportAddrActive
)

Directories

Path Synopsis
Package mdns provides local-network endpoint discovery for go-iroh.
Package mdns provides local-network endpoint discovery for go-iroh.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL