package iroh
Import Path
github.com/tmc/go-iroh/iroh (on go.dev)
Dependency Relation
imports 32 packages, and imported by one package
Involved Source Files
addresslookup.go
addresslookup_dns.go
addresslookup_memory.go
addresslookup_pkarr.go
addresslookup_static.go
bind_udp.go
conn.go
custom.go
defaults.go
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.
endpoint.go
errors.go
hooks.go
listener.go
metrics.go
netreport.go
path_selector.go
remoteinfo.go
router.go
session_cache.go
tls.go
zerortt.go
Code Examples
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)
}
}
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)
}
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)
}
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)
}
Package-Level Type Names (total 59)
Accepting is an accepted incoming connection whose handshake may still be in
progress. Call Connection to wait for the verified [Conn].
ALPN waits for the handshake to complete and returns the negotiated ALPN.
Connection waits for the handshake, verifies the peer id, registers the
connection with the endpoint, runs handshake hooks, and returns an
established [Conn].
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.
RemoteAddr returns the transport address of the connection.
func (*Incoming).Accept() (*Accepting, error)
func AcceptingHandler.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].
( AcceptingHandler) OnAccepting(ctx context.Context, accepting *Accepting) (*Conn, error)
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.
AddPublisher registers a publisher. If data has already been published, it is
published to the new service immediately.
AddResolver registers a resolver.
Clear removes all registered publishers and resolvers.
IsEmpty reports whether no publishers or resolvers are registered.
Len returns the number of registered publishers and resolvers.
Publish publishes data on every registered publisher, applying the registry's
address filter first, and records it for services added later.
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.
SetAddrFilter sets a filter applied to all data before publishing to any
service, ensuring consistent filtering across services.
*AddressLookupServices : AddressPublisher
*AddressLookupServices : AddressResolver
func WithAddressLookup(s *AddressLookupServices) Option
AddressPublisher publishes the endpoint's addressing information.
Publish records endpoint data with the service. It is fire-and-forget:
the call must not block, starting any background work itself.
*AddressLookupServices
AddressPublisherFunc
FilteredAddressPublisher
*PkarrPublisher
func FilteredAddressPublisher.Inner() AddressPublisher
func NewFilteredAddressPublisher(inner AddressPublisher, f AddrFilter) FilteredAddressPublisher
func (*AddressLookupServices).AddPublisher(publisher AddressPublisher)
AddressPublisherFunc adapts a function to [AddressPublisher].
Publish calls f(data).
AddressPublisherFunc : AddressPublisher
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.
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.
*AddressLookupServices
AddressResolverFunc
*DNSAddressLookup
*MemoryLookup
*PkarrResolver
*StaticLookup
func (*AddressLookupServices).AddResolver(resolver AddressResolver)
AddressResolverFunc adapts a function to [AddressResolver].
Resolve calls f(ctx, id).
AddressResolverFunc : AddressResolver
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.
func NewFilteredAddressPublisher(inner AddressPublisher, f AddrFilter) FilteredAddressPublisher
func (*AddressLookupServices).SetAddrFilter(f AddrFilter)
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.
LocalCustomAddrs returns the local custom addresses this endpoint should
advertise. The returned slice is copied by the endpoint.
Send sends p to remote. local is nil when qng did not select a specific
local custom address for the path.
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.
AdvertisingCustomTransport : CustomTransport
ApplicationError is an application-defined connection close error.
Code is the application-defined close code.
Reason is the application-defined close reason.
Remote reports whether the peer sent the close.
Error returns a human-readable close error.
Unwrap returns [net.ErrClosed].
*ApplicationError : error
*ApplicationError : golang.org/x/xerrors.Wrapper
func AsApplicationError(err error) (*ApplicationError, bool)
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.
Select implements [PathSelector].
BiasedRttPathSelector : PathSelector
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".
IsDefaultRoute *bool
IsRequired bool
PrefixLen uint8
func WithBindAddrOpts(addr netip.AddrPort, opts BindOpts) Option
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].
ALPN returns the negotiated ALPN protocol. For a connection obtained from
[Accepting.Into0RTT] it is empty until the handshake completes.
AcceptStream accepts the next bidirectional stream opened by the peer.
AcceptStreamConn accepts the next bidirectional stream and returns it as a
[net.Conn].
AcceptUniStream accepts the next unidirectional stream opened by the peer.
Close closes the connection with application error code 0 and an empty
reason. Use [Conn.CloseWithError] to send an application-specific close code.
CloseWithError closes the connection with an application error code and
reason.
Context returns a context that is cancelled when the connection is closed.
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.
KeyExchangeGroup returns the TLS named group negotiated for this connection.
It is empty until the handshake completes.
LocalAddr returns the local transport address, if known.
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.
MultipathNegotiated reports whether both endpoints negotiated the QUIC
multipath extension on this connection.
OpenStreamConn opens a bidirectional stream and returns it as a [net.Conn].
OpenStreamSync opens a new bidirectional stream, blocking until the peer's
flow control permits it or ctx is done.
OpenUniStreamSync opens a new unidirectional (send) stream.
Paths returns a snapshot of the connection's currently open network paths.
ReadDatagram receives the next unreliable datagram.
RemoteAddr returns the remote transport address, if known.
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.
SendDatagram sends an unreliable datagram.
Side reports whether this connection was dialed or accepted.
StableID returns an endpoint-local identifier for this connection. It is
fixed for the connection lifetime, even when the transport path changes.
Stats returns a snapshot of connection statistics.
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.
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.
*Conn : github.com/prometheus/common/expfmt.Closer
*Conn : io.Closer
func (*Accepting).Connection(ctx context.Context) (*Conn, error)
func (*Accepting).Into0RTT() (*Conn, error)
func AcceptingHandler.OnAccepting(ctx context.Context, accepting *Accepting) (*Conn, error)
func (*Connecting).Connection(ctx context.Context) (*Conn, error)
func (*Connecting).Into0RTT() (conn *Conn, ok bool)
func (*Endpoint).Accept(ctx context.Context) (*Conn, error)
func (*Endpoint).Connect(ctx context.Context, addr netaddr.EndpointAddr, alpn string) (*Conn, error)
func EndpointHooks.AfterHandshake(ctx context.Context, conn *Conn) error
func ProtocolHandler.Accept(ctx context.Context, conn *Conn) error
func ProtocolHandlerFunc.Accept(ctx context.Context, conn *Conn) error
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.
ALPN returns the application protocol negotiated for the connection.
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.
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).
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.
func (*Endpoint).ConnectEarly(ctx context.Context, addr netaddr.EndpointAddr, alpn string) (*Connecting, error)
ConnStats is a snapshot of connection statistics.
BytesLost is the number of bytes lost on the underlying connection (does
not monotonically increase, because packets that are declared lost can
subsequently be received). Does not include UDP or any other outer
framing.
BytesReceived is the number of total bytes received on the underlying
connection, including duplicate data for streams. Does not include UDP or
any other outer framing.
BytesSent is the number of bytes sent on the underlying connection,
including retransmissions. Does not include UDP or any other outer
framing.
LatestRTT is the last RTT sample observed on the active network path.
MeanDeviation estimates the variation in the RTT samples using a mean
variation. See https://www.rfc-editor.org/rfc/rfc9002#section-5.3
MinRTT is the estimate of the minimum RTT observed on the active network
path.
PacketsLost is the number of packets lost on the underlying connection
(does not monotonically increase, because packets that are declared lost
can subsequently be received).
PacketsReceived is the number of total packets received on the underlying
connection, including packets that were not processable.
PacketsSent is the number of packets sent on the underlying connection,
including those that are determined to have been lost.
SmoothedRTT is an exponentially weighted moving average of an endpoint's
RTT samples. See https://www.rfc-editor.org/rfc/rfc9002#section-5.3
func (*Conn).Stats() ConnStats
CustomDatagram is one datagram received by a [CustomTransport].
Data []byte
HasLocal bool
Local netaddr.CustomAddr
Remote netaddr.CustomAddr
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.
Send sends p to remote. local is nil when qng did not select a specific
local custom address for the path.
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.
AdvertisingCustomTransport (interface)
func WithCustomTransport(t CustomTransport) Option
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.
Resolve looks up id in DNS, issuing staggered concurrent queries and yielding
the first successful result or an error.
*DNSAddressLookup : AddressResolver
func N0DNSAddressLookup(resolver *dns.Resolver) *DNSAddressLookup
func NewDNSAddressLookup(origin string, resolver *dns.Resolver) *DNSAddressLookup
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].
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.
AcceptIncoming blocks until an incoming connection attempt arrives. The
returned [Incoming] can be accepted, refused, retried, or ignored.
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.
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.
Closed returns a channel closed when the endpoint is closed.
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].
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.
Dial dials addr, negotiates alpn, opens a bidirectional stream, and returns it
as a [net.Conn].
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).
ID returns the endpoint's network identifier.
InsertRelay adds or replaces a relay server configuration. It returns the
previous config for url when one existed.
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].
LocalAddr returns the bound UDP address.
Metrics returns a point-in-time snapshot of endpoint counters.
NetReport returns the most recent network report applied to the endpoint.
The boolean result is false when no report has completed yet.
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).
RemoteInfo returns a snapshot of known addressing information for remote.
It returns false if the endpoint has no recent state for remote.
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.
RemoveRelay removes a relay server configuration. It returns the removed
config, or nil if url was not configured.
SecretKey returns the endpoint's secret key.
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].
Shutdown shuts down the endpoint: it stops accepting, closes the QUIC
transport, and releases the UDP socket. In-flight connections are not
forcibly closed.
WatchAddr returns a watcher over the endpoint's current advertised address.
It updates when local external NAT candidates are added or replaced.
func Bind(ctx context.Context, opts ...Option) (*Endpoint, error)
func (*Router).Endpoint() *Endpoint
func github.com/pancsta/asyncmachine-go/pkg/rpc/iroh.NewClient(ctx context.Context, irohAddr string, id string, netSrcSchema am.Schema, opts *iroh.ClientOpts) (*arpc.Client, *Endpoint, error)
func github.com/pancsta/asyncmachine-go/pkg/rpc/iroh.NewMux(ctx context.Context, addr string, name string, stateSource am.Api, opts *iroh.MuxOpts) (*arpc.Mux, *Endpoint, error)
func github.com/pancsta/asyncmachine-go/pkg/rpc/iroh.NewServer(ctx context.Context, addr string, name string, stateSource am.Api, opts *iroh.ServerOpts) (*arpc.Server, *Endpoint, error)
func NewRouter(ep *Endpoint, handlers map[string]ProtocolHandler, cfg *RouterConfig) (*Router, error)
EndpointHooks observes and can reject outbound dials and completed
handshakes.
( EndpointHooks) AfterHandshake(ctx context.Context, conn *Conn) error
( EndpointHooks) BeforeConnect(ctx context.Context, addr netaddr.EndpointAddr, alpn string) error
func WithHooks(h EndpointHooks) Option
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].
Inner returns the wrapped publisher.
Publish filters data and publishes it to the inner service.
FilteredAddressPublisher : AddressPublisher
func NewFilteredAddressPublisher(inner AddressPublisher, f AddrFilter) FilteredAddressPublisher
HandshakeRejectError rejects a completed handshake with an application close
code and reason.
Code uint64
Reason string
Error implements error.
*HandshakeRejectError : error
Incoming is an incoming connection attempt accepted by an [Endpoint]. Call
Accept to continue the handshake, or Refuse/Ignore to close it.
Accept accepts the incoming connection and returns an [Accepting] handle.
Ignore closes the incoming connection without waiting for completion.
LocalAddr returns the local transport address the incoming connection used.
Refuse closes the incoming connection.
RemoteAddr returns the transport address of the incoming connection.
RemoteAddrValidated reports whether qng has validated the remote address.
func (*Endpoint).AcceptIncoming(ctx context.Context) (*Incoming, error)
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).
IncomingFilterOutcome is the decision an [IncomingFilter] returns for an
incoming connection. It mirrors the Rust IncomingFilterOutcome
(iroh/src/protocol.rs).
const FilterAccept
const FilterIgnore
const FilterReject
const FilterRetry
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.
Addr converts the item into a [netaddr.EndpointAddr].
EndpointID returns the id of the discovered endpoint.
EndpointInfo returns the discovered endpoint info.
LastUpdated returns the time the source last updated this info, in
microseconds since the unix epoch, and whether the source tracks it.
LastUpdatedTime returns the time the source last updated this info, and
whether the source tracks it.
Provenance returns a stable string identifying the lookup source that
produced this item, such as "pkarr", "dns", or "memory_lookup".
UserData returns the discovered user data, if set.
func NewItem(info dns.EndpointInfo, provenance string, lastUpdated *uint64) Item
KeyExchangePolicy selects the TLS key-exchange groups offered by an
endpoint. The zero value uses the package default.
func WithKeyExchangePolicy(policy KeyExchangePolicy) Option
const KeyExchangeClassical
const KeyExchangeDefault
const KeyExchangePQOnly
const KeyExchangePreferPQ
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.
Err error
Provenance string
Error implements error.
Unwrap returns the wrapped error for use with [errors.Is] and [errors.As].
*LookupError : error
*LookupError : golang.org/x/xerrors.Wrapper
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.
AddEndpointAddr is a convenience wrapper for [MemoryLookup.AddEndpointInfo]
taking an [netaddr.EndpointAddr].
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.
GetEndpointInfo returns the stored info for id and whether it exists.
RemoveEndpointInfo removes and returns the info for id, and whether it
existed.
Resolve returns the stored info for id, or nil if there is no entry.
SetEndpointInfo replaces all stored info for info.ID, returning the previous
[dns.EndpointData] and whether an entry existed.
*MemoryLookup : AddressResolver
func MemoryLookupFromInfo(infos ...dns.EndpointInfo) *MemoryLookup
func NewMemoryLookup() *MemoryLookup
func NewMemoryLookupWithProvenance(provenance string) *MemoryLookup
Metrics is a snapshot of endpoint counters.
AcceptsAccepted uint64
AcceptsFailed uint64
AcceptsStarted uint64
ConnectsAccepted uint64
ConnectsFailed uint64
ConnectsStarted uint64
NetReport NetReportMetrics
Socket SocketMetrics
Snapshot returns m as named counter values for [metrics.Registry].
String implements expvar.Var, returning the metrics snapshot as JSON.
WriteOpenMetrics writes m in OpenMetrics text format under the "endpoint"
prefix.
Metrics : github.com/tmc/go-iroh/metrics.Source
Metrics : expvar.Var
Metrics : fmt.Stringer
func (*Endpoint).Metrics() Metrics
NetReport is the public snapshot of the endpoint's most recent network
report. The active probing client remains internal.
CaptivePortal reports whether a captive portal is intercepting HTTP, when
the check ran.
GlobalV4 is the host's public IPv4 address as seen by a relay.
GlobalV6 is the host's public IPv6 address as seen by a relay.
MappingVariesByDestV4 reports whether the observed public IPv4 address
differs across relays, when known.
MappingVariesByDestV6 reports whether the observed public IPv6 address
differs across relays, when known.
PreferredRelay is the relay with the best recent latency, chosen with
hysteresis. It is the zero RelayURL when no relay responded.
RelayLatencies is the lowest latency recorded for each relay.
UDPv4 reports whether a QAD IPv4 round trip completed and reported an
observed IPv4 address.
UDPv6 reports whether a QAD IPv6 round trip completed and reported an
observed IPv6 address.
HasUDP reports whether any QAD round trip succeeded.
func (*Endpoint).NetReport() (NetReport, bool)
NetReportMetrics is a snapshot of endpoint net_report counters.
PortmapAttempts uint64
PortmapExternalAddressUpdated uint64
Reports uint64
ReportsFailed uint64
ReportsFull uint64
Option configures an [Endpoint] at [Bind] time.
func WithAddressLookup(s *AddressLookupServices) Option
func WithALPNs(alpns ...string) Option
func WithBindAddr(addr netip.AddrPort) Option
func WithBindAddrOpts(addr netip.AddrPort, opts BindOpts) Option
func WithCustomTransport(t CustomTransport) Option
func WithDNSResolver(r *dns.Resolver) Option
func WithHooks(h EndpointHooks) Option
func WithKeyExchangePolicy(policy KeyExchangePolicy) Option
func WithKeyLogWriter(w io.Writer) Option
func WithNATPMP(gateway netip.Addr) Option
func WithNetReport() Option
func WithoutIPTransports() Option
func WithoutRelayTransports() Option
func WithPathSelector(selector PathSelector) Option
func WithRelayFirstDial() Option
func WithRelayMode(mode relay.Mode) Option
func WithSecretKey(sk key.SecretKey) Option
func WithSourceAddressValidation(f func(net.Addr) bool) Option
func WithTransportConfig(tc *QUICTransportConfig) Option
func Bind(ctx context.Context, opts ...Option) (*Endpoint, error)
PathCandidate is one path offered to a [PathSelector].
Addr is the path's transport address.
RTT is the smoothed round-trip time observed on the path.
func BiasedRttPathSelector.Select(current netaddr.TransportAddr, candidates []PathCandidate) (netaddr.TransportAddr, bool)
func PathSelector.Select(current netaddr.TransportAddr, candidates []PathCandidate) (selected netaddr.TransportAddr, ok bool)
PathInfo is a snapshot of one currently open network path for a connection.
Addr is the path's transport address, when HasAddr is true.
BytesInFlight is the path's current application-data bytes in flight,
when HasBytesInFlight is true.
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.
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.
CongestionWindow is the path's current congestion window, when
HasCongestionWindow is true.
HasAddr reports whether Addr is known.
HasBytesInFlight reports whether BytesInFlight was observed for this path.
HasBytesReceived reports whether BytesReceived was observed for this path.
HasBytesSent reports whether BytesSent was observed for this path.
HasCongestionWindow reports whether CongestionWindow was observed for this
path.
HasLoss reports whether LostPackets and LostBytes were observed for this
path.
HasRTT reports whether RTT was observed for this path.
ID is the QUIC multipath PathID when known. The initial path has ID 0.
LostBytes is the number of application-data bytes declared lost on this
path, when HasLoss is true.
LostPackets is the number of application-data packets declared lost on
this path, when HasLoss is true.
RTT is the path's smoothed round-trip time, when HasRTT is true.
Relayed reports whether this path uses a relay server.
Selected reports whether this path is currently selected for application
data transmission.
Validated reports whether the path can carry non-probing application data.
func (*Conn).Paths() []PathInfo
func (*Conn).WatchPaths(ctx context.Context) (<-chan []PathInfo, error)
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.
( PathSelector) Select(current netaddr.TransportAddr, candidates []PathCandidate) (selected netaddr.TransportAddr, ok bool)
BiasedRttPathSelector
func WithPathSelector(selector PathSelector) Option
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.
Close stops the background publish goroutine and waits for it to exit.
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.
*PkarrPublisher : AddressPublisher
*PkarrPublisher : github.com/prometheus/common/expfmt.Closer
*PkarrPublisher : io.Closer
func N0PkarrPublisher(secretKey key.SecretKey, cfg *PkarrPublisherConfig) (*PkarrPublisher, error)
func NewPkarrPublisher(secretKey key.SecretKey, relayURL string, cfg *PkarrPublisherConfig) (*PkarrPublisher, error)
PkarrPublisherConfig configures a [PkarrPublisher].
AddrFilter controls which addresses are published. If nil,
[RelayOnlyFilter] is used. Use a filter that returns its input unchanged
to publish all addresses.
HTTPClient is used for relay requests. If nil, a client with a per-request
timeout is used.
RepublishInterval is how often packets are republished even when
unchanged. If zero, [DefaultRepublishInterval] is used.
TTL is the record TTL, in seconds, of published packets. If zero,
[DefaultPkarrTTL] is used.
func N0PkarrPublisher(secretKey key.SecretKey, cfg *PkarrPublisherConfig) (*PkarrPublisher, error)
func NewPkarrPublisher(secretKey key.SecretKey, relayURL string, cfg *PkarrPublisherConfig) (*PkarrPublisher, error)
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.
Resolve fetches the signed packet for id from the pkarr relay and decodes its
endpoint info.
*PkarrResolver : AddressResolver
func N0PkarrResolver(cfg *PkarrResolverConfig) (*PkarrResolver, error)
func NewPkarrResolver(relayURL string, cfg *PkarrResolverConfig) (*PkarrResolver, error)
PkarrResolverConfig configures a [PkarrResolver].
HTTPClient is used for relay requests. If nil, a client with a per-request
timeout is used.
func N0PkarrResolver(cfg *PkarrResolverConfig) (*PkarrResolver, error)
func NewPkarrResolver(relayURL string, cfg *PkarrResolverConfig) (*PkarrResolver, 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).
Accept handles an accepted connection. ctx is cancelled when the router
shuts down.
ProtocolHandlerFunc
func (*StreamListener).Handler() ProtocolHandler
func NewRouter(ep *Endpoint, handlers map[string]ProtocolHandler, cfg *RouterConfig) (*Router, error)
ProtocolHandlerFunc adapts a function to [ProtocolHandler].
Accept calls f(ctx, conn).
ProtocolHandlerFunc : ProtocolHandler
QUICTransportConfig configures stable QUIC transport settings used by
endpoints. A zero field keeps the default.
InitialPacketSize is the initial QUIC packet size in bytes.
KeepAlivePeriod time.Duration
MaxIdleTimeout time.Duration
MaxIncomingStreams is the maximum number of concurrent bidirectional
streams accepted from a peer.
func WithTransportConfig(tc *QUICTransportConfig) Option
ReceiveStream is the receive half of a unidirectional stream.
CancelRead aborts receiving on s with code.
Read reads data from s.
SetReadDeadline sets the read deadline for s.
*ReceiveStream : github.com/pion/datachannel.ReadDeadliner
*ReceiveStream : io.Reader
func (*Conn).AcceptUniStream(ctx context.Context) (*ReceiveStream, error)
RelayConfig configures a relay server used by an endpoint.
RelayStatus is the connection status of the endpoint's home relay, observed
through [Endpoint.HomeRelayStatus].
RemoteInfo is a snapshot of known addressing information for a remote
endpoint.
Addrs []TransportAddrInfo
ID key.EndpointID
func (*Endpoint).RemoteInfo(remote key.EndpointID) (RemoteInfo, bool)
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.
Endpoint returns the endpoint the router accepts on.
IsShutdown reports whether the router has been shut down.
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).
func NewRouter(ep *Endpoint, handlers map[string]ProtocolHandler, cfg *RouterConfig) (*Router, error)
RouterConfig configures a [Router].
IncomingFilter is consulted for each incoming connection.
Logger records handler errors and recovered panics. If nil,
[slog.Default] is used.
func NewRouter(ep *Endpoint, handlers map[string]ProtocolHandler, cfg *RouterConfig) (*Router, error)
SendStream is the send half of a unidirectional stream.
CancelWrite aborts sending on s with code.
Close closes s.
Context is cancelled when s is closed.
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.
SetWriteDeadline sets the write deadline for s.
Write writes data to s.
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.
*SendStream : github.com/miekg/dns.Writer
*SendStream : github.com/pion/datachannel.WriteDeadliner
*SendStream : github.com/prometheus/common/expfmt.Closer
*SendStream : internal/bisect.Writer
*SendStream : io.Closer
*SendStream : io.ReaderFrom
*SendStream : io.WriteCloser
*SendStream : io.Writer
func (*Conn).OpenUniStreamSync(ctx context.Context) (*SendStream, error)
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].
Get implements [tls.ClientSessionCache]. It returns the cached session for
sessionKey, if any.
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.
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.
*SessionCache : github.com/tmc/go-iroh/internal/itls/tls.ClientSessionCache
func NewSessionCache() *SessionCache
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).
Shutdown is called once when the router is shutting down.
Side reports whether a [Conn] was dialed locally or accepted from a peer.
( Side) String() string
Side : expvar.Var
Side : fmt.Stringer
func (*Conn).Side() Side
const SideClient
const SideServer
SocketMetrics is a snapshot of endpoint magic-socket datagram counters.
ActorLinkChange uint64
HolepunchAttempts uint64
NumConnsClosed uint64
NumConnsDirect uint64
NumConnsOpened uint64
PathsCustom uint64
PathsDirect uint64
PathsRelay uint64
RecvDataCustom uint64
RecvDataIPv4 uint64
RecvDataIPv6 uint64
RecvDataRelay uint64
RecvDatagrams uint64
RelayHomeChange uint64
SendBlackholed uint64
SendCustom uint64
SendEndpointID uint64
SendIPv4 uint64
SendIPv6 uint64
SendRelay uint64
TransportCustomPathsAdded uint64
TransportCustomPathsRemoved uint64
TransportIPPathsAdded uint64
TransportIPPathsRemoved uint64
TransportRelayPathsAdded uint64
TransportRelayPathsRemoved uint64
UpdateDirectAddrs uint64
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.
Resolve returns the static info for id, or nil if there is no entry.
*StaticLookup : AddressResolver
func NewStaticLookup(infos ...dns.EndpointInfo) *StaticLookup
func NewStaticLookupWithProvenance(provenance string, infos ...dns.EndpointInfo) *StaticLookup
func StaticLookupFromAddrs(addrs ...netaddr.EndpointAddr) *StaticLookup
Stream is a bidirectional stream.
CancelRead aborts receiving on s with code.
CancelWrite aborts sending on s with code.
Close closes the send side of s.
Context is cancelled when s is closed.
Read reads data from s.
ReadFrom implements [io.ReaderFrom]. See [SendStream.ReadFrom].
SetDeadline sets the read and write deadlines for s.
SetReadDeadline sets the read deadline for s.
SetWriteDeadline sets the write deadline for s.
Write writes data to s.
Writev writes the buffers in order as one write episode.
See [SendStream.Writev].
*Stream : github.com/miekg/dns.Writer
*Stream : github.com/pion/datachannel.ReadDeadliner
*Stream : github.com/pion/datachannel.WriteDeadliner
*Stream : github.com/pion/stun.Connection
*Stream : github.com/pion/stun/v3.Connection
*Stream : github.com/prometheus/common/expfmt.Closer
*Stream : internal/bisect.Writer
*Stream : io.Closer
*Stream : io.ReadCloser
*Stream : io.Reader
*Stream : io.ReaderFrom
*Stream : io.ReadWriteCloser
*Stream : io.ReadWriter
*Stream : io.WriteCloser
*Stream : io.Writer
func (*Conn).AcceptStream(ctx context.Context) (*Stream, error)
func (*Conn).OpenStreamSync(ctx context.Context) (*Stream, error)
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.
Accept waits for and returns the next accepted bidirectional stream.
Addr returns the endpoint's local UDP address.
Close stops accepting new streams. It does not close the underlying endpoint.
Handler returns a [ProtocolHandler] that dispatches accepted connection
streams to l.
*StreamListener : github.com/prometheus/common/expfmt.Closer
*StreamListener : io.Closer
*StreamListener : net.Listener
func NewStreamListener() *StreamListener
func (*Endpoint).ListenStreams() (*StreamListener, error)
TransportAddrInfo is a remote transport address plus usage metadata.
Addr netaddr.TransportAddr
Provenance string
Usage TransportAddrUsage
TransportAddrUsage reports whether a remote transport address is active.
const TransportAddrActive
const TransportAddrInactive
Package-Level Functions (total 42)
AsApplicationError returns the application close error in err, if any.
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.
IPOnlyFilter keeps only direct IP and custom addresses, dropping relays.
MemoryLookupFromInfo returns a MemoryLookup pre-populated with infos.
N0DNSAddressLookup returns a DNSAddressLookup using the number0 production
discovery origin ([dns.N0DNSEndpointOriginProd]).
N0PkarrPublisher creates a publisher using the number0 production pkarr relay
([N0DNSPkarrRelayProd]).
N0PkarrResolver creates a resolver using the number0 production pkarr relay
([N0DNSPkarrRelayProd]).
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.
NewFilteredAddressPublisher wraps inner so that published data is filtered by
f before reaching inner.
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.
NewMemoryLookup returns an empty MemoryLookup using [MemoryProvenance].
NewMemoryLookupWithProvenance returns an empty MemoryLookup whose resolved
[Item]s report the given provenance.
NewPkarrPublisher creates a publisher that signs packets with secretKey,
publishes to the pkarr relay at relayURL, and starts its background publish
goroutine.
NewPkarrResolver creates a resolver that resolves from the pkarr relay at
relayURL.
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.
NewSessionCache returns a [SessionCache] that retains at most [maxTLSTickets]
tickets, evicting the least-recently-used entry when full.
NewStaticLookup returns a StaticLookup for infos using [StaticProvenance].
NewStaticLookupWithProvenance returns a StaticLookup for infos whose resolved
[Item]s report the given provenance.
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.
RejectHandshake rejects a completed handshake with code and reason.
RelayOnlyFilter keeps only relay addresses. It is the default filter for
[PkarrPublisher], avoiding leaking direct IP addresses to a public pkarr
relay.
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.
StaticLookupFromAddrs returns a StaticLookup for endpoint addresses using
[StaticProvenance].
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].
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.
WithBindAddr sets the local UDP address to bind. The default is an
OS-assigned port on the unspecified address.
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.
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.
WithDNSResolver configures DNS endpoint discovery through the number0
production origin. It is a convenience wrapper around [WithAddressLookup].
WithHooks registers endpoint hooks. Hooks run in registration order and may
reject outgoing dials or completed handshakes.
WithKeyExchangePolicy selects the TLS key-exchange groups used for direct
peer connections. The zero policy keeps the package default.
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.
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.
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.
WithoutIPTransports prevents the endpoint from binding, advertising, or
dialing direct IP addresses. Relay and custom transports still use the magic
connection machinery.
WithoutRelayTransports disables relay connectivity.
WithPathSelector sets the policy used to choose among candidate network paths
to a remote endpoint. When unset, the endpoint uses [BiasedRttPathSelector].
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.
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.
WithSecretKey sets the endpoint's identity. If unset, [Bind] generates a
random key.
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.
WithTransportConfig overrides stable QUIC transport settings. Unsupported
qng internals remain private to the endpoint.
Package-Level Variables (total 10)
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.
ErrConnectRejected is returned when an endpoint hook rejects a dial before
any packet is sent.
ErrEndpointAcceptLoopInUse is returned when an operation would start or
reconfigure an endpoint accept loop while another accept owner is active.
ErrEndpointClosed is returned by operations on a closed [Endpoint].
ErrHandshakeRejected is returned when an endpoint hook rejects a completed
handshake.
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).
ErrNoRelay is returned by [Endpoint.Online] when the endpoint has no relays
configured (relays disabled), so it can never come online via a relay.
ErrNoResults is reported when every configured service finished without
yielding an item. The per-service errors, if any, are joined into it.
ErrNoServiceConfigured is reported when resolution is attempted with no
services registered.
ErrSelfConnect is returned by [Endpoint.Connect] when asked to dial the
endpoint's own id.
Package-Level Constants (total 27)
ConnectTimeout bounds a single Connect call when no reachable address
succeeds. iroh/src/endpoint.rs documents a 10s connect timeout.
DefaultPkarrTTL is the default record TTL, in seconds, of published pkarr
signed packets.
DefaultRepublishInterval is how often the publisher republishes the
endpoint info even when unchanged.
DNSProvenance is the provenance string for [DNSAddressLookup] items.
FilterAccept accepts the connection and dispatches it to a handler.
FilterIgnore closes the incoming connection without dispatching it.
FilterReject refuses the connection.
FilterRetry asks the peer to retry. Router evaluates this outcome before
qng constructs a connection, so it emits a real QUIC Retry packet.
HeartbeatInterval is the QUIC keep-alive / path keep-alive interval.
iroh/src/socket.rs HEARTBEAT_INTERVAL.
KeyExchangeClassical disables post-quantum key exchange.
KeyExchangeDefault uses the package default key-exchange groups.
KeyExchangePQOnly requires X25519MLKEM768.
KeyExchangePreferPQ prefers X25519MLKEM768 and retains classical fallback.
MaxMultipathPaths is the QUIC multipath path limit (transport parameter).
iroh/src/socket.rs MAX_MULTIPATH_PATHS.
MaxQNTAddresses is the maximum number of remote NAT-traversal addresses
(transport parameter). iroh/src/socket.rs MAX_QNT_ADDRESSES.
MemoryProvenance is the default provenance string for [MemoryLookup] items.
N0DNSPkarrRelayProd is the number0 production pkarr relay, which also
serves the records over DNS.
N0DNSPkarrRelayStaging is the number0 staging pkarr relay.
NetReportTimeout is the timeout for a complete network report.
PathMaxIdleTimeout is the idle timeout for a non-relay (direct) path.
iroh/src/socket.rs PATH_MAX_IDLE_TIMEOUT.
PkarrProvenance is the provenance string for [PkarrResolver] items.
RelayPathMaxIdleTimeout is the idle timeout for a relay path.
iroh/src/socket.rs RELAY_PATH_MAX_IDLE_TIMEOUT.
SideClient is a connection this endpoint dialed.
SideServer is a connection this endpoint accepted.
StaticProvenance is the default provenance string for [StaticLookup] items.
TransportAddrActive means the address is currently used.
TransportAddrInactive means the address is known but not currently used.
![]() |
The pages are generated with Golds v0.8.4. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds. |