Skip to main content

Builder

Struct Builder 

Source
pub struct Builder { /* private fields */ }
Expand description

Builder for Endpoint.

By default the endpoint will generate a new random SecretKey, which will result in a new EndpointId.

To create the Endpoint call Builder::bind.

Implementations§

Source§

impl Builder

Source

pub fn new(preset: impl Preset) -> Self

Creates a new Builder using the given Preset.

See presets for more.

Source

pub fn preset(self, preset: impl Preset) -> Self

Applies the given Preset.

Source

pub fn empty() -> Self

Creates an empty builder with no address lookup services, and RelayMode::Disabled.

Source

pub async fn bind(self) -> Result<Endpoint, BindError>

Binds the endpoint.

Source

pub fn bind_addr<A>(self, addr: A) -> Result<Self, InvalidSocketAddr>

Available on non-wasm_browser only.

Binds an IP socket at the provided socket address.

This is an advanced API to tightly control the sockets used by the endpoint. Most uses do not need to explicitly bind sockets.

§Warning
  • The builder always comes pre-configured with an IPv4 socket to be bound on the unspecified address: 0.0.0.0. This is the equivalent of using INADDR_ANY special bind address and results in a socket listening on all interfaces available.

  • Likewise the builder always comes pre-configured with an IPv6 socket to be bound on the unspecified address: [::]. This bind is allowed to fail however.

  • Adding a bind address removes the pre-configured unspecified bind address for this address family. Use Self::bind_addr_with_opts to bind additional addresses without replacing the default bind address.

  • This should be called at most once for each address family: once for IPv4 and/or once for IPv6. Calling it multiple times for the same address family will result in undefined routing behaviour. To bind multiple sockets of the same address family, use Self::bind_addr_with_opts.

§Description

Requests a socket to be bound on a specific address, with an implied netmask of /0. This allows restricting binding to only one network interface for a given address family.

If the port specified is already in use, binding the endpoint will fail. Using port 0 in the socket address assigns a random free port.

§Example
let endpoint = Endpoint::builder(presets::N0)
    .clear_ip_transports()
    .bind_addr("127.0.0.1:0")?
    .bind_addr("[::1]:0")?
    .bind()
    .await?;
Source

pub fn bind_addr_with_opts<A>( self, addr: A, opts: BindOpts, ) -> Result<Self, InvalidSocketAddr>

Available on non-wasm_browser only.

Binds an IP socket at the provided socket address.

This is an advanced API to tightly control the sockets used by the endpoint. Most uses do not need to explicitly bind sockets.

§Warning
  • The builder always comes pre-configured with an IPv4 socket to be bound on the unspecified address: 0.0.0.0. This is the equivalent of using INADDR_ANY special bind address and results in a socket listening on all interfaces available.

  • Likewise the builder always comes pre-configured with an IPv6 socket to be bound on the unspecified address: [::]. This bind is allowed to fail however.

§Description

Requests a socket to be bound on a specific address. This allows restricting binding to only one network interface for a given address family.

BindOpts::set_prefix_len should be used to configure the netmask of the network interface. This allows outgoing datagrams that start a new network flow to be sent over the socket which is attached to the subnet of the destination address. If multiple sockets are bound the standard routing-table semantics are used: the socket attached to the subnet with the longest prefix matching the destination is used. Practically this means the smallest subnets are at the top of the routing table, and the first subnet containing the destination address is chosen.

If no socket is bound to a subnet that contains the destination address, the notion of “default route” is used. At most one socket per address family may be marked as the default route using BindOpts::set_is_default_route, and this will be used for destinations not contained by the subnets of the bound sockets. This network is expected to have a default gateway configured. A socket with a prefix length of /0 will be set as a “default route” implicitly, unless BindOpts::set_is_default_route is set to false explicitly.

Be aware that using a subnet with a prefix length of /0 will always contain all destination addresses. It is valid to configure this, but no more than one such socket should be bound or the routing will be non-deterministic.

To use a subnet with a non-zero prefix length as the default route in addition to being routed when its prefix matches, use BindOpts::set_is_default_route. Subnets with a prefix length of zero are always marked as default routes.

Finally note that most outgoing datagrams are part of an existing network flow. That is, they are in response to an incoming datagram. In this case the outgoing datagram will be sent over the same socket as the incoming datagram was received on, and the routing with the prefix length and default route as described above does not apply.

Using port 0 in the socket address assigns a random free port.

If the port specified is already in use, binding the endpoint will fail, unless BindOpts::set_is_required is set to false

§Example
let endpoint = Endpoint::builder(presets::N0)
    .clear_ip_transports()
    .bind_addr_with_opts("127.0.0.1:0", BindOpts::default().set_prefix_len(24))?
    .bind_addr_with_opts("[::1]:0", BindOpts::default().set_prefix_len(48))?
    .bind()
    .await?;
Source

pub fn clear_ip_transports(self) -> Self

Available on non-wasm_browser only.

Removes all IP based transports.

Source

pub fn clear_relay_transports(self) -> Self

Removes all relay based transports.

Source

pub fn secret_key(self, secret_key: SecretKey) -> Self

Sets a secret key to authenticate with other peers.

This secret key’s public key will be the PublicKey of this endpoint and thus also its EndpointId

If not set, a new secret key will be generated.

Source

pub fn alpns(self, alpn_protocols: Vec<Vec<u8>>) -> Self

Sets the ALPN protocols that this endpoint will accept on incoming connections.

Not setting this will still allow creating connections, but to accept incoming connections at least one ALPN must be set.

Ordering matters for protocol negotiation. When an incoming connection offers multiple ALPNs, the first matching ALPN will be chosen. This means that alpns should be ordered such that the preferred protocols come first.

Source

pub fn relay_mode(self, relay_mode: RelayMode) -> Self

Sets the relay servers to assist in establishing connectivity.

Relay servers are used to establish initial connection with another iroh endpoint. They also perform various functions related to hole punching, see the crate docs for more details.

By default the number 0 relay servers are used, see RelayMode::Default.

When using RelayMode::Custom, the provided relay_map must contain at least one configured relay endpoint. If an invalid RelayMap is provided bind will result in an error.

Source

pub fn clear_address_lookup(self) -> Self

Removes all Address Lookup services from the builder.

If no Address Lookup is set, connecting to an endpoint without providing its direct addresses or relay URLs will fail.

See the documentation of the crate::address_lookup::AddressLookup trait for details.

Source

pub fn address_lookup(self, address_lookup: impl AddressLookupBuilder) -> Self

Adds an additional Address Lookup for this endpoint.

Once the endpoint is created the provided AddressLookupBuilder::into_address_lookup will be called. This allows Address Lookup’s to finalize their configuration by e.g. using the secret key from the endpoint which can be needed to sign published information.

This method can be called multiple times and all the Address Lookup’s passed in will be combined using an internal instance of the crate::address_lookup::AddressLookupServices. To clear all Address Lookup’s, use Self::clear_address_lookup.

If no Address Lookup is set, connecting to an endpoint without providing its direct addresses or relay URLs will fail.

See the documentation of the crate::address_lookup::AddressLookup trait for details.

Source

pub fn addr_filter(self, filter: AddrFilter) -> Self

Sets the address filter applied to all address data before publishing.

This filter is applied once, at the AddressLookupServices level, before distributing data to any individual address lookup service. This ensures consistent filtering regardless of how the services are configured.

Source

pub fn clear_addr_filter(self) -> Self

Clears the address filter, allowing all addresses to be published.

This removes any filter previously set via Self::addr_filter, including filters set by presets.

Source

pub fn user_data_for_address_lookup(self, user_data: UserData) -> Self

Sets the initial user-defined data to be published in Address Lookup’s for this node.

When using Address Lookup’s, this string of UserData will be published together with the endpoint’s addresses and relay URL. When other endpoints discover this endpoint, they retrieve the UserData in addition to the addressing info.

Iroh itself does not interpret the user-defined data in any way, it is purely left for applications to parse and use.

Source

pub fn external_addr(self, addr: SocketAddr) -> Self

Adds an external address on which this endpoint is directly reachable.

This address will be advertised to peers together with any discovered external addresses and will be used in NAT traversal and to establish direct connections.

Can be called multiple times. See also Endpoint::add_external_addr for adding addresses at runtime.

Source

pub fn transport_config(self, transport_config: QuicTransportConfig) -> Self

Sets a custom QuicTransportConfig for this endpoint.

The transport config contains parameters governing the QUIC state machine.

If unset, the default config is used. Default values should be suitable for most internet applications. Applications protocols which forbid remotely-initiated streams should set max_concurrent_bidi_streams and max_concurrent_uni_streams to zero.

Please be aware that changing some settings may have adverse effects on establishing and maintaining direct connections.

Source

pub fn dns_resolver(self, dns_resolver: DnsResolver) -> Self

Available on non-wasm_browser only.

Optionally sets a custom DNS resolver to use for this endpoint.

The DNS resolver is used to resolve relay hostnames, and endpoint addresses if crate::address_lookup::DnsAddressLookup is configured.

By default, a new DNS resolver is created which is configured to use the host system’s DNS configuration. You can pass a custom instance of DnsResolver here to use a differently configured DNS resolver for this endpoint, or to share a DnsResolver between multiple endpoints.

Source

pub fn proxy_url(self, url: Url) -> Self

Sets an explicit proxy url to proxy all HTTP(S) traffic through.

Source

pub fn proxy_from_env(self) -> Self

Sets the proxy url from the environment, in this order:

  • HTTP_PROXY
  • http_proxy
  • HTTPS_PROXY
  • https_proxy
Source

pub fn ca_tls_config(self, ca_tls_config: CaTlsConfig) -> Self

Sets the trusted CA root certificates for non-iroh TLS connections.

These Certificate Authority roots are used as trust anchors for verifying the validity of TLS certificates presented by external services, such as iroh relays, pkarr servers, or DNS-over-HTTPS resolvers. They don’t need to be trusted for the integrity or authenticity of native iroh connections, which rely on iroh’s own cryptographic authentication mechanisms.

Source

pub fn ca_roots_config(self, ca_roots_config: CaTlsConfig) -> Self

👎Deprecated since 1.0.0:

Renamed to ca_tls_config

Source

pub fn keylog(self, keylog: bool) -> Self

Enables saving the TLS pre-master key for connections.

This key should normally remain secret but can be useful to debug networking issues by decrypting captured traffic.

If keylog is true then setting the SSLKEYLOGFILE environment variable to a filename will result in this file being used to log the TLS pre-master keys.

Source

pub fn max_tls_tickets(self, n: usize) -> Self

Set the maximum number of TLS tickets to cache.

Set this to a larger value if you want to do 0rtt connections to a large number of clients.

The default is 256, taking about 150 KiB in memory.

Source

pub fn crypto_provider(self, crypto_provider: Arc<CryptoProvider>) -> Self

Specify the rustls cryptography to use for all TLS operations.

This includes

  • TLS for encryption and authentication of iroh connections themselves, but also
  • HTTPS connections to relays
  • Pkarr relay publishing HTTPS connections
  • and any other Address Lookup services that decide to use Endpoint::tls_config.

The two most common crypto providers in use today are ring as well as aws-lc-rs.

If either the tls-ring or tls-aws-lc-rs feature is set in iroh, this function doesn’t need to be called.

If none of these features are set, then calling this function in the builder is mandatory.

Source

pub fn hooks(self, hooks: impl EndpointHooks + 'static) -> Self

Install hooks onto the endpoint.

Endpoint hooks intercept the connection establishment process of an Endpoint.

You can install multiple EndpointHooks by calling this function multiple times. Order matters: hooks are invoked in the order they were installed onto the endpoint builder. Once a hook returns reject, further processing is aborted and other hooks won’t be invoked.

See EndpointHooks for details on the possible interception points in the connection lifecycle.

Source

pub fn portmapper_config(self, config: PortmapperConfig) -> Self

Configures the portmapper service (UPnP, PCP, NAT-PMP).

Defaults to PortmapperConfig::Enabled. Pass PortmapperConfig::Disabled to avoid gateway probing (e.g. if it triggers firewall prompts).

Source

pub fn net_report_config(self, config: NetReportConfig) -> Self

Configures the net report.

The net report component is responsible for figuring out if and how the endpoint is connected to the internet. It does this by doing various probes to the configured relay servers to get public addresses, NAT behaviour, and relay latencies. In addition it tries to detect captive portals.

Some non-essential features of the net report component can be disabled via this configuration.

Source

pub fn add_custom_transport(self, factory: Arc<dyn CustomTransport>) -> Self

Available on crate feature unstable-custom-transports only.

Adds a custom transport to the endpoint.

This API is unstable and gated behind the unstable-custom-transport feature. It is not covered by semantic versioning guarantees and may change in any release without a major version bump.

Source

pub fn path_selector(self, selector: Arc<dyn PathSelector>) -> Self

Available on crate feature unstable-custom-transports only.

Sets a custom PathSelector for this endpoint.

The path selector decides which path to use among the candidate paths to a remote endpoint. By default iroh uses a built-in selector that sorts paths by biased RTT (with IPv6 preferred over IPv4 and relay treated as backup) and is sticky to avoid flapping. Pass a custom PathSelector here to override that policy — for example, to make a custom transport always win over IP.

Takes an Arc<dyn PathSelector> so the same selector instance can be shared across multiple endpoints if desired. See examples/custom-transport.rs for an example implementation.

This API is unstable and gated behind the unstable-custom-transport feature. It is not covered by semantic versioning guarantees and may change in any release without a major version bump.

Trait Implementations§

Source§

impl Debug for Builder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more