Skip to main content

dig_nat/
mux.rs

1//! Stream multiplexing + byte-range streams over a single established peer connection.
2//!
3//! Every traversal tier (direct / UPnP / NAT-PMP / PCP / hole-punch / relayed) yields the SAME
4//! thing: one mTLS byte stream to the peer. On top of that single stream this module layers
5//! **[`yamux`]** multiplexing so the content/download layer can open **many cheap concurrent logical
6//! streams** to the peer with no head-of-line blocking — the transport is **streaming-first**, never
7//! "send request, buffer the whole response in memory".
8//!
9//! Two capabilities:
10//!
11//! 1. **Multiplexing** — [`PeerSession::open_stream`] opens an independent bidirectional
12//!    [`PeerStream`] (a tokio [`AsyncRead`] + [`AsyncWrite`]); open N of them concurrently and read
13//!    each incrementally with natural backpressure (yamux windows).
14//! 2. **Byte-range streams** — [`PeerSession::open_range_stream`] opens a stream scoped to a
15//!    `[offset, offset+len)` range of a named resource by writing a small [`RangeRequest`] preamble,
16//!    then hands back the stream so the caller reads exactly those bytes as they arrive. A downloader
17//!    opens range streams to DIFFERENT peers in parallel and reassembles — multi-source parallel
18//!    download falls out of "streams are cheap + multiplexed + range-scoped".
19//!
20//! The uniform abstraction holds regardless of how the connection was established, and regardless of
21//! whether the underlying byte stream is direct or (tier-6) relay-proxied.
22//!
23//! ## Wire alignment (normative)
24//!
25//! The control + range types here conform to the published **L7 peer-network spec** (docs.dig.net
26//! "L7 · DIG Node peer network", §8 streaming, §9 byte-range fetch + availability). The shapes are
27//! the `dig.getAvailability` / `dig.fetchRange` request/response and the streamed `RangeFrame`
28//! (`{offset, length, bytes, complete}`, first frame adding `total_length` + `chunk_lens` +
29//! `chunk_index` + `inclusion_proof` + `root`). Per-chunk integrity (split by `chunk_lens`, verify
30//! the whole-resource inclusion proof vs the chain-anchored `root`, AES-256-GCM-SIV-open) is done by
31//! the CONTENT layer above dig-nat; dig-nat carries these frames faithfully over the mux transport.
32
33use std::io;
34use std::sync::atomic::{AtomicBool, Ordering};
35use std::sync::Arc;
36
37use serde::{Deserialize, Serialize};
38use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
39use tokio::sync::Notify;
40use tokio_util::compat::{Compat, FuturesAsyncReadCompatExt, TokioAsyncReadCompatExt};
41
42/// One logical, bidirectional stream to the peer — a tokio [`AsyncRead`] + [`AsyncWrite`]. Reads
43/// deliver bytes incrementally as they arrive (streaming, with yamux-window backpressure); many
44/// [`PeerStream`]s coexist on one [`PeerSession`] without head-of-line blocking.
45///
46/// yamux streams are `futures` streams; this is the tokio-trait view via `tokio-util` compat.
47pub type PeerStream = Compat<yamux::Stream>;
48
49/// One item in a [`dig.getAvailability`](AvailabilityRequest) batch — a resource key at store, root,
50/// or capsule/resource granularity (inferred from which fields are present, per the L7 spec §9):
51/// `store_id` only → *has_store*; `+ root` → *has_root* (the capsule `store_id:root`); `+
52/// retrieval_key` → *has_resource*. Hashes are 64-hex.
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54pub struct AvailabilityItem {
55    /// The store id (64-hex). Always present.
56    pub store_id: String,
57    /// The generation root (64-hex). Present for root/resource granularity.
58    #[serde(default, skip_serializing_if = "Option::is_none")]
59    pub root: Option<String>,
60    /// The resource retrieval key (64-hex). Present for resource granularity.
61    #[serde(default, skip_serializing_if = "Option::is_none")]
62    pub retrieval_key: Option<String>,
63}
64
65/// The **availability pre-check** (`dig.getAvailability`, L7 spec §9) — asked BEFORE any range fetch.
66/// A multi-source download batches candidate peers × items in one call each and only fans byte-range
67/// requests at peers that answer *available* — never opening range streams to peers that may not hold
68/// the content. A message-style control call over the mux'd mTLS connection.
69#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
70pub struct AvailabilityRequest {
71    /// The items to check, batched.
72    pub items: Vec<AvailabilityItem>,
73}
74
75/// One answer in an [`AvailabilityResponse`], positionally aligned with the request `items`.
76#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
77pub struct AvailabilityAnswer {
78    /// Whether the peer holds the queried item. Always present.
79    pub available: bool,
80    /// (store granularity) generation roots the peer holds for the store, newest-first.
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    pub roots: Option<Vec<String>>,
83    /// (root/resource granularity) the ciphertext length — lets the caller plan its ranges.
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub total_length: Option<u64>,
86    /// (root/resource granularity) the chunk count.
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub chunk_count: Option<u64>,
89    /// Whether the peer holds the FULL resource/capsule (`true`) or only part (`false`).
90    #[serde(default, skip_serializing_if = "Option::is_none")]
91    pub complete: Option<bool>,
92}
93
94/// The peer's answer to an [`AvailabilityRequest`]: one [`AvailabilityAnswer`] per queried item,
95/// positionally aligned with the request's `items`.
96#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
97pub struct AvailabilityResponse {
98    /// One answer per queried item, in request order.
99    pub items: Vec<AvailabilityAnswer>,
100}
101
102/// A byte-range request (`dig.fetchRange`, L7 spec §9) written at the start of a range-scoped stream.
103/// Identifies a resource (`store_id` + `retrieval_key` [+ `root`]) or a whole capsule
104/// (`capsule: true`, identified by `store_id` [+ `root`]) and the `[offset, offset+length)` range.
105#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
106pub struct RangeRequest {
107    /// The store id (64-hex).
108    pub store_id: String,
109    /// The resource retrieval key (64-hex). Omitted when `capsule` is true.
110    #[serde(default, skip_serializing_if = "Option::is_none")]
111    pub retrieval_key: Option<String>,
112    /// The generation root (64-hex). Optional — defaults to the chain-anchored tip.
113    #[serde(default, skip_serializing_if = "Option::is_none")]
114    pub root: Option<String>,
115    /// Fetch a whole capsule / `.dig` (identified by `store_id` [+ `root`]) rather than one resource.
116    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
117    pub capsule: bool,
118    /// Start offset (bytes) into the resource ciphertext. Default `0`.
119    #[serde(default)]
120    pub offset: u64,
121    /// Length (bytes) to return (widened to whole-chunk boundaries; clamped to the node window).
122    pub length: u64,
123}
124
125/// One streamed `dig.fetchRange` frame (L7 spec §8 framing). Frames arrive in ascending `offset`
126/// order and tile the requested range exactly; the caller reassembles by `offset` and stops on
127/// `complete`. The **first frame** additionally carries the per-range verification metadata so a
128/// single-peer range is independently verifiable against the chain-anchored `root`.
129#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
130pub struct RangeFrame {
131    /// This frame's start offset within the requested range.
132    pub offset: u64,
133    /// This frame's byte length.
134    pub length: u64,
135    /// The raw ciphertext bytes.
136    #[serde(with = "serde_bytes")]
137    pub bytes: Vec<u8>,
138    /// Whether this is the final frame of the range.
139    pub complete: bool,
140    /// (first frame only) the full resource ciphertext length.
141    #[serde(default, skip_serializing_if = "Option::is_none")]
142    pub total_length: Option<u64>,
143    /// (first frame only) per-chunk ciphertext lengths of the whole resource, in order.
144    #[serde(default, skip_serializing_if = "Option::is_none")]
145    pub chunk_lens: Option<Vec<u64>>,
146    /// (first frame only) index into `chunk_lens` of the first chunk in this frame.
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub chunk_index: Option<u64>,
149    /// (first frame only) merkle inclusion proof of the whole resource vs the generation `root`
150    /// (base64, relayed verbatim); `null`/absent for `capsule: true` (self-verifying on install).
151    #[serde(default, skip_serializing_if = "Option::is_none")]
152    pub inclusion_proof: Option<String>,
153    /// (first frame only) the generation root (64-hex) the inclusion proof is against.
154    #[serde(default, skip_serializing_if = "Option::is_none")]
155    pub root: Option<String>,
156}
157
158impl AvailabilityRequest {
159    /// Serialize as a `u32` big-endian length prefix + JSON body (the uniform control framing).
160    pub fn encode(&self) -> Vec<u8> {
161        encode_framed(self)
162    }
163    /// Read + decode an [`AvailabilityRequest`] from `r` (the peer/serving side).
164    pub async fn decode<R: AsyncRead + Unpin>(r: &mut R) -> io::Result<Self> {
165        decode_framed(r).await
166    }
167}
168
169impl AvailabilityResponse {
170    /// Serialize as a `u32` big-endian length prefix + JSON body.
171    pub fn encode(&self) -> Vec<u8> {
172        encode_framed(self)
173    }
174    /// Read + decode an [`AvailabilityResponse`] from `r` (the requesting side).
175    pub async fn decode<R: AsyncRead + Unpin>(r: &mut R) -> io::Result<Self> {
176        decode_framed(r).await
177    }
178}
179
180impl RangeRequest {
181    /// A range request for a content resource (`store_id` + `retrieval_key`).
182    pub fn resource(
183        store_id: impl Into<String>,
184        retrieval_key: impl Into<String>,
185        offset: u64,
186        length: u64,
187    ) -> Self {
188        RangeRequest {
189            store_id: store_id.into(),
190            retrieval_key: Some(retrieval_key.into()),
191            root: None,
192            capsule: false,
193            offset,
194            length,
195        }
196    }
197
198    /// Serialize as a `u32` big-endian length prefix + JSON body — the preamble a peer reads to learn
199    /// the resource + range before streaming the frames.
200    pub fn encode(&self) -> Vec<u8> {
201        encode_framed(self)
202    }
203    /// Read + decode a [`RangeRequest`] preamble from `r` (the serving side of a range stream).
204    pub async fn decode<R: AsyncRead + Unpin>(r: &mut R) -> io::Result<Self> {
205        decode_framed(r).await
206    }
207}
208
209impl RangeFrame {
210    /// Serialize as a `u32` big-endian length prefix + JSON body (one framed frame on the stream).
211    pub fn encode(&self) -> Vec<u8> {
212        encode_framed(self)
213    }
214    /// Read + decode one [`RangeFrame`] from `r`. Returns `Ok(None)` at clean end-of-stream (the
215    /// reader hit EOF on a frame boundary), so a consumer loops until `None` or `complete`.
216    pub async fn decode<R: AsyncRead + Unpin>(r: &mut R) -> io::Result<Option<Self>> {
217        decode_framed_opt(r).await
218    }
219}
220
221/// Maximum length-prefixed control/preamble body — guards against a malicious length prefix forcing
222/// a huge allocation.
223const MAX_FRAMED_BODY: usize = 64 * 1024;
224
225/// Serialize `value` as a `u32` big-endian length prefix + JSON body — the uniform framing for every
226/// small control message on a stream (availability + range preambles).
227fn encode_framed<T: Serialize>(value: &T) -> Vec<u8> {
228    let body = serde_json::to_vec(value).expect("control message serializes");
229    let mut out = Vec::with_capacity(4 + body.len());
230    out.extend_from_slice(&(body.len() as u32).to_be_bytes());
231    out.extend_from_slice(&body);
232    out
233}
234
235/// Read + decode a length-prefixed JSON control message from `r`, bounded by [`MAX_FRAMED_BODY`].
236async fn decode_framed<T: for<'de> Deserialize<'de>, R: AsyncRead + Unpin>(
237    r: &mut R,
238) -> io::Result<T> {
239    let mut len_buf = [0u8; 4];
240    r.read_exact(&mut len_buf).await?;
241    let len = u32::from_be_bytes(len_buf) as usize;
242    if len > MAX_FRAMED_BODY {
243        return Err(io::Error::new(
244            io::ErrorKind::InvalidData,
245            "control message too large",
246        ));
247    }
248    let mut body = vec![0u8; len];
249    r.read_exact(&mut body).await?;
250    serde_json::from_slice(&body).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
251}
252
253/// Like [`decode_framed`] but returns `Ok(None)` on a CLEAN end-of-stream at a frame boundary (the
254/// length prefix read hits immediate EOF), so a streaming consumer can loop until the stream ends.
255async fn decode_framed_opt<T: for<'de> Deserialize<'de>, R: AsyncRead + Unpin>(
256    r: &mut R,
257) -> io::Result<Option<T>> {
258    let mut len_buf = [0u8; 4];
259    match r.read_exact(&mut len_buf).await {
260        Ok(_) => {}
261        Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
262        Err(e) => return Err(e),
263    }
264    let len = u32::from_be_bytes(len_buf) as usize;
265    if len > MAX_FRAMED_BODY {
266        return Err(io::Error::new(
267            io::ErrorKind::InvalidData,
268            "control message too large",
269        ));
270    }
271    let mut body = vec![0u8; len];
272    r.read_exact(&mut body).await?;
273    serde_json::from_slice(&body)
274        .map(Some)
275        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
276}
277
278/// One command to the yamux driver task. yamux 0.13 has no `Control` handle, so we drive the
279/// [`yamux::Connection`] in a task and talk to it over this channel.
280enum MuxCommand {
281    /// Open a new outbound stream; the resulting [`yamux::Stream`] (or error) comes back on the sender.
282    OpenOutbound(tokio::sync::oneshot::Sender<Result<yamux::Stream, String>>),
283}
284
285/// A multiplexed session over one peer connection: open many concurrent logical [`PeerStream`]s.
286///
287/// yamux 0.13 exposes a poll-based [`yamux::Connection`] (no `Control` handle), so a background
288/// driver task owns the connection and serves open-stream requests over a command channel; inbound
289/// streams are surfaced on [`Self::inbound_rx`] for a serving node. Dropping the session closes the
290/// command channel, which ends the driver and tears down the underlying byte stream.
291pub struct PeerSession {
292    cmd_tx: tokio::sync::mpsc::Sender<MuxCommand>,
293    /// Inbound streams opened BY the peer (server role / bidirectional use). A pure client can
294    /// ignore this; a serving node reads accepted range-request streams from here.
295    inbound_rx: tokio::sync::mpsc::Receiver<PeerStream>,
296    /// Set + notified when the driver task ends (the underlying byte stream closed — a clean close or
297    /// a transport error). Observed via [`Self::closed_handle`] so fast-connect can detect a transport
298    /// dying and fall back without holding the session lock.
299    closed_flag: Arc<AtomicBool>,
300    closed_notify: Arc<Notify>,
301}
302
303/// A cheap, cloneable observer of a [`PeerSession`]'s underlying byte stream closing (the mux driver
304/// task ending — a clean close OR a transport error). Fast-connect's promotion guard holds one to
305/// detect the active transport dying and fall back to another tier, without locking the session.
306#[derive(Clone)]
307pub struct ClosedHandle {
308    flag: Arc<AtomicBool>,
309    notify: Arc<Notify>,
310}
311
312impl ClosedHandle {
313    /// Whether the session's transport has already closed.
314    pub fn is_closed(&self) -> bool {
315        self.flag.load(Ordering::Acquire)
316    }
317
318    /// Resolve once the session's transport has closed (returns immediately if already closed).
319    pub async fn closed(&self) {
320        loop {
321            if self.flag.load(Ordering::Acquire) {
322                return;
323            }
324            // Arm the wait, then re-check the flag: the driver sets the flag BEFORE
325            // `notify_waiters`, so a close that races this arming is caught by the recheck (no lost
326            // wakeup).
327            let notified = self.notify.notified();
328            if self.flag.load(Ordering::Acquire) {
329                return;
330            }
331            notified.await;
332        }
333    }
334}
335
336impl std::fmt::Debug for PeerSession {
337    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
338        f.debug_struct("PeerSession").finish_non_exhaustive()
339    }
340}
341
342impl PeerSession {
343    /// Wrap an established mTLS byte stream in yamux as the **client** (outbound-stream opener) and
344    /// spawn the driver. `io` is any tokio duplex stream (the mTLS [`tokio_rustls::client::TlsStream`]
345    /// or, in tests, a loopback stream). Returns the session; open streams with
346    /// [`Self::open_stream`] / [`Self::open_range_stream`].
347    pub fn client<S>(io: S) -> Self
348    where
349        S: AsyncRead + AsyncWrite + Send + Unpin + 'static,
350    {
351        Self::new(io, yamux::Mode::Client)
352    }
353
354    /// Wrap an established byte stream in yamux as the **server** (accepts inbound streams). Inbound
355    /// streams the peer opens are delivered via [`Self::accept_stream`]. Provided for symmetry + the
356    /// serving side of tests.
357    pub fn server<S>(io: S) -> Self
358    where
359        S: AsyncRead + AsyncWrite + Send + Unpin + 'static,
360    {
361        Self::new(io, yamux::Mode::Server)
362    }
363
364    fn new<S>(io: S, mode: yamux::Mode) -> Self
365    where
366        S: AsyncRead + AsyncWrite + Send + Unpin + 'static,
367    {
368        let (cmd_tx, cmd_rx) = tokio::sync::mpsc::channel::<MuxCommand>(64);
369        let (inbound_tx, inbound_rx) = tokio::sync::mpsc::channel::<PeerStream>(64);
370        let conn = yamux::Connection::new(io.compat(), yamux::Config::default(), mode);
371        let closed_flag = Arc::new(AtomicBool::new(false));
372        let closed_notify = Arc::new(Notify::new());
373        tokio::spawn(drive_connection(
374            conn,
375            cmd_rx,
376            inbound_tx,
377            Arc::clone(&closed_flag),
378            Arc::clone(&closed_notify),
379        ));
380        PeerSession {
381            cmd_tx,
382            inbound_rx,
383            closed_flag,
384            closed_notify,
385        }
386    }
387
388    /// A cloneable observer of this session's transport closing — see [`ClosedHandle`].
389    pub fn closed_handle(&self) -> ClosedHandle {
390        ClosedHandle {
391            flag: Arc::clone(&self.closed_flag),
392            notify: Arc::clone(&self.closed_notify),
393        }
394    }
395
396    /// Open a new outbound logical stream to the peer. Cheap — open as many as you need to run
397    /// concurrent transfers without head-of-line blocking.
398    pub async fn open_stream(&mut self) -> io::Result<PeerStream> {
399        let (tx, rx) = tokio::sync::oneshot::channel();
400        self.cmd_tx
401            .send(MuxCommand::OpenOutbound(tx))
402            .await
403            .map_err(|_| io::Error::other("mux driver closed"))?;
404        let stream = rx
405            .await
406            .map_err(|_| io::Error::other("mux driver dropped request"))?
407            .map_err(io::Error::other)?;
408        Ok(stream.compat())
409    }
410
411    /// Accept the next inbound logical stream the peer opened (server side). Returns `None` when the
412    /// connection has closed. A pure client never calls this.
413    pub async fn accept_stream(&mut self) -> Option<PeerStream> {
414        self.inbound_rx.recv().await
415    }
416
417    /// Open a `dig.fetchRange` stream for `req`: opens a fresh logical stream, writes the
418    /// [`RangeRequest`] preamble, and returns the stream for the caller to read [`RangeFrame`]s from
419    /// (via [`RangeFrame::decode`]) as they arrive. The building block for multi-source parallel
420    /// range downloads — open one of these per (peer, range) and read them concurrently.
421    pub async fn open_range_stream(&mut self, req: &RangeRequest) -> io::Result<PeerStream> {
422        let mut stream = self.open_stream().await?;
423        stream.write_all(&req.encode()).await?;
424        stream.flush().await?;
425        Ok(stream)
426    }
427
428    /// **Availability pre-check** (`dig.getAvailability`) — ask the peer which of `items` it holds,
429    /// BEFORE opening any range streams. Opens a short-lived control stream, writes the batched
430    /// [`AvailabilityRequest`], reads the [`AvailabilityResponse`]. A multi-source downloader runs
431    /// this against candidate peers and only range-fetches from holders — the normative flow is:
432    /// discover peers → `query_availability` (batch) → fan byte-ranges across holders → verify each
433    /// vs the chain-anchored root → retry a bad range from another holder → reassemble.
434    pub async fn query_availability(
435        &mut self,
436        items: Vec<AvailabilityItem>,
437    ) -> io::Result<AvailabilityResponse> {
438        let req = AvailabilityRequest { items };
439        let mut stream = self.open_stream().await?;
440        stream.write_all(&req.encode()).await?;
441        stream.flush().await?;
442        AvailabilityResponse::decode(&mut stream).await
443    }
444}
445
446/// Drive one yamux [`Connection`](yamux::Connection): concurrently service open-outbound commands
447/// and surface inbound streams, until the command channel closes (session dropped) or the connection
448/// errors. This is the task that replaces yamux 0.12's `Control`.
449///
450/// `T` is the futures-io view of the byte stream (a `tokio-util` [`Compat`] of the tokio mTLS
451/// stream), since yamux operates on `futures::AsyncRead + AsyncWrite`.
452async fn drive_connection<T>(
453    mut conn: yamux::Connection<T>,
454    mut cmd_rx: tokio::sync::mpsc::Receiver<MuxCommand>,
455    inbound_tx: tokio::sync::mpsc::Sender<PeerStream>,
456    closed_flag: Arc<AtomicBool>,
457    closed_notify: Arc<Notify>,
458) where
459    T: futures::AsyncRead + futures::AsyncWrite + Send + Unpin + 'static,
460{
461    use std::future::poll_fn;
462
463    loop {
464        tokio::select! {
465            // An open-outbound request from the session.
466            cmd = cmd_rx.recv() => {
467                match cmd {
468                    Some(MuxCommand::OpenOutbound(reply)) => {
469                        let res = poll_fn(|cx| conn.poll_new_outbound(cx)).await;
470                        let _ = reply.send(res.map_err(|e| e.to_string()));
471                    }
472                    None => {
473                        // Session dropped — close the connection and end the driver.
474                        let _ = poll_fn(|cx| conn.poll_close(cx)).await;
475                        break;
476                    }
477                }
478            }
479            // An inbound stream opened by the peer.
480            inbound = poll_fn(|cx| conn.poll_next_inbound(cx)) => {
481                match inbound {
482                    Some(Ok(stream)) => {
483                        // Deliver to a serving node; if no one is accepting, the stream is dropped.
484                        let _ = inbound_tx.try_send(stream.compat());
485                    }
486                    Some(Err(_)) | None => {
487                        // Connection closed / errored — end the driver.
488                        break;
489                    }
490                }
491            }
492        }
493    }
494
495    // The transport is gone: publish closure (flag BEFORE notify, so `ClosedHandle::closed`'s
496    // arm-then-recheck can never miss the wakeup).
497    closed_flag.store(true, Ordering::Release);
498    closed_notify.notify_waiters();
499}