signaling

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: 28 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// HandshakeTimeout is the deadline for each individual handshake attempt.
	HandshakeTimeout = 30 * time.Second

	// MaxRetries is the number of times to retry on transient errors.
	MaxRetries = 3

	// RetryBackoff is the base delay between retries (doubles each attempt).
	RetryBackoff = 2 * time.Second
)
View Source
const (
	// NonceSize is the byte length of handshake nonces.
	NonceSize = 32

	// TimestampFreshness is the maximum age of a ConnRequest timestamp.
	// W3 #1c320188: applied symmetrically; the future-skew is intentionally
	// asymmetric and smaller (FutureSkewMax) — there's no good reason a
	// peer's clock would legitimately run minutes ahead of ours.
	TimestampFreshness = 5 * time.Minute

	// FutureSkewMax is the maximum permitted clock skew where the peer's
	// timestamp is ahead of ours. Healthy NTP drift is sub-second; 30s is
	// a generous bound that closes most of the future-replay window.
	// W3 #1c320188.
	FutureSkewMax = 30 * time.Second

	// NonceCacheTTL is how long replayed nonces are remembered. Must be at
	// least TimestampFreshness + FutureSkewMax so a captured request can't
	// outlive the cache that catches its replay.
	NonceCacheTTL = 10 * time.Minute

	// DefaultMaxNonceEntries caps the number of nonces held in memory (and
	// therefore the size of the persisted snapshot). W3 #dccf7e8b: a backstop
	// against unbounded growth. Post-fix only *validly-signed* requests reach
	// the insert path (Remember runs after signature verification), so under
	// legitimate load the cache holds only the handful of handshakes seen in
	// the last NonceCacheTTL — far below this cap. When the cap is reached the
	// oldest entry is evicted first, so memory/disk stay bounded even under a
	// flood of validly-signed requests. ~50 bytes/entry → ~3 MB at the cap.
	DefaultMaxNonceEntries = 65536

	// ConnRequestCanonicalLabel domain-separates the bytes signed by a
	// CONN_REQUEST Dilithium signature from any other Dilithium signing
	// context (in particular the IdentityBinding label).
	ConnRequestCanonicalLabel = "ensemble.v1.connreq"
)
View Source
const DefaultMaxConcurrentConns = 256

DefaultMaxConcurrentConns caps the number of inbound signaling connections handled concurrently across all services (W3 #cfffd8a4). Legitimate handshakes complete in well under a second; this is a backstop against an unauthenticated connection flood spawning unbounded goroutines. Excess connections wait at the semaphore (the kernel accept backlog buffers more), and handleConn's 30s first-read deadline guarantees slots free up.

Variables

View Source
var ErrRejected = errors.New("connection rejected")

ErrRejected is returned when the peer explicitly rejects the connection. This is not retried.

View Source
var ErrServiceExists = errors.New("signaling: service already added")

ErrServiceExists is returned by AddService when the name is already registered.

View Source
var ErrServiceNotFound = errors.New("signaling: service not found")

ErrServiceNotFound is returned by RemoveService when no such service is registered.

Functions

func ConnRequestCanonicalBytes

func ConnRequestCanonicalBytes(fromAddr, targetAddr string, nonce []byte, timestamp int64) []byte

ConnRequestCanonicalBytes returns the deterministic byte sequence signed by the initiator's Dilithium key for a CONN_REQUEST. Any future re-implementation MUST use this exact layout.

Layout (byte-exact):

ConnRequestCanonicalLabel    ("ensemble.v1.connreq", 19 bytes)
0x00                         (label terminator)
uint16 big-endian            (len(from_address))
from_address                 (ASCII bytes)
uint16 big-endian            (len(target_address))
target_address               (ASCII bytes)
uint16 big-endian            (len(nonce), always 32)
nonce                        (raw bytes)
int64 big-endian             (timestamp, Unix millis)

Length-prefixing every variable-length field prevents canonicalisation ambiguity (e.g., from_address="foobar" + target_address="" must produce different bytes from from_address="foo" + target_address="bar").

func CreateConnConfirm

func CreateConnConfirm(id *identity.Identity, binding *identity.Binding, responderNonce []byte) ([]byte, error)

CreateConnConfirm builds a CONN_CONFIRM that proves the initiator owns the operational ed25519 key authorised by its IdentityBinding. The ed25519 signature covers the responder's nonce.

func CreateConnRequest

func CreateConnRequest(fromAddr, targetAddr string, id *identity.Identity) (data, nonce []byte, err error)

CreateConnRequest builds a Dilithium-signed CONN_REQUEST. The initiator's Identity provides both the signing key and the Dilithium pubkey carried on the wire.

fromAddr is the address the initiator is authenticating AS — id's own address.

func CreateConnResponse

func CreateConnResponse(accepted bool, id *identity.Identity, binding *identity.Binding, requestNonce []byte, reason string, manifest ...*pb.ServiceManifestWire) (data, respNonce []byte, err error)

CreateConnResponse builds a CONN_RESPONSE proving the responder's Dilithium identity and binding its operational ed25519 key. The ed25519 signature covers the initiator's request nonce.

If !accepted, fields other than `reason` are zeroed — no identity material is revealed on rejection. The optional trailing manifest is the responder service's capability declaration, attached only on the accepted path (admission → capabilities). It is variadic so the many existing call sites compile unchanged; production passes the service's manifest, tests pass none.

func EncryptIPInfo

func EncryptIPInfo(info *IPInfo, id *identity.Identity, peerPub ed25519.PublicKey) ([]byte, error)

EncryptIPInfo encrypts IPInfo using an ECDH-derived AES-256-GCM key. Converts the Identity's ed25519 operational key + the peer's ed25519 operational key to X25519, performs ECDH, derives an AES key via HKDF-SHA256, and encrypts the serialized IPExchangeMsg.

peerPub is the peer's ed25519 operational pubkey (bound by IdentityBinding in the handshake).

func FilterLocalReachableAddrs

func FilterLocalReachableAddrs(addrs []string) []string

FilterLocalReachableAddrs filters libp2p multiaddrs down to those that are plausibly reachable from a same-host or same-LAN peer:

  • loopback (127.0.0.0/8, ::1)
  • RFC1918 private (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16)
  • link-local (169.254.0.0/16, fe80::/10)

Backends whose intended reach is local (loopback, mDNS) must wrap their LocalAddrs source with this filter before handing it to ServiceConfig. Without filtering, libp2p's host.Addrs() may include identify-protocol observed externals (e.g. a VPN egress IP) that the peer at the other end of a same-host signaling exchange cannot route back to. libp2p then dials every advertised addr in parallel, the public-IP dials time out, and the resulting (peer, addr) backoff entries poison the working loopback/LAN addrs in the same dial round — leaving subsequent SendBytes calls with "all dials failed".

Multiaddrs that fail to parse, or that don't expose an IPv4/IPv6 component, are dropped (no IP means no reachability claim we can validate; the production caller is feeding us libp2p multiaddrs which always lead with ip4/ip6). Input order is preserved in the filtered output.

The Tor backend deliberately does NOT use this filter — Tor's IP exchange is the *only* way the peer learns how to reach the originator over libp2p, and that path is by definition cross-network, so observed externals are load-bearing rather than noise.

func GenerateNonce

func GenerateNonce() ([]byte, error)

GenerateNonce creates a cryptographically random nonce.

func ValidateConnConfirm

func ValidateConnConfirm(data []byte, responderNonce, expectedDilithiumPub []byte) (*pb.ConnConfirm, error)

ValidateConnConfirm verifies a CONN_CONFIRM against the initiator's established Dilithium identity (from step 1) and the responder's nonce. expectedDilithiumPub is the initiator's Dilithium pubkey received in CONN_REQUEST; the binding here must verify under it.

Returns the parsed message; the binding's Ed25519Pub is the initiator's operational key and should be stashed in the peer-state cache for downstream envelope verification.

func ValidateConnRequest

func ValidateConnRequest(data []byte, nc *NonceCache) (*pb.ConnRequest, error)

ValidateConnRequest unmarshals + cryptographically verifies a CONN_REQUEST.

On success: nonce + timestamp are fresh AND the address-pubkey match holds AND the Dilithium signature is valid. The returned message is safe to use for askUser flows — the dialer's claimed identity has been authenticated.

On failure: error returned BEFORE any user-facing side effect. Callers (server.go::handleEnvelopeForService) MUST treat this error as a reason to drop the connection without prompting the user.

func ValidateConnResponse

func ValidateConnResponse(data []byte, requestNonce []byte, targetAddr string) (*pb.ConnResponse, error)

ValidateConnResponse verifies a CONN_RESPONSE against the initiator's expectations:

  • the responder's Dilithium pubkey hashes to targetAddr;
  • the embedded binding's Dilithium signature verifies under that pubkey;
  • the ed25519 signature over request_nonce verifies under the bound operational key.

On success the responder is authenticated and the bound ed25519 op key is safe to record for downstream wire-message verification.

Types

type Backend

type Backend interface {
	// Listener returns the inbound listener for the given service together
	// with the ServiceEndpoint describing where peers should reach it
	// (e.g. an onion address for TorBackend, a socket path for the future
	// LoopbackBackend). The keypair is supplied so backends that need to
	// derive a persistent endpoint identity from it can do so (TorBackend
	// today ignores kp — the registry persists the onion key separately).
	//
	// The returned listener is owned by the caller; Backend implementations
	// do not close it on Stop. (Today the underlying onion.Service /
	// net.Listener lifecycle belongs to whoever provisioned it — the
	// registry, for TorBackend.)
	Listener(ctx context.Context, svc string, id *identity.Identity) (net.Listener, ServiceEndpoint, error)

	// Dial resolves a peer's signaling endpoint to a net.Conn. Used by
	// signaling clients to drive the 3-step handshake.
	Dial(ctx context.Context, endpoint ServiceEndpoint) (net.Conn, error)

	// Ready closes once the backend can serve Listener / Dial calls. For
	// TorBackend this is the Tor bootstrap-complete signal; for the future
	// LoopbackBackend it closes immediately.
	Ready() <-chan struct{}
}

Backend abstracts the transport that carries signaling envelopes. Today the only implementation is TorBackend (in internal/signaling/tor), which wraps the existing onion-listener + Tor SOCKS dial paths. T2 / T5 will add LoopbackBackend (Unix domain sockets) and MdnsBackend (mDNS).

The signaling.Server holds a Backend and calls Listener at AddService time to bind the per-service accept loop. Outbound dials currently still flow through signaling.Client + its dedicated Dialer; the Backend.Dial method is the seam that T2 / T5 will route the client through once the per-backend ServiceEndpoint shape settles.

type Client

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

Client sends outbound signaling requests to a peer's .onion address.

func NewClient

func NewClient(id *identity.Identity, binding *identity.Binding, addr string, dialer Dialer) *Client

NewClient creates a signaling client that dials as the given ensemble address.

func (*Client) RequestConnection

func (c *Client) RequestConnection(ctx context.Context, peerOnion string, targetAddr string) (*HandshakeResult, error)

RequestConnection performs the full 3-step handshake with a peer. Retries on transient errors (timeouts, connection failures) but not on explicit rejections.

type ConnectionDecision

type ConnectionDecision struct {
	Accepted bool
	Reason   string
}

ConnectionDecision represents the user's accept/reject decision for a connection request.

type ConnectionRequest

type ConnectionRequest struct {
	Service          string
	FromAddress      string
	FromDilithiumPub []byte
	Decision         chan ConnectionDecision
}

ConnectionRequest represents an inbound connection request pending user decision. Service identifies the per-daemon service that the inbound request landed on.

FromDilithiumPub is the IDENTITY pubkey for FromAddress, **already verified** by the time askUser is invoked, and it always hashes to FromAddress (AddressFromDilithiumPub(FromDilithiumPub) == FromAddress) — it is the dialer's own signing key. This is the right pubkey to persist as the contact's identity and to fingerprint in the UI.

type CreatesListeners

type CreatesListeners interface {
	CreatesListeners() bool
}

CreatesListeners is an optional Backend capability. A backend whose Listener() call CREATES the listener (loopback, mdns) implements this returning true, telling the Server it owns those listeners and must close them on RemoveService — otherwise re-adding the same service name fails with "address already listening" forever (the ADR-0009 upgrade path: stop → swap artifact → re-register the same name). TorBackend does NOT implement it: its Listener() merely looks up an onion the registry provisioned, and the engine closes those in its own teardown.

type Dialer

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

Dialer abstracts network dialing for signaling connections.

type EnvelopeHandler

type EnvelopeHandler func(conn net.Conn, env *pb.Envelope)

EnvelopeHandler is invoked for envelopes whose MessageType is not handled by the signaling layer. Today this is the DHT path; the daemon plugs this in so each per-service onion listener still routes DHT FIND_NODE / PUT_RECORD.

type HandshakeResult

type HandshakeResult struct {
	PeerEd25519Pub ed25519.PublicKey
	PeerAddr       string
	// ServiceManifest is the responder service's capability declaration, pushed
	// inside CONN_RESPONSE on acceptance (ticket d80aae80). Nil when the responder
	// advertised none (or runs a pre-manifest binary). An UNTRUSTED hint — the
	// initiator sanitises + length-bounds it before use, and the host stays the
	// final execution authority.
	ServiceManifest *pb.ServiceManifestWire
}

HandshakeResult contains the outcome of a successful handshake.

PeerEd25519Pub is the responder's *operational* ed25519 pubkey — the one bound to its Dilithium identity by the IdentityBinding in CONN_RESPONSE. This is the pubkey that will sign per-envelope wire messages from this peer going forward.

type IPInfo

type IPInfo struct {
	Addrs  []string // multiaddrs, e.g. /ip4/1.2.3.4/udp/4001/quic-v1
	PeerID string   // libp2p host peer ID (Base58); empty for pre-fix peers
}

IPInfo holds network addresses for direct connection plus the libp2p host peer ID. The peer ID is load-bearing for multi-service deployments: the signaling layer's per-service keypair signs CONN_RESPONSE, but the libp2p host runs under the daemon's node keypair, so peer-ID-from-signaling-pubkey derivation produces the wrong ID for any non-node service. Shipping the real host ID alongside the addrs lets the connector store the peerstore entry under the correct ID. Empty PeerID is treated as "peer running pre-fix binary" and the caller falls back to ed25519 derivation.

func DecryptIPInfo

func DecryptIPInfo(ciphertext []byte, id *identity.Identity, peerPub ed25519.PublicKey) (*IPInfo, error)

DecryptIPInfo decrypts ciphertext produced by EncryptIPInfo.

func ExchangeIPs

func ExchangeIPs(ctx context.Context, conn net.Conn, ourInfo *IPInfo, id *identity.Identity, peerPub ed25519.PublicKey) (*IPInfo, error)

ExchangeIPs performs a bidirectional encrypted IP exchange over conn. Both sides send their encrypted IP info concurrently and decrypt the peer's reply. Uses the existing length-prefixed wire protocol.

type NonceCache

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

NonceCache provides replay protection by remembering recently used nonces. The cache is in-memory plus an optional on-disk snapshot so daemon restarts don't reset replay protection within the freshness window.

func NewNonceCache

func NewNonceCache() *NonceCache

NewNonceCache creates a new in-memory nonce cache.

func NewPersistentNonceCache

func NewPersistentNonceCache(path string) (*NonceCache, error)

NewPersistentNonceCache constructs a cache that flushes its entries to the given path at most once per flushPeriod (30 s) and loads any previously-persisted entries from that path. Missing file is not an error. W3 #1c320188.

func (*NonceCache) Check

func (nc *NonceCache) Check(nonce []byte) bool

Check is the atomic check-and-insert form: returns true (recording the nonce) if fresh, false on replay. Equivalent to Remember; retained for callers/tests that don't need the two-phase split. Verification paths should prefer Seen() before signature verification + Remember() after, so an invalid-signature flood never reaches the insert. W3 #dccf7e8b.

func (*NonceCache) Flush

func (nc *NonceCache) Flush()

Flush forces an immediate disk snapshot. Used by the daemon at shutdown so anything seen since the last debounced flush is captured.

func (*NonceCache) Remember

func (nc *NonceCache) Remember(nonce []byte) bool

Remember records the nonce, returning true if it was fresh and false on replay. Callers MUST only Remember a nonce AFTER the request's signature has verified (W3 #dccf7e8b) so an unauthenticated flood of invalid-signature requests never populates — and never persists — the cache.

The cache is bounded at maxEntries: when full, the oldest entry is evicted before the new one is inserted, so memory and the persisted snapshot stay bounded even under a flood of validly-signed requests. If the cache has a persistence path and the last flush was longer than flushPeriod ago, the snapshot is rewritten before Remember returns.

func (*NonceCache) Seen

func (nc *NonceCache) Seen(nonce []byte) bool

Seen reports whether the nonce is already cached WITHOUT inserting it. It is the cheap pre-verification reject: a replay of a previously-accepted request is dropped before the expensive Dilithium signature verification runs. W3 #dccf7e8b. A wrong-length nonce is reported "seen" (it can never be a fresh, valid nonce) so it can't slip through; callers length-check anyway.

func (*NonceCache) SetFlushPeriod

func (nc *NonceCache) SetFlushPeriod(d time.Duration)

SetFlushPeriod overrides the debounce on disk persistence. Used by tests; production code stays on the 30 s default.

func (*NonceCache) SetMaxEntries

func (nc *NonceCache) SetMaxEntries(n int)

SetMaxEntries overrides the capacity cap. Test-only; production stays on DefaultMaxNonceEntries. A value <= 0 disables the cap. W3 #dccf7e8b.

func (*NonceCache) Size

func (nc *NonceCache) Size() int

Size returns the current number of cached nonces. Test/diagnostic helper.

type PeerState

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

PeerState is a thread-safe, bounded in-memory map: ed25519 op pubkey → ensemble address. Populated by the signaling handshake at the moment the binding is verified; consulted by downstream packets to attribute envelopes.

func NewPeerState

func NewPeerState() *PeerState

NewPeerState constructs an empty cache with default TTL + size bounds.

func (*PeerState) Bind

func (ps *PeerState) Bind(ed25519Pub []byte, address string)

Bind records that ed25519Pub is the operational key for address. Overwrites any prior binding for the same key — peer rotations land here too — and refreshes its recency. Triggers lazy eviction so the cache stays bounded.

func (*PeerState) Forget

func (ps *PeerState) Forget(ed25519Pub []byte)

Forget drops any binding for ed25519Pub. Used by the handshake when a peer's binding is replaced, and by tests for setup hygiene.

func (*PeerState) Lookup

func (ps *PeerState) Lookup(ed25519Pub []byte) (string, bool)

Lookup returns the address bound to ed25519Pub, or ("", false) if no binding has been recorded (e.g., a peer that hasn't completed the handshake yet) or the binding has expired. A live binding's recency is refreshed, which is what keeps an actively-communicating peer warm against both TTL expiry and LRU eviction.

func (*PeerState) Size

func (ps *PeerState) Size() int

Size returns the number of bindings in the cache. Cheap thread-safe accessor for diagnostics + tests.

type Server

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

Server demultiplexes inbound signaling streams across multiple registered services. Each service has its own keypair, contact store, and onion listener; the server runs one accept goroutine per service so streams never cross over between services.

The Server holds a Backend that supplies per-service Listeners (today TorBackend wraps tor.Engine.OnionListener; T2 / T5 add Loopback and mDNS). Tests may construct a Server with no Backend and supply each ServiceConfig.Listener directly.

func NewServer

func NewServer(backend Backend) *Server

NewServer creates a signaling server with no services. Call AddService to register each service before (or after) Start.

If backend is non-nil, AddService will fetch each service's listener from it (and any ServiceConfig.Listener field acts as an override for tests). If backend is nil, every ServiceConfig must carry its own Listener.

func NewServerWithNonceCache

func NewServerWithNonceCache(backend Backend, nc *NonceCache) *Server

NewServerWithNonceCache constructs a Server backed by a caller-supplied NonceCache so the daemon can wire up a persistent cache and survive restarts within the replay window. W3 #1c320188.

Like NewServer, backend may be nil for tests that wire Listener directly on each ServiceConfig.

func (*Server) AddService

func (s *Server) AddService(cfg ServiceConfig) error

AddService registers a service with the server. If the server has been started, the service's accept loop launches immediately; otherwise it launches when Start is called.

The listener for the service comes from cfg.Listener if set (test path) or from the Server's configured Backend otherwise. AddService returns an error if neither source supplies one.

func (*Server) Backend

func (s *Server) Backend() Backend

Backend returns the backend the server is configured with (nil if none). Exposed so callers can introspect the active signaling transport for logging / debug surfaces.

func (*Server) HandleEnvelope

func (s *Server) HandleEnvelope(ctx context.Context, conn net.Conn, env *pb.Envelope, svcName string)

HandleEnvelope processes a pre-read CONN_REQUEST envelope on an existing connection, routing it to the named service's handshake state. The daemon's per-onion mux uses this when it has already consumed the first envelope. Returns silently if the named service is not registered.

func (*Server) NonceCache

func (s *Server) NonceCache() *NonceCache

NonceCache exposes the server's nonce cache so callers can Flush() it on shutdown.

func (*Server) PeerState

func (s *Server) PeerState() *PeerState

PeerState exposes the post-handshake ed25519-op-key → address cache. Downstream consumers (rpc, chat, filetransfer) use this to attribute envelopes by env.PubKey.

func (*Server) RemoveService

func (s *Server) RemoveService(name string) error

RemoveService cancels the service's accept loop and drops it from the server. The underlying listener is not closed by RemoveService — the caller (the Tor engine) owns the listener's lifecycle. The accept goroutine exits once the caller closes the listener; RemoveService does not wait for that to happen.

func (*Server) ServiceEndpoint

func (s *Server) ServiceEndpoint(name string) ServiceEndpoint

ServiceEndpoint returns the backend-supplied endpoint for the named service, or nil if no such service is registered or the listener was supplied directly (test path). Callers should treat nil as "no backend-side reach info" rather than an error.

func (*Server) SetEnvelopeHandler

func (s *Server) SetEnvelopeHandler(h EnvelopeHandler)

SetEnvelopeHandler installs a handler for envelopes whose message type is not a signaling message. The daemon uses this to route DHT envelopes off the same onion listener.

func (*Server) SetOnConnectionRequest

func (s *Server) SetOnConnectionRequest(name string, cb func(*ConnectionRequest)) error

SetOnConnectionRequest replaces the unknown-peer callback for the given service. Returns ErrServiceNotFound if the service has not been added.

func (*Server) SetPeerBoundRecorder

func (s *Server) SetPeerBoundRecorder(rec func(peerAddr, localAddr string))

SetPeerBoundRecorder installs a hook invoked when an inbound handshake completes: peerAddr is the verified dialer and localAddr the local service it dialed (whose IdentityBinding crossed in CONN_RESPONSE, so the dialer can attribute envelopes signed as localAddr). The daemon wires this to the rpc layer's identity-scoped reply routing, authorizing service-signed replies to a peer that has not yet sent any envelope (ticket e19b1b63).

func (*Server) SetTorConnPromoter

func (s *Server) SetTorConnPromoter(p TorConnPromoter)

SetTorConnPromoter installs the hook that keeps a post-handshake connection open as a control channel instead of closing it. See TorConnPromoter.

func (*Server) Start

func (s *Server) Start(ctx context.Context) error

Start begins running per-service accept loops. Already-registered services start immediately; services added later via AddService start as they are added. Returns nil on success; subsequent calls are no-ops.

func (*Server) Stop

func (s *Server) Stop()

Stop signals every per-service accept loop to exit. Listeners belong to the caller (typically the Tor engine, which closes them in its own Stop) and are not closed here; the accept goroutines exit when their listener does. Stop does not wait for accept goroutines to finish — closing the listener is what unblocks them, and that is the caller's responsibility.

type ServiceConfig

type ServiceConfig struct {
	Name      string
	Identity  *identity.Identity
	Binding   *identity.Binding
	Address   string
	Contacts  *contacts.Store
	OnRequest func(*ConnectionRequest)
	// OnEstablished, when set, is called once a peer's inbound connection to
	// this service completes the handshake and has a negotiated data path
	// (ADR-0007 §5). Optional — nil means the service does not observe its
	// connection roster. Fire-and-forget; must not block the handshake.
	OnEstablished func(peerAddr string)
	Listener      net.Listener
	LocalAddrs    func() []string
	LocalPeerID   func() string
	// Capabilities, when set, returns the service's capability manifest to push
	// to an accepted initiator inside CONN_RESPONSE (ticket d80aae80). Optional —
	// nil/absent means no capabilities are advertised. The daemon wires this from
	// the services registry; today it carries the slash-command set.
	Capabilities func() *pb.ServiceManifestWire
}

ServiceConfig describes one service's signaling state. Each registered service has its own keypair, address, contact store, and unknown-peer callback.

The Server obtains the per-service net.Listener from its configured Backend at AddService time. Tests may supply a Listener directly to bypass the backend (the field acts as an optional override) — this is how the existing signaling unit tests construct a bare-TCP responder without standing up a real Tor engine. Production callers leave Listener nil and let the Backend supply it.

LocalAddrs returns this service's libp2p multiaddrs for the responder-side IP exchange that runs after the 3-step handshake. If nil, IP exchange is skipped and the initiator falls back to Tor-only routing.

LocalPeerID returns the libp2p host's peer ID (Base58). It's shipped to the initiator alongside the addrs so the connector stores the peerstore entry under the *host's* ID rather than deriving an ID from the service's signing pubkey (which would be wrong for any service whose keypair differs from the node keypair). May be nil for tests or pre-multi-service code paths; the initiator then falls back to ed25519-from-signaling-pubkey derivation.

type ServiceEndpoint

type ServiceEndpoint interface {
	// Backend returns the identifier of the originating backend ("tor",
	// "loopback", "mdns"). Implementations should return a stable lowercase
	// string suitable for logging and for the eventual --signaling flag.
	Backend() string

	// String returns a human-readable rendering of the endpoint, suitable
	// for log lines and debug output.
	String() string
}

ServiceEndpoint carries the backend-specific reach information for a registered service. It is opaque to the signaling layer — only the originating backend knows how to interpret its concrete type.

For TorBackend the implementation is a small struct carrying the onion address + port (see internal/signaling/tor). T2 will add a loopback flavour (socket path) and T5 an mDNS flavour (instance name + advertised addr). The Backend() string is the discriminator T2's --signaling flag will key off.

type TorConnPromoter

type TorConnPromoter func(conn net.Conn, peerAddr string, peerEd25519Pub []byte)

TorConnPromoter is invoked with the post-IP-exchange signaling connection so the responder can keep it open as a multiplexed control channel rather than closing it. peerEd25519Pub is the peer's verified operational key (already bound in PeerState). When a promoter is wired, the responder always offers the connection as a control channel: if the initiator settled on a direct QUIC route it closes its end and the promoted session falls away harmlessly; if the initiator is tor-only it keeps its end, giving both peers a data path over the one held Tor circuit (chat replies, pings). The promoter TAKES OWNERSHIP of conn — it must not be closed by the signaling layer afterward. The daemon wires this only on the Tor backend; it is nil for loopback/mdns, where peers are always reachable directly. See ticket 00c477e3.

Directories

Path Synopsis
Package loopback provides a same-host signaling.Backend backed by Unix domain sockets under a well-known rendezvous directory.
Package loopback provides a same-host signaling.Backend backed by Unix domain sockets under a well-known rendezvous directory.
Package mdns provides a LAN-only signaling.Backend backed by mDNS / DNS-SD advertisements.
Package mdns provides a LAN-only signaling.Backend backed by mDNS / DNS-SD advertisements.
Package tor provides the Tor-based signaling.Backend implementation.
Package tor provides the Tor-based signaling.Backend implementation.

Jump to

Keyboard shortcuts

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