Instance Method
addOnion(key:ports:detach:)
Register an ephemeral v3 onion service via ADD_ONION (control-spec.txt §3.27).
func addOnion(key: OnionKeySpec, ports: [OnionPortMapping], detach: Bool = false) async throws -> OnionService
Parameters
-
key
-
Key policy. See OnionKeySpec.newV3(discardPrivateKey:) for Tor-generated keys or OnionKeySpec.providedV3(_:) to re-adopt a persisted key.
-
ports
-
One or more virtual-port → target mappings. Use toLocalPort(_:localPort:) for the common loopback case.
-
detach
-
Whether to detach the service from this connection. Defaults to false.
Return Value
A fresh OnionService record. Its privateKey is populated iff key was OnionKeySpec.newV3(discardPrivateKey:) with discardPrivateKey: false or OnionKeySpec.providedV3(_:) (in which case it echoes the supplied key).
Mentioned In
Discussion
Serialises ADD_ONION <keyType> [Flags=…] Port=… Port=… from the provided OnionKeySpec and OnionPortMapping array, sends it, parses the reply with parseAddOnionResponse(_:), and wraps the result in an OnionService with a fresh createdAt timestamp.
Lifecycle
detach: false (default) — service is tied to this control connection and removed when the socket closes. Ideal for request-scoped services (e.g. a one-shot file transfer).
detach: true — Detach flag is added; service persists until explicit delOnion(_:) or Tor exit. Ideal for long-lived services that outlive the launching process.
Throws
TorError.controlProtocolError(code:message:) on rejection, TorError.invalidResponse(_:) on malformed reply, or TorError.serviceAlreadyExists(_:) when a duplicate key is submitted (Tor reply 550/554).
Important
privateKey is secret material. Persist only via Keychain (Apple) or an equivalent credential store.