Skip to main content

dig_nat/
lib.rs

1//! # dig-nat — abstract NAT traversal for DIG Node peer connections
2//!
3//! One API, [`connect`], establishes a **mutually-authenticated (mTLS)** connection to a peer using
4//! the best available NAT-traversal method, transparently. **The caller never chooses the method** —
5//! they describe the peer once and get back a verified [`PeerConnection`]; which technique got there
6//! is reported for observability but is not something the caller handles.
7//!
8//! ## Traversal order (first success wins, relay last)
9//!
10//! Internally the [`strategy`] attempts, in this order:
11//! 1. **Direct** — peer publicly reachable / already port-forwarded ([`method::direct`])
12//! 2. **UPnP/IGD** port mapping ([`method::upnp`])
13//! 3. **NAT-PMP** (RFC 6886, [`method::natpmp`])
14//! 4. **PCP** (RFC 6887, [`method::pcp`])
15//! 5. **Relay-coordinated hole-punch** (RLY-007, [`method::hole_punch`])
16//! 6. **Relayed transport** via `relay.dig.net` — the LAST resort ([`relay`])
17//!
18//! [`stun`] (RFC 5389) discovers this node's reflexive address for candidate advertisement +
19//! hole-punch coordination.
20//!
21//! ## Streaming-first + multiplexed transport
22//!
23//! Whatever tier establishes the connection, the result is uniform: a [`PeerConnection`] wrapping a
24//! single mTLS byte stream in [`yamux`](mux) multiplexing. The caller opens **many cheap concurrent
25//! logical streams** ([`PeerConnection::open_stream`]) with no head-of-line blocking, and
26//! **byte-range streams** ([`PeerConnection::open_range_stream`]) scoped to `[offset, len)` of a
27//! resource — so a downloader fetches DIFFERENT ranges from DIFFERENT peers in parallel and
28//! reassembles. The API is streaming (read bytes as they arrive), never buffer-the-whole-response.
29//!
30//! ## Identity + mTLS — delegated to `dig-tls`
31//!
32//! Every peer connection is mutual TLS, and the entire certificate model is owned by the canonical
33//! [`dig-tls`](dig_tls) crate (L00): `peer_id = SHA-256(TLS SPKI DER)`, the #1204 BLS-G1 cert
34//! binding, and the ready rustls mutual-auth configs. dig-nat presents this node's [`NodeCert`]
35//! and uses [`dig_tls::client_config_spki_pinned`] for the outbound handshake, authenticating the
36//! remote peer by its SPKI `peer_id` pin (matched to the [`peer::PeerTarget::peer_id`] the caller
37//! specified), rustls proof-of-possession, and the #1204 BLS cert binding — with NO DigNetwork-CA
38//! chain requirement; live self-signed peer leaves are accepted (the DIG-CA-everywhere migration
39//! #1378 is deferred). dig-nat holds NO cert/binding/peer_id code of its own (it was extracted to
40//! dig-tls in 0.6.0); the names below are re-exports for convenience.
41//!
42//! ## Graceful fallback + relay resilience
43//!
44//! Each method is bounded by a per-method timeout; if ALL fail, [`connect`] returns a clear
45//! [`NatError::AllMethodsFailed`] (never panics, never hangs). The [`relay`] client — used both as
46//! the last-resort transport and as a node's persistent reachability channel — establishes and
47//! maintains its session with keepalive + capped-exponential-backoff reconnect, tolerates the relay
48//! being down (retries in the background, never crashes the node), logs once per state change, and
49//! honours the `DIG_RELAY_URL=off` opt-out. See [`relay::RelayStatus`].
50//!
51//! ## Example
52//!
53//! ```no_run
54//! # use std::sync::Arc;
55//! # use dig_nat::{connect, NatConfig, NodeCert, PeerTarget, PeerId};
56//! # async fn run(node: Arc<NodeCert>, peer_id: PeerId, addr: std::net::SocketAddr) -> Result<(), dig_nat::NatError> {
57//! let peer = PeerTarget::with_addr(peer_id, addr, "DIG_MAINNET");
58//! let conn = connect(&peer, &node, &NatConfig::default()).await?;
59//! println!("connected to {} via {:?}", conn.peer_id, conn.method);
60//! # Ok(()) }
61//! ```
62
63#![forbid(unsafe_code)]
64#![warn(missing_docs)]
65
66pub mod accept;
67pub mod config;
68pub mod dialer;
69pub mod error;
70pub mod fast_connect;
71pub mod method;
72pub mod mux;
73pub mod peer;
74pub mod relay;
75pub mod relay_descriptor;
76pub mod runtime;
77pub mod strategy;
78pub mod stun;
79pub mod tunnel;
80pub mod wire;
81
82#[cfg(test)]
83mod relayed_dial_tests;
84
85use std::sync::Arc;
86
87// --- Certificate / mTLS / identity model — re-exported from the canonical `dig-tls` crate (L00).
88// dig-nat CONSUMES dig-tls for ALL of these (it holds no copy of its own), so a single source of
89// truth means the DIG cert shape can never byte-drift between crates. ---
90pub use dig_tls::binding::{verify_binding_from_leaf_cert, BindingOutcome};
91pub use dig_tls::verify::{CapturedBlsPub, CapturedPeerId};
92pub use dig_tls::{
93    peer_id_from_leaf_cert_der, peer_id_from_tls_spki_der, BindingPolicy, NodeCert, PeerId,
94};
95
96pub use accept::RelayAcceptor;
97pub use config::{NatConfig, NatConfigBuilder};
98pub use error::{MethodError, NatError};
99pub use fast_connect::{connect_fast, FastPeerConnection, FastPeerStream};
100pub use method::hole_punch::{HolePunchCoordinator, HolePunchMethod};
101pub use method::relayed::{
102    RelayedDialMethod, RelayedDialer, RelayedTransport, ReservationRelayedTransport,
103};
104pub use method::upnp::{IgdGateway, RealIgd, UpnpMethod};
105pub use method::{TraversalKind, TraversalMethod};
106pub use mux::{
107    AvailabilityAnswer, AvailabilityItem, AvailabilityRequest, AvailabilityResponse, ClosedHandle,
108    PeerSession, PeerStream, RangeFrame, RangeRequest,
109};
110pub use peer::{PeerConnection, PeerTarget};
111pub use relay::{RelayState, RelayStatus, RelayTunnel};
112pub use relay_descriptor::{verify_relay_descriptor, RelayDescriptor, RelayDescriptorError};
113pub use runtime::{NatRuntime, NatRuntimeBuilder};
114
115use dialer::MtlsDialer;
116use method::direct::DirectMethod;
117use method::natpmp::NatPmpMethod;
118use method::pcp::PcpMethod;
119
120/// Establish a mutually-authenticated connection to `peer` with an empty runtime — the convenience
121/// entry point for a caller that holds NO live transport handles (a publicly-reachable node). Only
122/// the **Direct** tier is composable without runtime handles; a NAT'd node that needs the full ladder
123/// (UPnP/NAT-PMP/PCP/hole-punch/relayed) calls [`connect_with_runtime`] with a [`NatRuntime`] carrying
124/// the gateway/port/relay handles.
125///
126/// `node` is this node's [`NodeCert`] — its CA-signed mTLS identity from [`dig-tls`](dig_tls),
127/// presented as the client certificate; `config` selects which methods are enabled, the per-method
128/// timeout, and the [`BindingPolicy`] applied to the peer's #1204 cert binding.
129///
130/// # Errors
131/// - [`NatError::NoMethodsEnabled`] — no method could be composed (nothing enabled, or the enabled
132///   tiers all lacked their runtime inputs — here, only Direct is available).
133/// - [`NatError::AllMethodsFailed`] — every composed method failed (with per-method reasons).
134///
135/// This never panics and never hangs: every method + dial is bounded by
136/// [`NatConfig::per_method_timeout`].
137pub async fn connect(
138    peer: &PeerTarget,
139    node: &Arc<NodeCert>,
140    config: &NatConfig,
141) -> Result<PeerConnection, NatError> {
142    connect_with_runtime(peer, node, config, &NatRuntime::default()).await
143}
144
145/// Establish a mutually-authenticated connection to `peer`, auto-composing the **FULL** NAT-traversal
146/// ladder — direct → UPnP → NAT-PMP → PCP → hole-punch → relayed — trying each in rank order, first
147/// success wins, relay last. The caller never chooses the method: it supplies the data [`NatConfig`]
148/// and the live [`NatRuntime`] handles, and the strategy picks the first tier that establishes an
149/// mTLS [`PeerConnection`] whose remote `peer_id` matches [`PeerTarget::peer_id`].
150///
151/// Each tier is composed ONLY when it is enabled in `config` AND its runtime inputs are present in
152/// `runtime` (an absent tier is skipped — the composition is honest, never a silently-broken dial):
153/// - **Direct** — always (no runtime input).
154/// - **UPnP** — `runtime.local_port` (+ an optional injected IGD gateway; else the real one).
155/// - **NAT-PMP** — `runtime.local_port` + `runtime.gateway_v4`.
156/// - **PCP** — `runtime.local_port` + `runtime.gateway_v4` + `runtime.client_ip`.
157/// - **Hole-punch** — `runtime.hole_punch` + `runtime.my_external_addr`.
158/// - **Relayed** — `runtime.relayed` (carries mTLS over the relay tunnel — NOT a weaker connection).
159///
160/// Every tier — including the relayed one — runs the SAME dig-tls mTLS: the CA-chained [`NodeCert`],
161/// the `peer_id` pin, and the #1204 BLS binding. IPv6 is preferred at every IP-dialing tier via
162/// `dig-ip` (§5.2). The relayed tier tunnels the identical handshake through the relay, which forwards
163/// only ciphertext it cannot read.
164///
165/// # Errors
166/// Same as [`connect`]: [`NatError::NoMethodsEnabled`] if no tier could be composed, else
167/// [`NatError::AllMethodsFailed`] with each composed tier's reason in attempt order.
168pub async fn connect_with_runtime(
169    peer: &PeerTarget,
170    node: &Arc<NodeCert>,
171    config: &NatConfig,
172    runtime: &NatRuntime,
173) -> Result<PeerConnection, NatError> {
174    let methods = compose_ladder(config, runtime);
175    if methods.is_empty() {
176        return Err(NatError::NoMethodsEnabled);
177    }
178    let mut dialer = MtlsDialer::new(Arc::clone(node)).with_binding_policy(config.binding_policy);
179    if let Some(relayed) = &runtime.relayed {
180        dialer = dialer.with_relayed_dialer(Arc::clone(relayed));
181    }
182    strategy::connect_with_strategy(peer, methods, &dialer, config.per_method_timeout).await
183}
184
185/// Assemble the [`TraversalMethod`] trait objects for the full ladder from the enabled tiers in
186/// `config` whose runtime inputs are present in `runtime`. The strategy orders them by
187/// [`TraversalKind::rank`], so the order they are pushed here is irrelevant. A tier missing its
188/// runtime inputs is silently omitted — `connect` only ever attempts a tier it can actually run.
189fn compose_ladder(config: &NatConfig, runtime: &NatRuntime) -> Vec<Arc<dyn TraversalMethod>> {
190    let mut methods: Vec<Arc<dyn TraversalMethod>> = Vec::new();
191
192    // Direct — always composable (the peer's own candidate addresses).
193    if config.is_enabled(TraversalKind::Direct) {
194        methods.push(Arc::new(DirectMethod));
195    }
196
197    // UPnP — needs a local port to map; uses an injected IGD gateway or the real SSDP-discovered one.
198    if config.is_enabled(TraversalKind::Upnp) {
199        if let Some(port) = runtime.local_port {
200            let gateway: Arc<dyn IgdGateway> = runtime
201                .igd
202                .clone()
203                .unwrap_or_else(|| Arc::new(RealIgd::default()));
204            methods.push(Arc::new(UpnpMethod::new(gateway, port)));
205        }
206    }
207
208    // NAT-PMP — needs the local port + the IPv4 gateway.
209    if config.is_enabled(TraversalKind::NatPmp) {
210        if let (Some(port), Some(gw)) = (runtime.local_port, runtime.gateway_v4) {
211            methods.push(Arc::new(NatPmpMethod::new(gw, port)));
212        }
213    }
214
215    // PCP — needs the local port + the IPv4 gateway + this node's client IP.
216    if config.is_enabled(TraversalKind::Pcp) {
217        if let (Some(port), Some(gw), Some(client_ip)) =
218            (runtime.local_port, runtime.gateway_v4, runtime.client_ip)
219        {
220            methods.push(Arc::new(PcpMethod::new(gw, port, client_ip)));
221        }
222    }
223
224    // Hole-punch — needs a relay coordinator + this node's STUN-discovered reflexive address.
225    if config.is_enabled(TraversalKind::HolePunch) {
226        if let (Some(coordinator), Some(my_addr)) =
227            (runtime.hole_punch.clone(), runtime.my_external_addr)
228        {
229            methods.push(Arc::new(HolePunchMethod::new(coordinator, my_addr)));
230        }
231    }
232
233    // Relayed (TURN-last) — needs the relay data-plane; the dial carries mTLS over the relay tunnel.
234    if config.is_enabled(TraversalKind::Relayed) {
235        if let Some(relayed) = runtime.relayed.clone() {
236            methods.push(Arc::new(RelayedDialMethod::new(relayed)));
237        }
238    }
239
240    methods
241}