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 cert_binding;
62pub mod config;
63pub mod dialer;
64pub mod error;
65pub mod identity;
66pub mod method;
67pub mod mtls;
68pub mod mux;
69pub mod peer;
70pub mod relay;
71pub mod relay_descriptor;
72pub mod strategy;
73pub mod stun;
74pub mod wire;
75
76use std::sync::Arc;
77
78pub use cert_binding::{
79 build_bound_cert, verify_binding_from_leaf_cert, BindingOutcome, BindingPolicy,
80 CertBindingError,
81};
82pub use config::{LocalIdentity, NatConfig, NatConfigBuilder};
83pub use error::{MethodError, NatError};
84pub use identity::{peer_id_from_leaf_cert_der, peer_id_from_tls_spki_der, PeerId};
85pub use method::{TraversalKind, TraversalMethod};
86pub use mux::{
87 AvailabilityAnswer, AvailabilityItem, AvailabilityRequest, AvailabilityResponse, PeerSession,
88 PeerStream, RangeFrame, RangeRequest,
89};
90pub use peer::{PeerConnection, PeerTarget};
91pub use relay_descriptor::{verify_relay_descriptor, RelayDescriptor, RelayDescriptorError};
92
93use dialer::MtlsDialer;
94use method::direct::DirectMethod;
95
96/// Establish a mutually-authenticated connection to `peer`, choosing the traversal method
97/// transparently (first success wins; relay is the last resort).
98///
99/// `identity` is this node's mTLS identity (its client certificate + key); `config` selects which
100/// methods are enabled + the per-method timeout + the relay/STUN endpoints. On success the returned
101/// [`PeerConnection`] carries the verified remote `peer_id`, the [`TraversalKind`] that established
102/// it, and the authenticated stream.
103///
104/// # Errors
105/// - [`NatError::NoMethodsEnabled`] — the config enabled no methods.
106/// - [`NatError::AllMethodsFailed`] — every enabled method failed (with per-method reasons).
107/// - [`NatError::InvalidConfig`] — the identity/relay/STUN config could not be used.
108///
109/// This function never panics and never hangs: every method (and its dial) is bounded by
110/// [`NatConfig::per_method_timeout`].
111pub async fn connect(
112 peer: &PeerTarget,
113 identity: &LocalIdentity,
114 config: &NatConfig,
115) -> Result<PeerConnection, NatError> {
116 let methods = build_enabled_methods(config);
117 if methods.is_empty() {
118 return Err(NatError::NoMethodsEnabled);
119 }
120 let dialer = MtlsDialer::new(identity.clone());
121 strategy::connect_with_strategy(peer, methods, &dialer, config.per_method_timeout).await
122}
123
124/// Assemble the enabled [`TraversalMethod`] trait objects for a config.
125///
126/// NOTE: the UPnP/NAT-PMP/PCP/hole-punch methods need runtime inputs the caller has not yet supplied
127/// through the current minimal config surface (gateway address, this node's local port + reflexive
128/// address, a live relay coordinator). Until those are wired through the builder, `connect` composes
129/// the methods it can construct from the config alone — currently the always-available **Direct**
130/// method. The other methods are fully implemented + tested and are composed explicitly by callers
131/// (e.g. `dig-node`) that hold that runtime context, via [`strategy::connect_with_strategy`]. This
132/// keeps `connect` honest (it never claims a method it cannot actually run) while the richer
133/// auto-composition lands with the discovery inputs.
134fn build_enabled_methods(config: &NatConfig) -> Vec<Arc<dyn TraversalMethod>> {
135 let mut methods: Vec<Arc<dyn TraversalMethod>> = Vec::new();
136 let direct = DirectMethod;
137 if config.is_enabled(direct.kind()) {
138 methods.push(Arc::new(direct));
139 }
140 methods
141}