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
31//!
32//! Every peer connection is mutual TLS. A peer's identity is `peer_id = SHA-256(TLS SPKI DER)`
33//! ([`identity`], matching `dig-gossip`). The dial presents this node's certificate and the
34//! [`mtls::PeerIdPinningVerifier`] rejects the handshake unless the remote's derived `peer_id`
35//! matches the [`peer::PeerTarget::peer_id`] the caller asked for — so the transport is
36//! self-authenticating.
37//!
38//! ## Graceful fallback + relay resilience
39//!
40//! Each method is bounded by a per-method timeout; if ALL fail, [`connect`] returns a clear
41//! [`NatError::AllMethodsFailed`] (never panics, never hangs). The [`relay`] client — used both as
42//! the last-resort transport and as a node's persistent reachability channel — establishes and
43//! maintains its session with keepalive + capped-exponential-backoff reconnect, tolerates the relay
44//! being down (retries in the background, never crashes the node), logs once per state change, and
45//! honours the `DIG_RELAY_URL=off` opt-out. See [`relay::RelayStatus`].
46//!
47//! ## Example
48//!
49//! ```no_run
50//! # use dig_nat::{connect, NatConfig, LocalIdentity, PeerTarget, PeerId};
51//! # async fn run(identity: LocalIdentity, peer_id: PeerId, addr: std::net::SocketAddr) -> Result<(), dig_nat::NatError> {
52//! let peer = PeerTarget::with_addr(peer_id, addr, "DIG_MAINNET");
53//! let conn = connect(&peer, &identity, &NatConfig::default()).await?;
54//! println!("connected to {} via {:?}", conn.peer_id, conn.method);
55//! # Ok(()) }
56//! ```
57
58#![forbid(unsafe_code)]
59#![warn(missing_docs)]
60
61pub mod config;
62pub mod dialer;
63pub mod error;
64pub mod identity;
65pub mod method;
66pub mod mtls;
67pub mod mux;
68pub mod peer;
69pub mod relay;
70pub mod strategy;
71pub mod stun;
72pub mod wire;
73
74use std::sync::Arc;
75
76pub use config::{LocalIdentity, NatConfig, NatConfigBuilder};
77pub use error::{MethodError, NatError};
78pub use identity::{peer_id_from_leaf_cert_der, peer_id_from_tls_spki_der, PeerId};
79pub use method::{TraversalKind, TraversalMethod};
80pub use mux::{
81 AvailabilityAnswer, AvailabilityItem, AvailabilityRequest, AvailabilityResponse, PeerSession,
82 PeerStream, RangeFrame, RangeRequest,
83};
84pub use peer::{PeerConnection, PeerTarget};
85
86use dialer::MtlsDialer;
87use method::direct::DirectMethod;
88
89/// Establish a mutually-authenticated connection to `peer`, choosing the traversal method
90/// transparently (first success wins; relay is the last resort).
91///
92/// `identity` is this node's mTLS identity (its client certificate + key); `config` selects which
93/// methods are enabled + the per-method timeout + the relay/STUN endpoints. On success the returned
94/// [`PeerConnection`] carries the verified remote `peer_id`, the [`TraversalKind`] that established
95/// it, and the authenticated stream.
96///
97/// # Errors
98/// - [`NatError::NoMethodsEnabled`] — the config enabled no methods.
99/// - [`NatError::AllMethodsFailed`] — every enabled method failed (with per-method reasons).
100/// - [`NatError::InvalidConfig`] — the identity/relay/STUN config could not be used.
101///
102/// This function never panics and never hangs: every method (and its dial) is bounded by
103/// [`NatConfig::per_method_timeout`].
104pub async fn connect(
105 peer: &PeerTarget,
106 identity: &LocalIdentity,
107 config: &NatConfig,
108) -> Result<PeerConnection, NatError> {
109 let methods = build_enabled_methods(config);
110 if methods.is_empty() {
111 return Err(NatError::NoMethodsEnabled);
112 }
113 let dialer = MtlsDialer::new(identity.clone());
114 strategy::connect_with_strategy(peer, methods, &dialer, config.per_method_timeout).await
115}
116
117/// Assemble the enabled [`TraversalMethod`] trait objects for a config.
118///
119/// NOTE: the UPnP/NAT-PMP/PCP/hole-punch methods need runtime inputs the caller has not yet supplied
120/// through the current minimal config surface (gateway address, this node's local port + reflexive
121/// address, a live relay coordinator). Until those are wired through the builder, `connect` composes
122/// the methods it can construct from the config alone — currently the always-available **Direct**
123/// method. The other methods are fully implemented + tested and are composed explicitly by callers
124/// (e.g. `dig-node`) that hold that runtime context, via [`strategy::connect_with_strategy`]. This
125/// keeps `connect` honest (it never claims a method it cannot actually run) while the richer
126/// auto-composition lands with the discovery inputs.
127fn build_enabled_methods(config: &NatConfig) -> Vec<Arc<dyn TraversalMethod>> {
128 let mut methods: Vec<Arc<dyn TraversalMethod>> = Vec::new();
129 let direct = DirectMethod;
130 if config.is_enabled(direct.kind()) {
131 methods.push(Arc::new(direct));
132 }
133 methods
134}