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).
Tracing ¶
Every endpoint installs the qlog connection tracer, so setting the QLOGDIR environment variable records a qlog trace of each QUIC connection the process opens or accepts, with no code change. Each connection writes <odcid>_client.sqlog or <odcid>_server.sqlog under that directory, in JSON-seq; the two ends of one connection share the original destination connection id. Traces carry frame metadata, loss and congestion events, and the handshake, but no payload bytes. QLOGDIR is process-wide, so several endpoints in one process interleave their traces in one directory; WithQLOG replaces it for a single endpoint, and QLOGDir reproduces its file layout.
To see payload bytes, log the TLS traffic secrets with WithKeyLogWriter, capture the UDP flow, and decrypt the capture with Wireshark. Writing those secrets compromises the confidentiality of every connection the endpoint makes, so it is a debugging tool only. Relayed traffic, 0-RTT early data, and the reverse direction after a connection-id rotation are not covered.
The Go API is not stable before v1 and may change in any v0 release.
Index ¶
- Constants
- Variables
- func IPOnlyFilter(addrs []netaddr.TransportAddr) []netaddr.TransportAddr
- func QLOGDir(dir string) func(context.Context, QLOGConnection) io.WriteCloser
- func RejectHandshake(code uint64, reason string) error
- func RelayOnlyFilter(addrs []netaddr.TransportAddr) []netaddr.TransportAddr
- func ServerName(id key.EndpointID) string
- type Accepting
- type AcceptingHandler
- type AddrFilter
- type AddressLookupServices
- func (s *AddressLookupServices) AddPublisher(publisher AddressPublisher)
- func (s *AddressLookupServices) AddResolver(resolver AddressResolver)
- func (s *AddressLookupServices) Clear()
- func (s *AddressLookupServices) IsEmpty() bool
- func (s *AddressLookupServices) Len() int
- func (s *AddressLookupServices) Publish(data dns.EndpointData)
- func (s *AddressLookupServices) Resolve(ctx context.Context, id key.EndpointID) iter.Seq2[Item, error]
- func (s *AddressLookupServices) SetAddrFilter(f AddrFilter)
- type AddressPublisher
- type AddressPublisherFunc
- type AddressResolver
- type AddressResolverFunc
- type AdvertisingCustomTransport
- type ApplicationError
- type BiasedRttPathSelector
- type BindOpts
- type Conn
- func (c *Conn) ALPN() string
- func (c *Conn) AcceptStream(ctx context.Context) (*Stream, error)
- func (c *Conn) AcceptStreamConn(ctx context.Context) (net.Conn, error)
- func (c *Conn) AcceptUniStream(ctx context.Context) (*ReceiveStream, error)
- func (c *Conn) Close() error
- func (c *Conn) CloseWithError(code uint64, reason string) error
- func (c *Conn) Context() context.Context
- func (c *Conn) HandshakeComplete() <-chan struct{}
- func (c *Conn) KeyExchangeGroup() string
- func (c *Conn) LocalAddr() net.Addr
- func (c *Conn) MaxDatagramSize() (n int, ok bool)
- func (c *Conn) MultipathNegotiated() bool
- func (c *Conn) OpenStreamConn(ctx context.Context) (net.Conn, error)
- func (c *Conn) OpenStreamSync(ctx context.Context) (*Stream, error)
- func (c *Conn) OpenUniStreamSync(ctx context.Context) (*SendStream, error)
- func (c *Conn) Paths() []PathInfo
- func (c *Conn) ReadDatagram(ctx context.Context) ([]byte, error)
- func (c *Conn) RemoteAddr() net.Addr
- func (c *Conn) RemoteID() key.EndpointID
- func (c *Conn) SendDatagram(b []byte) error
- func (c *Conn) Side() Side
- func (c *Conn) StableID() uint64
- func (c *Conn) Stats() ConnStats
- func (c *Conn) Used0RTT() bool
- func (c *Conn) WatchPaths(ctx context.Context) (<-chan []PathInfo, error)
- type ConnStats
- type Connecting
- type CustomDatagram
- type CustomTransport
- type DNSAddressLookup
- type Endpoint
- func (e *Endpoint) Accept(ctx context.Context) (*Conn, error)
- func (e *Endpoint) AcceptIncoming(ctx context.Context) (*Incoming, error)
- func (e *Endpoint) AddExternalAddr(addr netip.AddrPort)
- func (e *Endpoint) Addr() netaddr.EndpointAddr
- func (e *Endpoint) Closed() <-chan struct{}
- func (e *Endpoint) Connect(ctx context.Context, addr netaddr.EndpointAddr, alpn string) (*Conn, error)
- func (e *Endpoint) ConnectEarly(ctx context.Context, addr netaddr.EndpointAddr, alpn string) (*Connecting, error)
- func (e *Endpoint) Dial(ctx context.Context, addr netaddr.EndpointAddr, alpn string) (net.Conn, error)
- func (e *Endpoint) HomeRelayStatus() watch.Observer[*RelayStatus]
- func (e *Endpoint) ID() key.EndpointID
- func (e *Endpoint) InsertRelay(url netaddr.RelayURL, cfg *RelayConfig) (*RelayConfig, error)
- func (e *Endpoint) ListenStreams() (*StreamListener, error)
- func (e *Endpoint) LocalAddr() netip.AddrPort
- func (e *Endpoint) Metrics() Metrics
- func (e *Endpoint) NetReport() (NetReport, bool)
- func (e *Endpoint) Online(ctx context.Context) error
- func (e *Endpoint) RemoteInfo(remote key.EndpointID) (RemoteInfo, bool)
- func (e *Endpoint) RemoveExternalAddr(addr netip.AddrPort) bool
- func (e *Endpoint) RemoveRelay(url netaddr.RelayURL) *RelayConfig
- func (e *Endpoint) SecretKey() key.SecretKey
- func (e *Endpoint) SetALPNs(alpns []string) error
- func (e *Endpoint) Shutdown(ctx context.Context) error
- func (e *Endpoint) WatchAddr() watch.Observer[netaddr.EndpointAddr]
- type EndpointHooks
- type FilteredAddressPublisher
- type HandshakeRejectError
- type Incoming
- type IncomingFilter
- type IncomingFilterOutcome
- type Item
- func (i Item) Addr() netaddr.EndpointAddr
- func (i Item) EndpointID() key.EndpointID
- func (i Item) EndpointInfo() dns.EndpointInfo
- func (i Item) LastUpdated() (uint64, bool)
- func (i Item) LastUpdatedTime() (time.Time, bool)
- func (i Item) Provenance() string
- func (i Item) UserData() (dns.UserData, bool)
- type KeyExchangePolicy
- type LookupError
- type MemoryLookup
- func (m *MemoryLookup) AddEndpointAddr(addr netaddr.EndpointAddr)
- func (m *MemoryLookup) AddEndpointInfo(info dns.EndpointInfo)
- func (m *MemoryLookup) GetEndpointInfo(id key.EndpointID) (dns.EndpointInfo, bool)
- func (m *MemoryLookup) RemoveEndpointInfo(id key.EndpointID) (dns.EndpointInfo, bool)
- func (m *MemoryLookup) Resolve(ctx context.Context, id key.EndpointID) iter.Seq2[Item, error]
- func (m *MemoryLookup) SetEndpointInfo(info dns.EndpointInfo) (dns.EndpointData, bool)
- type Metrics
- type NetReport
- type NetReportMetrics
- type Option
- func WithALPNs(alpns ...string) Option
- func WithAddressLookup(s *AddressLookupServices) 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() Optiondeprecated
- func WithPathSelector(selector PathSelector) Option
- func WithQLOG(sink func(context.Context, QLOGConnection) io.WriteCloser) 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 WithoutIPTransports() Option
- func WithoutNetReport() Option
- func WithoutRelayTransports() Option
- type PathCandidate
- type PathInfo
- type PathSelector
- type PkarrPublisher
- type PkarrPublisherConfig
- type PkarrResolver
- type PkarrResolverConfig
- type ProtocolHandler
- type ProtocolHandlerFunc
- type QLOGConnection
- type QUICTransportConfig
- type ReceiveStream
- type RelayConfig
- type RelayStatus
- type RemoteInfo
- type Router
- type RouterConfig
- type SendStream
- func (s *SendStream) CancelWrite(code uint64)
- func (s *SendStream) Close() error
- func (s *SendStream) Context() context.Context
- func (s *SendStream) ReadFrom(r io.Reader) (int64, error)
- func (s *SendStream) SetWriteDeadline(t time.Time) error
- func (s *SendStream) Write(p []byte) (int, error)
- func (s *SendStream) Writev(bufs *net.Buffers) (int64, error)
- type SessionCache
- type ShutdownHandler
- type Side
- type SocketMetrics
- type StaticLookup
- type Stream
- func (s *Stream) CancelRead(code uint64)
- func (s *Stream) CancelWrite(code uint64)
- func (s *Stream) Close() error
- func (s *Stream) CloseWrite() error
- func (s *Stream) Context() context.Context
- func (s *Stream) Read(p []byte) (int, error)
- func (s *Stream) ReadFrom(r io.Reader) (int64, error)
- func (s *Stream) SetDeadline(t time.Time) error
- func (s *Stream) SetReadDeadline(t time.Time) error
- func (s *Stream) SetWriteDeadline(t time.Time) error
- func (s *Stream) Write(p []byte) (int, error)
- func (s *Stream) Writev(bufs *net.Buffers) (int64, error)
- type StreamListener
- type TransportAddrInfo
- type TransportAddrUsage
Examples ¶
Constants ¶
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.
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 )
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.
const DNSProvenance = "dns"
DNSProvenance is the provenance string for DNSAddressLookup items.
const MemoryProvenance = "memory_lookup"
MemoryProvenance is the default provenance string for MemoryLookup items.
const NetReportTimeout = 5 * time.Second
NetReportTimeout is the timeout for a complete network report.
const PkarrProvenance = "pkarr"
PkarrProvenance is the provenance string for PkarrResolver items.
const StaticProvenance = "static_lookup"
StaticProvenance is the default provenance string for StaticLookup items.
Variables ¶
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.
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.
var ErrConnectRejected = errors.New("iroh: connect rejected by hook")
ErrConnectRejected is returned when an endpoint hook rejects a dial before any packet is sent.
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.
var ErrEndpointClosed = errors.New("iroh: endpoint closed")
ErrEndpointClosed is returned by operations on a closed Endpoint.
var ErrHandshakeRejected = errors.New("iroh: handshake rejected by hook")
ErrHandshakeRejected is returned when an endpoint hook rejects a completed handshake.
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).
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.
var ErrSelfConnect = errors.New("iroh: cannot connect to self")
ErrSelfConnect is returned by Endpoint.Connect when asked to dial the endpoint's own id.
var ErrTLSHandshakeFailure = errors.New("iroh: tls handshake failure")
ErrTLSHandshakeFailure reports a QUIC handshake that ended in the TLS "handshake_failure" alert (alert 40), which a peer sends when it finds no acceptable set of handshake parameters. Between iroh endpoints the cause is a key-exchange group mismatch: the two KeyExchangePolicy values have no group in common, so neither side can complete the exchange. The cipher suite and the raw-public-key signature algorithm are fixed by the protocol and never differ between iroh peers; a peer running another implementation may send the same alert for another reason.
Endpoint.Connect and Endpoint.Dial wrap such a failure so it can be told apart from other handshake failures without matching error text:
if _, err := ep.Connect(ctx, addr, alpn); errors.Is(err, iroh.ErrTLSHandshakeFailure) {
// no key exchange group in common; see WithKeyExchangePolicy
}
The alert is symmetric: the dialer sees it whether its own policy or the peer's was the narrower one.
Functions ¶
func IPOnlyFilter ¶
func IPOnlyFilter(addrs []netaddr.TransportAddr) []netaddr.TransportAddr
IPOnlyFilter drops relay addresses and keeps everything else. Despite the name it is not an IP allowlist: netaddr.CustomAddr transport addresses are kept too, because IPOnlyFilter is defined as the exact complement of RelayOnlyFilter.
A caller filtering for privacy should read this as "no relays". To publish nothing but IP addresses, write a filter that tests for netaddr.IPAddr positively.
func QLOGDir ¶ added in v0.1.1
func QLOGDir(dir string) func(context.Context, QLOGConnection) io.WriteCloser
QLOGDir returns a WithQLOG sink that writes <connection id>_<client|server>.sqlog files in dir, the layout QLOGDIR produces. It creates dir if needed, and traces nothing it cannot write.
Example ¶
ExampleQLOGDir installs a per-endpoint qlog sink. The same sink can be passed to several endpoints when their traces belong in one directory.
package main
import (
"context"
"fmt"
"io"
"os"
"github.com/tmc/go-iroh/iroh"
)
func main() {
dir, err := os.MkdirTemp("", "iroh-qlog-")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
sink := iroh.QLOGDir(dir)
w := sink(context.Background(), iroh.QLOGConnection{
ConnectionID: "0102",
Client: true,
})
if w == nil {
panic("create qlog")
}
if _, err := io.WriteString(w, "trace"); err != nil {
panic(err)
}
if err := w.Close(); err != nil {
panic(err)
}
entries, err := os.ReadDir(dir)
if err != nil {
panic(err)
}
fmt.Println(entries[0].Name())
}
Output: 0102_client.sqlog
func RejectHandshake ¶
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) Connection ¶
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 ¶
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 ¶
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 ¶
func (s *AddressLookupServices) Resolve(ctx context.Context, id key.EndpointID) iter.Seq2[Item, error]
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. Implementations should return an empty sequence rather
// than nil when there is nothing to report; callers must tolerate nil.
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 ¶
AddressResolverFunc adapts a function to AddressResolver.
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 ¶
func (BiasedRttPathSelector) Select(current netaddr.TransportAddr, candidates []PathCandidate) (netaddr.TransportAddr, bool)
Select implements PathSelector.
type BindOpts ¶
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 ¶
ALPN returns the negotiated ALPN protocol. For a connection obtained from Accepting.Into0RTT it is empty until the handshake completes.
func (*Conn) AcceptStream ¶
AcceptStream accepts the next bidirectional stream opened by the peer.
func (*Conn) AcceptStreamConn ¶
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 ¶
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 ¶
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) 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 ¶
KeyExchangeGroup returns the TLS named group negotiated for this connection. It is empty until the handshake completes.
func (*Conn) MaxDatagramSize ¶
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 ¶
MultipathNegotiated reports whether both endpoints negotiated the QUIC multipath extension on this connection.
func (*Conn) OpenStreamConn ¶
OpenStreamConn opens a bidirectional stream and returns it as a net.Conn.
func (*Conn) OpenStreamSync ¶
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 ¶
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 ¶
ReadDatagram receives the next unreliable datagram.
func (*Conn) RemoteAddr ¶
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 ¶
SendDatagram sends an unreliable datagram.
func (*Conn) StableID ¶
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 ¶
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 ¶
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 ¶
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, passing each received
// datagram to recv.
//
// recv reports whether the datagram was taken. A false result means the
// datagram was dropped, most often because the receive queue was full
// under a burst; it is not a signal to stop. Serve must keep serving and
// return only when ctx is done, so `if !recv(d) { return }` tears the
// transport down on the first burst. Shutdown is reported through ctx
// alone, which is cancelled before the queue stops being drained.
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.
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 ¶
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 ¶
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 ¶
AcceptIncoming blocks until an incoming connection attempt arrives. The returned Incoming can be accepted, refused, retried, or ignored.
func (*Endpoint) AddExternalAddr ¶
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.
When addr carries no usable address at all - a dial by endpoint ID alone - Connect resolves one through the services given to WithAddressLookup and dials the first answer that has any. Such a call waits on the lookup, so it blocks where it would once have failed at once; it still returns ErrNoAddress when no service is configured or none answers before the deadline. Connect does not consult the lookup when addr already has an address, even if none of them work.
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.
Example (AddressLookup) ¶
ExampleEndpoint_Connect_addressLookup dials a peer using only its endpoint ID after an address lookup service supplies its transport 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/address-lookup/1"
server, err := iroh.Bind(ctx,
iroh.WithALPNs(alpn),
iroh.WithBindAddr(netip.AddrPortFrom(netip.IPv6Loopback(), 0)),
)
if err != nil {
panic(err)
}
defer server.Shutdown(ctx)
lookup := iroh.NewMemoryLookup()
lookup.AddEndpointAddr(netaddr.NewEndpointAddr(server.ID()).WithIP(server.LocalAddr()))
var services iroh.AddressLookupServices
services.AddResolver(lookup)
client, err := iroh.Bind(ctx,
iroh.WithAddressLookup(&services),
iroh.WithBindAddr(netip.AddrPortFrom(netip.IPv6Loopback(), 0)),
)
if err != nil {
panic(err)
}
defer client.Shutdown(ctx)
accepted := make(chan *iroh.Conn, 1)
go func() {
conn, err := server.Accept(ctx)
if err != nil {
close(accepted)
return
}
accepted <- conn
}()
conn, err := client.Connect(ctx, netaddr.NewEndpointAddr(server.ID()), alpn)
if err != nil {
panic(err)
}
defer conn.CloseWithError(0, "")
if server := <-accepted; server != nil {
defer server.CloseWithError(0, "")
}
fmt.Println(conn.RemoteID() == server.ID())
}
Output: true
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)
}
}
Output:
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 ¶
LocalAddr returns the bound UDP address, as reported by the socket. For a dual-stack socket that is an IPv6 address whatever WithBindAddr was given; see WithBindAddr for which bind addresses are dual-stack.
func (*Endpoint) NetReport ¶
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 ¶
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)
}
Output:
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 ¶
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) SetALPNs ¶
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.
type EndpointHooks ¶
type EndpointHooks interface {
// BeforeConnect runs before an outbound dial. Returning an error abandons
// the dial and the error reaches the caller of [Endpoint.Connect]. It does
// not run for accepted connections.
BeforeConnect(ctx context.Context, addr netaddr.EndpointAddr, alpn string) error
// AfterHandshake runs once for every connection the endpoint establishes,
// dialed and accepted alike; [Conn.Side] distinguishes them. A hook
// installed on a server therefore fires for connections it never dialed.
// Returning an error closes the connection; use [RejectHandshake] to pick
// the close code and reason.
//
// On the ordinary paths it runs on the goroutine that is establishing the
// connection, with that caller's context. On the 0-RTT paths
// ([Connecting.Into0RTT] and early-data accepts) the handshake
// completes after the connection is already in use, so AfterHandshake runs
// on a separate goroutine with a background context: a hook that touches
// shared state must be safe for concurrent use.
AfterHandshake(ctx context.Context, conn *Conn) error
}
EndpointHooks observes and can reject an endpoint's outbound dials and its 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 ¶
func (f FilteredAddressPublisher) Inner() AddressPublisher
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 ¶
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) Ignore ¶
func (in *Incoming) Ignore()
Ignore closes the incoming connection without waiting for completion.
func (*Incoming) LocalAddr ¶
LocalAddr returns the local transport address the incoming connection used.
func (*Incoming) RemoteAddr ¶
RemoteAddr returns the transport address of the incoming connection.
func (*Incoming) RemoteAddrValidated ¶
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 ¶
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 ¶
LastUpdatedTime returns the time the source last updated this info, and whether the source tracks it.
func (Item) Provenance ¶
Provenance returns a stable string identifying the lookup source that produced this item, such as "pkarr", "dns", or "memory_lookup".
func (Item) UserData ¶
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 ¶
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.
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 an empty sequence 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 ¶
Snapshot returns m as named counter values for metrics.Registry.
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.
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 ¶
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, and Endpoint.Connect consults them to seed a dial by endpoint ID alone. When unset, the endpoint does no lookup-driven address resolution and connects only to the addresses passed to Connect.
func WithBindAddr ¶
WithBindAddr sets the local UDP address to bind. The default is an OS-assigned port on the IPv6 unspecified address, which the OS gives a dual-stack socket.
An IPv4 address, 0.0.0.0 included, binds an IPv4-only socket, so the endpoint reaches IPv4 peers only and Endpoint.LocalAddr reports the family that was asked for. Pass an IPv6 address, or nothing, for dual-stack.
func WithBindAddrOpts ¶
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 ¶
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.
Both peers must offer a group the other accepts. A dial to a peer with no group in common fails with ErrTLSHandshakeFailure, whichever side's policy is the narrower one.
func WithKeyLogWriter ¶
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 ¶
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
deprecated
func WithNetReport() Option
WithNetReport enables background net_report refreshes after Bind.
Deprecated: net_report runs by default whenever relays are configured. Use WithoutNetReport to turn it off.
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 WithQLOG ¶ added in v0.1.1
func WithQLOG(sink func(context.Context, QLOGConnection) io.WriteCloser) Option
WithQLOG sends this endpoint's qlog traces to sink instead of to the directory named by the QLOGDIR environment variable. sink is called once per connection, before the handshake; returning nil traces that connection not at all. The returned writer receives one JSON-seq qlog trace and is closed once, when the connection ends.
The environment variable is process-wide, so several endpoints in one process interleave their traces in one directory keyed only by connection id. A sink is per-endpoint: give each one its own directory with QLOGDir, or its own io.WriteCloser to route traces anywhere. QLOGDIR still applies to endpoints that install no sink.
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 ¶
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 ¶
WithSecretKey sets the endpoint's identity. If unset, Bind generates a random key.
func WithSourceAddressValidation ¶
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 WithoutNetReport ¶ added in v0.2.0
func WithoutNetReport() Option
WithoutNetReport disables background net_report refreshes.
net_report measures relay latency and reports the QAD-derived global addresses that are advertised as local QNT candidates for active remotes. Without it the home relay stays whichever relay Bind picked to bootstrap with, which is the first in the relay map rather than the nearest one, and Endpoint.NetReport never reports a measurement.
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.
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 ¶
ProtocolHandlerFunc adapts a function to ProtocolHandler.
type QLOGConnection ¶ added in v0.1.1
type QLOGConnection struct {
// ConnectionID is the original destination connection ID, lowercase hex.
// It is the stem QLOGDIR uses for the trace's file name, so its exact
// form is part of this API.
ConnectionID string
// Client reports whether this endpoint dialed the connection.
Client bool
}
QLOGConnection identifies the connection a qlog trace belongs to. It is passed to the sink installed by WithQLOG.
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 ¶
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"))
// CloseWrite tells the server that the request is complete while leaving
// the read side open for its response.
s.CloseWrite()
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, so it must not have an accept loop of its own; see Endpoint.Accept.
The router replaces the endpoint's accepted ALPN set with the handler keys. Passing WithALPNs to Bind is therefore only useful as a subset of them: NewRouter returns an error naming any ALPN the endpoint was bound with that has no handler, rather than negotiating a protocol it cannot dispatch. A router with more ALPNs than the endpoint was bound with is fine and widens the set.
The rule is about what Bind was given, not about what the endpoint accepts at the time. Endpoint.SetALPNs documents that it replaces the accepted set, so a router replacing it again is that contract, not a mistake.
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) IsShutdown ¶
IsShutdown reports whether the router has been shut down.
func (*Router) Shutdown ¶
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) 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 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.
type Stream ¶
type Stream struct {
// contains filtered or unexported fields
}
Stream is a bidirectional stream.
func (*Stream) CancelRead ¶
CancelRead aborts receiving on s with code.
func (*Stream) CancelWrite ¶
CancelWrite aborts sending on s with code.
func (*Stream) CloseWrite ¶ added in v0.1.1
CloseWrite closes the send side of s, leaving the receive side open so the peer's reply can still be read. It does exactly what Stream.Close does, under the name the io half-close convention uses, so that a Stream satisfies interfaces that probe for CloseWrite.
func (*Stream) ReadFrom ¶ added in v0.0.2
ReadFrom implements io.ReaderFrom. See SendStream.ReadFrom.
func (*Stream) SetDeadline ¶
SetDeadline sets the read and write deadlines for s.
func (*Stream) SetReadDeadline ¶
SetReadDeadline sets the read deadline for s.
func (*Stream) SetWriteDeadline ¶
SetWriteDeadline sets the write deadline for s.
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 )