transport

package
v0.0.0-...-de45444 Latest Latest
Warning

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

Go to latest
Published: Jun 17, 2026 License: MIT Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ReconnectMaxRetries = 3
	ReconnectBaseDelay  = 2 * time.Second
	CachedLookupMaxAge  = 1 * time.Hour
)

Reconnection tuning constants.

View Source
const CapDirectSimultaneousOpen = "direct-simultaneous-open"

CapDirectSimultaneousOpen is the capability token a peer advertises to say it can take part in the coordinated simultaneous-open hole punch. Both sides must advertise it for the dance to proceed.

View Source
const (
	// StreamTimeout is the default deadline for stream operations.
	StreamTimeout = 30 * time.Second
)

Variables

This section is empty.

Functions

func ReadAll

func ReadAll(s network.Stream, maxBytes int) ([]byte, error)

ReadAll reads the full contents from a stream up to maxBytes.

func ReadFramed

func ReadFramed(s Stream, timeout time.Duration) (*pb.Envelope, error)

ReadFramed sets the read deadline and reads one framed envelope from s, resetting the stream on failure. Note the inbound Demux deliberately does NOT use this — it lets a read error fall through to its deferred Close rather than resetting, matching the pre-refactor controlStreamHandler.

func SetAllowLocalDialTargets

func SetAllowLocalDialTargets(allow bool)

SetAllowLocalDialTargets enables (LAN backends) or disables (Tor) dialing local-segment peer addresses. The daemon calls it once at startup from the signaling-backend choice.

func WriteFramed

func WriteFramed(s Stream, timeout time.Duration, env *pb.Envelope) error

WriteFramed sets the write deadline and writes one framed envelope to s, resetting the stream on failure. It centralises the deadline+write+reset discipline the chat send, presence ping, and rpc send paths each open-coded. The timeout is a parameter because callers differ (presence uses a short ping timeout, others StreamTimeout). The returned error is unwrapped — callers add their own context.

Types

type ConnState

type ConnState int

ConnState represents the state of a peer connection.

const (
	StateDiscovering   ConnState = iota // looking up peer in DHT/mDNS
	StateSignaling                      // 3-step handshake over Tor
	StateExchangingIPs                  // encrypted IP swap
	StateNATTraversal                   // attempting direct connection
	StateConnected                      // direct QUIC connection
	StateConnectedTor                   // Tor-only fallback
	StateDisconnected                   // cleanly disconnected
	StateFailed                         // connection attempt failed
	StateReconnecting                   // auto-reconnecting after loss
)

func (ConnState) String

func (s ConnState) String() string

type Connector

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

Connector manages the full peer connection lifecycle.

func NewConnector

func NewConnector(cfg ConnectorConfig) *Connector

NewConnector creates a connection orchestrator.

func (*Connector) AcquireTransferSlot

func (c *Connector) AcquireTransferSlot() bool

AcquireTransferSlot tries to acquire a concurrent transfer slot. Returns false if the limit is reached.

func (*Connector) ActivePeers

func (c *Connector) ActivePeers() []*PeerConnection

ActivePeers returns all active (connected) peers.

func (*Connector) ActiveTransfers

func (c *Connector) ActiveTransfers() int

ActiveTransfers returns the number of in-flight file transfers.

func (*Connector) AllPeers

func (c *Connector) AllPeers() []*PeerConnection

AllPeers returns a copy of every tracked peer connection regardless of state — connected, in-flight (a dial currently in connectFlow), and failed reconnects. The unified peers list (ADR-0004) needs the non-connected entries too, so a contact mid-dial shows "connecting" and a dead one shows "failed" instead of vanishing. Note this still only covers peers THIS node dialed (plus MarkDirectUpgrade); inbound Tor peers live in ControlRegistry.

func (*Connector) Connect

func (c *Connector) Connect(ctx context.Context, peerAddr string) (*PeerConnection, error)

Connect initiates the full connection flow to a peer, signed with the node identity. Discovery → Signaling → IP Exchange → NAT Traversal → Connected.

func (*Connector) ConnectAs

func (c *Connector) ConnectAs(ctx context.Context, peerAddr, serviceAddr string, serviceID *identity.Identity, serviceBinding *identity.Binding) (*PeerConnection, error)

ConnectAs initiates the full connection flow to a peer, signing the signaling handshake with a SERVICE identity (serviceAddr + serviceKP) instead of the node identity. Everything else — discovery, the libp2p host, the shipped node peer ID, NAT traversal — is identical to Connect. The responder's gate therefore sees serviceAddr as CONN_REQUEST.FromAddress. Ticket 5fb8deb1.

Caveat: auto-reconnect (StartAutoReconnect → ReconnectWithFallback) re-dials with the NODE identity, so a dropped service-identity connection that gets auto-reconnected would re-present the node address to the responder gate. For the introduced-peer use case the connection is short-lived and this is acceptable; per-peer dial-identity persistence is a documented follow-up.

func (*Connector) DemoteToTor

func (c *Connector) DemoteToTor(peerAddr string)

DemoteToTor flips a peer's data path from a direct connection back to its Tor control channel — the inverse of MarkDirectUpgrade. The auto-reconnect watchdog calls it when a direct link drops but the held Tor circuit is still alive: chat and presence go back to riding the control channel and the connection stays up, instead of a destructive re-handshake. No-op if the peer is unknown or already tor-only. See ticket 00c477e3 slice 3.

func (*Connector) Disconnect

func (c *Connector) Disconnect(peerAddr string)

Disconnect closes the connection to a peer.

func (*Connector) GetPeer

func (c *Connector) GetPeer(addr string) *PeerConnection

GetPeer returns the current state of a peer connection.

func (*Connector) MarkDirectUpgrade

func (c *Connector) MarkDirectUpgrade(peerAddr, peerID string)

MarkDirectUpgrade flips a peer's data path from Tor to a direct connection after the upgrade dance succeeds: the libp2p host now holds a QUIC connection to pid, so chat/presence should prefer it over the control channel. Creates a PeerConnection if none exists (the responder side never dialed, so it has no connector entry). The Tor control channel is intentionally left registered as a fallback. See ticket 00c477e3 slice 2.

func (*Connector) MaxPeers

func (c *Connector) MaxPeers() int

MaxPeers returns the configured peer limit.

func (*Connector) MaxTransfers

func (c *Connector) MaxTransfers() int

MaxTransfers returns the configured concurrent transfer limit.

func (*Connector) Reconnect

func (c *Connector) Reconnect(ctx context.Context, peerAddr string) (*PeerConnection, error)

Reconnect attempts to re-establish a connection to a peer that went offline. Uses cached discovery info if fresh, otherwise performs a full DHT lookup.

func (*Connector) ReconnectWithFallback

func (c *Connector) ReconnectWithFallback(ctx context.Context, peerAddr string) (*PeerConnection, error)

ReconnectWithFallback attempts to reconnect, starting from a lower NAT strategy if the previous one failed. Falls through: Direct → HolePunch → Relay → TorOnly.

func (*Connector) ReleaseTransferSlot

func (c *Connector) ReleaseTransferSlot()

ReleaseTransferSlot returns a concurrent transfer slot.

func (*Connector) StartAutoReconnect

func (c *Connector) StartAutoReconnect(ctx context.Context, presence *Presence)

StartAutoReconnect monitors connected peers via the presence service and automatically attempts reconnection when a peer goes offline. Blocks until ctx is cancelled.

type ConnectorConfig

type ConnectorConfig struct {
	Identity   *identity.Identity
	Binding    *identity.Binding
	Host       *Host
	Finder     PeerFinder
	Dialer     TorDialer
	NATCfg     NATConfig
	OnState    func(StateEvent) // called on each state transition
	MaxPeers   int              // max simultaneous peers (0 = 50)
	MaxXfers   int              // max concurrent file transfers (0 = 5)
	PeerBinder PeerStateBinder  // optional; records dialed peers' (ed25519pub→addr)
	// ManifestSink, when set, receives the responder service's capability manifest
	// pushed in CONN_RESPONSE (ticket d80aae80). Optional; nil disables caching.
	ManifestSink ServiceManifestSink

	// ControlReg, when set, makes the connector promote a tor-only connection
	// (no direct QUIC route) into a multiplexed control channel registered
	// here, instead of closing the Tor signaling conn. ControlHandler is the
	// inbound dispatcher installed on that channel — it routes streams the peer
	// opens (a chat message, a ping) to chat/presence. Both are nil for
	// signaling backends that always reach peers directly (loopback, mdns);
	// when nil, the connector closes the Tor conn as before. See ticket 00c477e3.
	ControlReg     *ControlRegistry
	ControlHandler ControlStreamHandler

	// OnTorPromoted, when set, is invoked (in a goroutine) right after a
	// tor-only connection is promoted to a control channel. The daemon uses it
	// to kick off the connection-mode upgrade dance (the initiator offers to
	// switch to a direct connection). nil disables the dance. See ticket
	// 00c477e3 slice 2.
	OnTorPromoted func(cc *ControlChannel)
}

ConnectorConfig configures the connection orchestrator.

type ControlChannel

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

ControlChannel is a multiplexed, bidirectional session layered over a single net.Conn — specifically the Tor signaling connection, held open after the handshake instead of being closed. It uses yamux so each logical request/response is a short-lived stream, mirroring the libp2p per-stream model. This is the data path for peers that have no direct QUIC route (connected-tor): chat, presence, and later rpc ride it; it is also the rendezvous channel for the coordinated direct-upgrade dance.

yamux keepalive (DefaultConfig, 30s) runs on the underlying conn, so a dead Tor circuit is detected by the session itself rather than by the higher-level presence pinger flapping — see ticket 00c477e3.

func NewControlChannel

func NewControlChannel(conn net.Conn, peerAddr string, client bool, handler ControlStreamHandler) (*ControlChannel, error)

NewControlChannel wraps an established net.Conn (the post-handshake Tor connection) in a yamux session and starts accepting inbound streams. The initiator side (the dialer) passes client=true; the responder passes client=false — exactly one side of a yamux session must be the client.

handler is invoked (in its own goroutine) for every stream the peer opens. It may be nil for a send-only channel, in which case inbound streams are rejected (reset).

func (*ControlChannel) Close

func (c *ControlChannel) Close() error

Close tears down the session and the underlying conn. Idempotent.

func (*ControlChannel) Initiator

func (c *ControlChannel) Initiator() bool

Initiator reports whether this side dialed the underlying Tor connection (yamux client). The registry uses it to tell a same-device reconnect (same direction → replace) from the two halves of a mutual dial (opposite directions → coexist). See ControlRegistry.Put.

func (*ControlChannel) IsClosed

func (c *ControlChannel) IsClosed() bool

IsClosed reports whether the underlying session has shut down (e.g. the Tor circuit dropped and yamux keepalive noticed).

func (*ControlChannel) OpenStream

func (c *ControlChannel) OpenStream(ctx context.Context) (Stream, error)

OpenStream opens a new outbound logical stream to the peer over the control channel. The returned Stream is used exactly like a libp2p stream: write the request envelope, read the response.

func (*ControlChannel) PeerAddr

func (c *ControlChannel) PeerAddr() string

PeerAddr returns the ensemble address of the peer this channel reaches.

type ControlRegistry

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

ControlRegistry holds the live ControlChannel(s) for each peer reachable only over Tor (connected-tor). It is the lookup chat and presence consult to find the data path for a tor-only peer: when a peer has no direct QUIC route, its post-handshake Tor connection is promoted to a ControlChannel and parked here, keyed by ensemble address.

One address, many channels. A single identity can be present on several devices at once — e.g. the operator's primary and a second device both authenticate as the one address. Each lands its own control channel, distinguished by the peer's operational ed25519 key. They COEXIST: a second device's channel does not evict the first. A reconnect from the SAME device (same op-key, same direction) replaces its own stale channel.

Mutual dials (ticket 7389b9b8): when two peers dial EACH OTHER, each side ends up promoting two channels into the same (address, op-key) bucket — the conn it dialed (initiator) and the conn the peer dialed (responder). These are NOT a reconnect: closing one of them closes the very conn the peer's own send path is riding, which forces the peer to re-dial, whose promotion closes our remaining channel in turn — a permanent re-dial storm that exhausts Tor SOCKS circuits. Opposite-direction channels for one device therefore COEXIST; only a same-direction Put (a genuine reconnect superseding that device's stale conn) replaces-and-closes. Per-device consumers (GetAll fan-out) treat the up-to-two coexisting channels as the one device they are.

Outbound use:

  • Get returns one live channel (the most recent) — the single best route a router hands to a one-stream caller. It includes a direct-fallback channel (see below), since that is still a valid Tor route to fall back to.
  • GetAll returns every live channel EXCEPT direct-fallback ones, for fan-out of an unsolicited message to an identity's *other* live devices.

Direct-fallback channels (upgrade dance, ticket 00c477e3): when a device's Tor channel is upgraded to a direct QUIC route, MarkDirectUpgrade keeps the channel registered as a fallback (DemoteToTor rides it back if the direct link drops). That device is now reached over its direct route, so its retained Tor channel must NOT be treated as a separate device by fan-out — it is the SAME device, already covered by the direct send. We flag such an entry directFallback so Get/DemoteToTor still see it but GetAll/fan-out skips it. Without this, a single device reachable both directly and over Tor receives every chat twice (the duplicate the receiver's firstSee then has to absorb).

Channels self-heal: a dropped Tor circuit closes the yamux session, and reads prune any channel whose session has closed so callers never hand work to a dead path.

func NewControlRegistry

func NewControlRegistry() *ControlRegistry

NewControlRegistry returns an empty registry.

func (*ControlRegistry) Addrs

func (r *ControlRegistry) Addrs() []string

Addrs returns every peer address with at least one live channel, pruning closed channels as a side effect. Order is unspecified. This is the enumeration the unified peers list (ADR-0004) uses to surface inbound-only peers — a peer that dialed us lives solely here, never in the connector's peers table.

func (*ControlRegistry) ClearDirectFallback

func (r *ControlRegistry) ClearDirectFallback(peerAddr string)

ClearDirectFallback clears the direct-fallback flag on every channel for peerAddr — the inverse of MarkDirectFallback. Called from DemoteToTor: once the direct route is gone the Tor channel is the active path again, so fan-out must resume covering it. DemoteToTor has only the address (not a peer id), and at most one device per address holds a direct route, so clearing all is right.

func (*ControlRegistry) Close

func (r *ControlRegistry) Close()

Close tears down every registered channel and empties the registry.

func (*ControlRegistry) Get

func (r *ControlRegistry) Get(peerAddr string) *ControlChannel

Get returns one live channel for peerAddr (the most recently registered), or nil if none. Closed channels are pruned as a side effect. Used by the router to offer a single best Tor route to a one-stream caller.

func (*ControlRegistry) GetAll

func (r *ControlRegistry) GetAll(peerAddr string) []*ControlChannel

GetAll returns the live channels for peerAddr that represent OTHER devices — at most ONE channel per device (op-key), EXCEPT any device flagged directFallback (reached over a direct route, already covered by the primary send). Used to fan out an unsolicited message to an identity's other devices. A mutually-dialed device holds two coexisting channels (one per direction); fanning out to both would double-deliver to the one device, so the most recently registered live channel represents it. Empty-op-key entries cannot be matched to a device and are each returned as their own. Returns nil if none qualify.

func (*ControlRegistry) MarkDirectFallback

func (r *ControlRegistry) MarkDirectFallback(peerAddr string, peerID peer.ID)

MarkDirectFallback flags the channel whose device matches peerID (its op-key derives that libp2p peer id) as a direct fallback, so GetAll/fan-out stops treating it as a separate device once that device is reached directly. Called from MarkDirectUpgrade after the upgrade dance succeeds. No-op if no entry's op-key derives peerID (e.g. an empty-op-key channel) — the safe direction: fan-out keeps covering it and the receiver's firstSee absorbs the duplicate.

func (*ControlRegistry) Put

func (r *ControlRegistry) Put(peerAddr string, opKey []byte, c *ControlChannel)

Put registers c under peerAddr for the device identified by opKey (the peer's operational ed25519 pubkey). A channel for a DIFFERENT device coexists; a channel for the SAME device AND SAME direction (we-dialed vs peer-dialed) replaces and closes the prior one (a fresh connection supersedes that device's stale one). A same-device channel of the OPPOSITE direction coexists — it is the other half of a mutual dial, and closing it would kill the conn the peer's send path is riding (the 7389b9b8 storm). An empty opKey is treated as its own unique device (it cannot be matched), preserving a safe default if a caller lacks the op-key.

func (*ControlRegistry) Remove

func (r *ControlRegistry) Remove(peerAddr string)

Remove drops and closes EVERY channel for peerAddr.

type ControlStreamHandler

type ControlStreamHandler func(peerAddr string, s Stream)

ControlStreamHandler dispatches a single inbound stream the peer opened on the control channel. peerAddr is the ensemble address of the peer that owns the channel (it was authenticated during the handshake that produced the channel, so the handler can trust it without re-verifying per stream). Implementations read the first framed envelope and route by message type to the same handlers the libp2p SetStreamHandler path uses (chat handleIncoming, presence handlePing, the upgrade dance …). The handler owns the stream and must close (or reset) it when done.

type Demux

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

Demux is the single inbound message-routing table, shared by both transports. Before it, inbound routing lived in two hand-synced places: per-protocol libp2p SetStreamHandler registrations and the daemon's controlStreamHandler type switch for the Tor path. Demux collapses the dispatch decision into one MessageType→handler table that either transport feeds: the Tor control channel installs Dispatch as its ControlStreamHandler, and a libp2p stream handler can call Dispatch too. Registering a new message type (e.g. rpc over Tor) is then a single Register call instead of editing a switch. See ticket c831a27f.

func NewDemux

func NewDemux() *Demux

NewDemux returns an empty routing table.

func (*Demux) ControlHandler

func (d *Demux) ControlHandler() ControlStreamHandler

ControlHandler returns Dispatch typed as a ControlStreamHandler, for installing on a ControlChannel / SetTorConnPromoter.

func (*Demux) Dispatch

func (d *Demux) Dispatch(peerAddr string, s Stream)

Dispatch reads the first framed envelope from s and routes it to the handler registered for its MessageType. For a Register'd handler it then closes the stream; for a RegisterStreaming handler it leaves the stream open and the handler owns the close. A read error returns and closes; an envelope with no registered handler is reset (then closed), matching the pre-Demux controlStreamHandler's default. Its signature is exactly ControlStreamHandler, so it installs directly as a Tor control channel's inbound dispatcher.

func (*Demux) Register

func (d *Demux) Register(t pb.MessageType, h EnvelopeHandler)

Register installs (or replaces) a single-round-trip handler for a message type. Dispatch closes the stream once the handler returns.

func (*Demux) RegisterStreaming

func (d *Demux) RegisterStreaming(t pb.MessageType, h EnvelopeHandler)

RegisterStreaming installs (or replaces) a handler that takes ownership of the stream for a long-lived multi-message exchange. Dispatch hands it the stream and the first envelope and does NOT close the stream — the handler owns its lifecycle (filetransfer's OFFER→CHUNKs→COMPLETE, ticket 4a38c7de).

type DirectDialer

type DirectDialer func(ctx context.Context, peerID string, addrs []string) error

DirectDialer attempts a direct libp2p connection to peerID at the given multiaddrs. In production this is transport.Host.ConnectDirect (host.Connect over QUIC); the call from both peers at the same instant is what pops the NAT/conntrack pinholes. Returning nil means a direct connection now exists.

type EnvelopeHandler

type EnvelopeHandler func(peerAddr string, s Stream, env *pb.Envelope)

EnvelopeHandler processes one already-read framed envelope on a stream. peerAddr is the ensemble address of the peer that owns the transport the envelope arrived on — authenticated when the Tor control channel was established (so it can be trusted without re-verifying per stream), or empty on a transport that doesn't carry it (a direct libp2p stream, where the handler attributes the sender from the envelope's own signature instead).

For a handler registered with Register, Demux.Dispatch owns the stream lifecycle: the handler reads/writes the rest of a single round-trip on s but does not close it (chat, presence, rpc, the upgrade dance). A handler registered with RegisterStreaming instead TAKES OWNERSHIP of the stream for a long-lived multi-message exchange (filetransfer's OFFER→CHUNKs→COMPLETE, ticket 4a38c7de) — Dispatch hands it the stream and the first envelope and does not close it; the handler must close (or reset) it when the transfer ends.

type Host

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

Host wraps a libp2p host for direct QUIC connections.

func NewHost

func NewHost(cfg HostConfig) (*Host, error)

NewHost creates a libp2p host with QUIC transport (QUIC carries its own TLS 1.3 security and native stream multiplexing — so there is no separate Noise upgrade and no separate stream muxer; libp2p's default yamux muxer is inert because there are no non-QUIC connections), AutoNAT, optional NATPortMap, hole punching, and relay client. The only yamux session in the system is our own ControlChannel (control.go), which muxes the held Tor signaling conn — a raw net.Conn libp2p never sees.

func (*Host) AddrInfo

func (h *Host) AddrInfo() peer.AddrInfo

AddrInfo returns the full peer.AddrInfo for connecting to this host.

func (*Host) Addrs

func (h *Host) Addrs() []string

Addrs returns the multiaddrs this host is listening on.

func (*Host) Close

func (h *Host) Close() error

Close shuts down the host.

func (*Host) Connect

func (h *Host) Connect(ctx context.Context, pi peer.AddrInfo) error

Connect dials a remote peer.

func (*Host) ConnectDirect

func (h *Host) ConnectDirect(ctx context.Context, peerID string, addrs []string) error

ConnectDirect dials peerID at the given multiaddrs over the direct QUIC transport. It is the production DirectDialer for the upgrade dance: when both peers call it at the agreed instant, the crossing QUIC initials pop the NAT/conntrack pinholes (simultaneous open) and a direct connection forms, with no relay and no opened port. A nil return means the connection now exists in the host's network; chat/presence will reuse it via OpenStream.

func (*Host) ID

func (h *Host) ID() peer.ID

ID returns the libp2p peer ID.

func (*Host) Inner

func (h *Host) Inner() host.Host

Inner returns the underlying libp2p host for stream handling.

func (*Host) IsConnected

func (h *Host) IsConnected(pid peer.ID) bool

IsConnected reports whether the host currently has a live connection to the given peer. Used by the rpc service to decide whether a cached inbound peer is still reachable before replying over its connection.

func (*Host) IsConnectedPeer

func (h *Host) IsConnectedPeer(peerID string) bool

IsConnectedPeer is IsConnected for a string-encoded peer id (the form the upgrade dance carries on the wire). Undecodable ids report false.

func (*Host) OfferAddrs

func (h *Host) OfferAddrs() []string

OfferAddrs returns every address worth advertising as a dial/punch target for this host: Addrs(), plus the host's unfiltered local view (AllAddrs — which keeps UPnP-mapped and activated-observed addrs that AutoNATv2 marked unreachable; a failed dial-back is expected behind NAT and such addrs are still valid simultaneous-open targets), plus identify-observed public addrs the tracker has seen from even a single peer. This is what the upgrade offer and the Tor-path IP exchange should ship (ticket 59fc74a7): a NATed host's reflexive addr appears here as soon as one direct connection to any public peer (e.g. a seed node) has identified.

func (*Host) OpenStream

func (h *Host) OpenStream(ctx context.Context, peerID peer.ID, proto protocol.ID) (network.Stream, error)

OpenStream opens a libp2p stream to a connected peer using the given protocol.

func (*Host) RemoveStreamHandler

func (h *Host) RemoveStreamHandler(proto protocol.ID)

RemoveStreamHandler removes the handler for the given protocol.

func (*Host) SendBytes

func (h *Host) SendBytes(ctx context.Context, peerID peer.ID, proto protocol.ID, data []byte) error

SendBytes opens a stream, writes data, and closes the write side.

func (*Host) SetStreamHandler

func (h *Host) SetStreamHandler(proto protocol.ID, handler network.StreamHandler)

SetStreamHandler registers a handler for incoming streams of the given protocol.

type HostConfig

type HostConfig struct {
	// Identity provides the operational ed25519 key the libp2p host runs under.
	Identity *identity.Identity
	// ListenPort is the UDP port for QUIC. 0 picks a random port.
	ListenPort int
	// DisableNATMap disables UPnP/NAT-PMP port mapping.
	DisableNATMap bool
	// DisableHolePunch disables DCUtR hole punching.
	DisableHolePunch bool
	// BandwidthReporter, when non-nil, is wired into the host via
	// libp2p.BandwidthReporter so it sees every transferred byte (global +
	// per-peer + per-protocol). The daemon passes its BandwidthCounter here
	// only when the metrics master flag is on — nil means no metering at
	// the source (the privacy default).
	BandwidthReporter libp2pmetrics.Reporter
}

HostConfig configures the libp2p host.

type NATConfig

type NATConfig struct {
	DirectTimeout    time.Duration // UPnP/NAT-PMP + direct connect timeout
	HolePunchTimeout time.Duration // DCUtR timeout
	RelayTimeout     time.Duration // Circuit Relay v2 timeout
}

NATConfig holds timeouts for each traversal strategy.

func DefaultNATConfig

func DefaultNATConfig() NATConfig

DefaultNATConfig returns the standard cascade timeouts.

type NATResult

type NATResult struct {
	Strategy NATStrategy
	Addrs    []string      // multiaddrs of the established connection
	Latency  time.Duration // round-trip latency estimate
}

NATResult describes the outcome of a NAT traversal attempt.

func NATTraverse

func NATTraverse(ctx context.Context, h *Host, peerInfo peer.AddrInfo, cfg NATConfig) NATResult

NATTraverse attempts to connect to peerInfo using a cascade of strategies. It tries each strategy in priority order and returns the first that succeeds. If all strategies fail, it returns StrategyTorOnly as a fallback.

func NATTraverseFrom

func NATTraverseFrom(ctx context.Context, h *Host, peerInfo peer.AddrInfo, cfg NATConfig, from NATStrategy) NATResult

NATTraverseFrom is like NATTraverse but starts from the given strategy, skipping higher-priority strategies.

type NATStrategy

type NATStrategy int

NATStrategy identifies which traversal method succeeded.

const (
	StrategyDirect    NATStrategy = iota // UPnP/NAT-PMP or already public
	StrategyHolePunch                    // DCUtR UDP hole punching
	StrategyRelay                        // Circuit Relay v2
	StrategyTorOnly                      // Tor fallback (no direct connection)
)

func (NATStrategy) String

func (s NATStrategy) String() string

type OnlineStatus

type OnlineStatus struct {
	Address string
	Online  bool
}

OnlineStatus reports a peer's presence state.

type PeerConnection

type PeerConnection struct {
	Address      string
	State        ConnState
	Strategy     NATStrategy
	Latency      time.Duration
	PeerID       peer.ID
	Addrs        []string
	LastActivity time.Time // updated on connect/reconnect
	// DialAddress is the signing identity that established this connection —
	// the node address for Connect/Reconnect, or the service address for
	// ConnectAs. The responder binds the dialer's key to THIS address during
	// the signaling handshake (per-service-key attribution), so connection
	// reuse must be scoped by it: a new local service dialing an
	// already-connected peer needs its OWN handshake to get bound, even
	// though a node-level route already exists. See ticket a4f4c8d0.
	DialAddress string
}

PeerConnection represents an active or pending connection to a peer.

type PeerFinder

type PeerFinder interface {
	FindPeer(ctx context.Context, addr string) (PeerLookupResult, error)
}

PeerFinder abstracts peer discovery for the connector.

type PeerLister

type PeerLister interface {
	ActivePeers() []*PeerConnection
}

PeerLister returns all currently connected peers.

type PeerLookupResult

type PeerLookupResult struct {
	Address   string
	OnionAddr string
}

PeerLookupResult holds discovery results.

type PeerStateBinder

type PeerStateBinder interface {
	Bind(pub []byte, addr string)
}

PeerStateBinder records the (operational ed25519 pubkey → ensemble address) binding learned during the signaling handshake. The daemon's signaling.PeerState satisfies it. Bound entries let receive paths attribute envelopes by env.PubKey instead of trusting the wire-claimed FromAddress (protocol.VerifyAndAttribute). On the responder side, the signaling.Server binds in handleConn. The initiator side is bound here so chat ACKs / RPC replies from the dialed peer also attribute correctly. Without that, a dialer with no PeerState entry for its counterparty would reject every legitimate reply envelope.

type PingPath

type PingPath int

PingPath identifies which transport answered a presence probe. It lets the auto-reconnect watchdog tell "the direct link dropped but the peer is still reachable over Tor" (fall back + re-dance) apart from "gone on every path" (reconnect). See ticket 00c477e3 slice 3.

const (
	PathNone   PingPath = iota // peer did not answer on any path
	PathDirect                 // answered over a direct libp2p stream
	PathTor                    // answered over the Tor control channel
)

func (PingPath) String

func (p PingPath) String() string

type Presence

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

Presence handles ping/pong health checks for connected peers.

func NewPresence

func NewPresence(host *Host, id *identity.Identity) *Presence

NewPresence creates a presence service and registers the pong handler.

func (*Presence) Close

func (p *Presence) Close()

Close unregisters the stream handler.

func (*Presence) HandlePingEnvelope

func (p *Presence) HandlePingEnvelope(stream Stream, env *pb.Envelope)

HandlePingEnvelope answers an already-read PING envelope with a PONG on the given stream. It is the transport-agnostic body of the pong responder: the direct libp2p handler reads the envelope then calls this, and the Tor control-channel dispatcher does the same for a ping that arrives over the held circuit. The caller owns closing the stream.

func (*Presence) IsOnline

func (p *Presence) IsOnline(addr string) bool

IsOnline returns whether a peer is currently marked as online.

func (*Presence) PingPeer

func (p *Presence) PingPeer(ctx context.Context, pid peer.ID) (time.Duration, error)

PingPeer sends a ping over a direct libp2p stream and waits for a pong. Returns round-trip time. This is the direct-route path; callers that may be talking to a tor-only peer should use PingPeerConn, which picks the right transport.

func (*Presence) PingPeerConn

func (p *Presence) PingPeerConn(ctx context.Context, pc *PeerConnection) (time.Duration, error)

PingPeerConn pings a peer over whichever transport currently reaches it and returns the round-trip time. It is a thin wrapper over ProbePeer kept for the periodic pinger and existing callers that don't care which path answered.

func (*Presence) ProbePeer

func (p *Presence) ProbePeer(ctx context.Context, pc *PeerConnection) (PingPath, time.Duration, error)

ProbePeer reports whether pc is reachable right now and over which transport, trying every path the peer might be on so presence reflects real reachability. A directly-connected peer is pinged over its libp2p stream first; if that fails — the direct link dropped — and a Tor control channel is registered, the ping is retried over Tor. A connected-tor peer goes straight to its control channel. The returned path is what lets the auto-reconnect watchdog distinguish "direct dropped but still reachable over Tor" (fall back + re-dance) from "gone entirely" (reconnect). See ticket 00c477e3 slice 3.

func (*Presence) SetControlRegistry

func (p *Presence) SetControlRegistry(r *ControlRegistry)

SetControlRegistry wires the registry of Tor control channels. Once set, pings to a connected-tor peer ride that peer's control channel instead of a (nonexistent) direct libp2p stream — which is what stops the presence pinger from flapping a peer that is reachable only over Tor. See ticket 00c477e3.

func (*Presence) Start

func (p *Presence) Start(ctx context.Context, lister PeerLister, onChange func(OnlineStatus))

Start begins periodic pinging of all connected peers. onChange is called when a peer's online status changes. Blocks until ctx is cancelled.

type Route

type Route struct {
	Path PingPath
	Open func(ctx context.Context) (Stream, error)
}

Route is one candidate transport to a peer, in priority order. Open lazily establishes the stream when the caller is ready to use it (so enumerating routes is cheap and side-effect-free). Path records which transport this route uses, so a caller that cares — presence, which reports whether the peer answered over direct or Tor — can attribute the answer.

type ServiceManifestSink

type ServiceManifestSink interface {
	OnServiceManifest(peerAddr string, manifest *pb.ServiceManifestWire)
}

ServiceManifestSink receives a responder service's capability manifest pushed inside CONN_RESPONSE during the handshake (ticket d80aae80). The daemon wires it to the api layer's remote-manifest cache, keyed by the dialed peerAddr, so remote /-autocomplete and the cross-node send-gate can see what the service declares. The manifest is UNTRUSTED — the sink sanitises + length-bounds it; a nil manifest (responder advertised none) is a no-op.

type StateEvent

type StateEvent struct {
	PeerAddr string
	State    ConnState
	Error    string
}

StateEvent is emitted when a connection state changes.

type Stream

type Stream interface {
	io.ReadWriteCloser
	SetReadDeadline(t time.Time) error
	SetWriteDeadline(t time.Time) error
	Reset() error
	CloseWrite() error
}

Stream is the narrow per-message contract shared by a libp2p network.Stream and a yamux stream: enough for the chat / presence / rpc request-response round-trips to run unchanged over either transport. libp2p's network.Stream and yamux's *Stream both satisfy it, so the same round-trip code can open a stream over a direct QUIC connection or over the Tor control channel without caring which it got.

CloseWrite half-closes the write side without tearing down reads; the bulk filetransfer sender uses it to signal "no more chunks" and then drains until the receiver finalises and closes (filetransfer, ticket 4a38c7de). Both network.Stream and yamux's *Stream provide it, so it costs the round-trip callers nothing and keeps the direct path's half-close semantics over Tor.

type StreamRouter

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

StreamRouter is the single owner of the "direct QUIC vs Tor control channel" decision. Before it, that choice was re-implemented in chat (state-based openStream), presence (prefer-direct-fall-back-to-Tor), and chat's responder registry fallback. Now those callers ask the router for the ordered routes to a peer and the policy lives in one place — which is also what lets rpc and filetransfer get tor-only reachability for free once they route through it.

The priority is always: a direct libp2p stream when the peer has a usable direct path, then the peer's Tor control channel when one is registered. A single-shot caller (chat) takes the first route; a probing caller (presence) tries each in turn and reports which answered. See ticket c831a27f.

rpc intentionally does NOT use the router: its direct resolution is richer (a libp2p inbound-peer reply cache) and its Tor lookup remaps a service address to the node address its control channel is keyed under — neither of which the router models. Folding those in (a pluggable resolver) is a possible later step; until then rpc.openSendStream owns its own selection.

func NewStreamRouter

func NewStreamRouter(host *Host) *StreamRouter

NewStreamRouter builds a router over the given libp2p host. The control registry is wired later (SetControlRegistry) because, like chat and presence today, it only exists once the Tor signaling backend has started.

func (*StreamRouter) ControlChannels

func (r *StreamRouter) ControlChannels(peerAddr string) []*ControlChannel

ControlChannels returns every live Tor control channel for peerAddr — one per live device of that identity. Callers fanning out an unsolicited message to all of an identity's devices iterate these. Nil when no control registry is wired or the peer has no tor-only route.

func (*StreamRouter) OpenStream

func (r *StreamRouter) OpenStream(ctx context.Context, peerAddr string, pc *PeerConnection, directProto protocol.ID) (Stream, PingPath, error)

OpenStream opens a stream over the highest-priority available route and reports which path it used. It is the single-shot entry point for callers (chat) that want one stream over the best transport and treat the absence of any route as a hard failure; it does not fall back to a lower-priority route if the chosen one fails to open (a connected peer's send failure is a real failure, matching the pre-refactor behaviour). Probing callers that want to try every path use Routes directly.

func (*StreamRouter) Routes

func (r *StreamRouter) Routes(peerAddr string, pc *PeerConnection, directProto protocol.ID) []Route

Routes returns the candidate transports to the peer, highest priority first.

  • A direct libp2p route (PathDirect) is offered when pc describes a peer with a usable direct path: pc is non-nil, not known tor-only, and carries a libp2p peer id. directProto is the protocol opened on that route.
  • A Tor route (PathTor) is offered when a live control channel is registered for peerAddr — including the responder case where pc is nil (the peer was never dialed, so there's no PeerConnection, but its promoted channel is parked in the registry).

The slice is empty when neither path exists; callers turn that into a "peer unreachable" error.

func (*StreamRouter) SetControlRegistry

func (r *StreamRouter) SetControlRegistry(reg *ControlRegistry)

SetControlRegistry wires the registry of Tor control channels. Until set, the router offers only direct routes (the behaviour for signaling backends that always reach peers directly, e.g. loopback/mdns).

type TorDialer

type TorDialer interface {
	DialContext(ctx context.Context, address string) (net.Conn, error)
}

TorDialer abstracts Tor network dialing.

type UpgradeConfig

type UpgradeConfig struct {
	// LocalAddrs / LocalPeerID describe this host's direct reachability, sent
	// to the peer so it can dial us during the simultaneous open.
	LocalAddrs  func() []string
	LocalPeerID func() string
	// DirectDial performs the actual hole-punch dial to the peer.
	DirectDial DirectDialer
	// OnUpgraded is called when a direct connection has been established with
	// peerAddr (libp2p host peer id = peerID), so the connector can flip the
	// peer's data path from Tor to direct.
	OnUpgraded func(peerAddr, peerID string)
	// IsConnected reports whether the host already holds a live connection to
	// peerID. Optional. Used after a failed punch dial to detect the peer's
	// half of the simultaneous open landing anyway — a QUIC connection is
	// bidirectional, so an inbound one is an upgrade all the same (ticket
	// 46cdc26f: without this, the failed-dial side stays "tor" while the
	// peer shows "direct").
	IsConnected func(peerID string) bool
	// SyncDelay overrides upgradeSyncDelay (tests use a short value).
	SyncDelay time.Duration
	// InboundWait overrides how long a failed dial waits for the peer's
	// crossing dial to land (defaults to upgradeDialTimeout; tests shrink it).
	InboundWait time.Duration
}

UpgradeConfig wires the Upgrader to its surroundings without importing them.

type Upgrader

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

Upgrader runs the connection-mode upgrade dance over an established Tor control channel: a mutual "shall we connect?" negotiation (CONN_UPGRADE_OFFER / CONN_UPGRADE_ACCEPT) followed by a coordinated simultaneous open (HOLEPUNCH_SYNC). One Upgrader instance serves every control channel; role is per-call — the initiator of a channel offers (Negotiate), the responder answers inbound offers (HandleOffer). A peer that declines, or doesn't understand the messages, leaves the pair on the working Tor data path (graceful downgrade). See ticket 00c477e3 slice 2.

func NewUpgrader

func NewUpgrader(cfg UpgradeConfig) *Upgrader

NewUpgrader builds an Upgrader. LocalAddrs, LocalPeerID and DirectDial are required; without them the dance can't run and Negotiate/HandleOffer no-op.

func (*Upgrader) HandleOffer

func (u *Upgrader) HandleOffer(peerAddr string, s Stream, offerEnv *pb.Envelope)

HandleOffer runs the accepter side of the dance for an inbound CONN_UPGRADE_OFFER already read off the stream by the control dispatcher. It replies with acceptance (or a decline) and, on agreement, coordinates and fires the simultaneous open. The caller owns closing the stream after this returns — so HandleOffer blocks until the punch completes.

func (*Upgrader) Negotiate

func (u *Upgrader) Negotiate(ctx context.Context, cc *ControlChannel) error

Negotiate runs the offerer side of the dance over cc. It opens a control stream, offers to upgrade, and — on mutual agreement — coordinates and fires the simultaneous open. A declined or unanswered offer returns nil (the pair stays on the Tor data path); only transport errors are returned.

Jump to

Keyboard shortcuts

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