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