Skip to main content

capsule_sdk/peering/
channel.rs

1//! Establishing the channel: mutually-authenticated TLS 1.3 with an application-layer hybrid
2//! identity check.
3//!
4//! A peer connection is a framed request/response exchange over a **mutually-authenticated TLS
5//! 1.3** channel with **no CA** — the device keys are the trust anchor. TLS 1.3 has no ML-DSA
6//! certificate path, so the split
7//! the peering doc mandates is honored exactly:
8//!
9//! 1. **Classical, at the TLS layer.** Each side presents a self-signed leaf ([`rcgen`]) and the
10//!    handshake proves possession of its classical private key. The certificates carry no trust
11//!    of their own — the accept-any verifiers below deliberately accept every well-formed peer
12//!    cert, because trust is decided one layer up.
13//! 2. **Hybrid, above the channel.** Once the handshake completes, each side derives the RFC 5705
14//!    **TLS exporter** keying material — a value cryptographically bound to *this* TLS session —
15//!    and signs it with its **hybrid** device key. The peer verifies that signature under the
16//!    key published for the claimed `device_id` in the shared, IK-signed [device directory]. A
17//!    MITM that re-terminated TLS would export different material and could not forge the
18//!    victim's hybrid signature over it, so the hybrid identity is bound to the channel. The
19//!    directory *is* the trust anchor: a device not in it — revoked, or a foreign user entirely —
20//!    cannot pass this check, and it runs **before any payload byte**.
21//!
22//! Around that core the channel enforces the rest of the peering trust model:
23//!
24//! - **Version window.** Each hello advertises a `[Min, Max]` peering-protocol window and the
25//!   pair speaks the highest common version; only disjoint windows end the connection, with a
26//!   typed [`PeeringError::VersionDisjoint`] naming which device must update.
27//! - **Directory anti-rollback.** The highest `directory_version` this device has verified is
28//!   persisted behind [`DirectoryVersions`]; a pinned directory below it is refused (a stale
29//!   directory cannot readmit a revoked device), and so is a peer presenting a lower version.
30//! - **Handshake rate limit.** [`accept`] admits a source address only through a
31//!   [`HandshakeLimiter`], so the LAN cannot probe a device for membership.
32//! - **Artifact secret.** A second exporter label yields the per-session [`ArtifactSecret`]
33//!   that seals a sync artifact: fresh per session, never stored, never a user passphrase.
34//! - **Lower Effort marking.** The channel carries bulk bytes (hand-offs, sync artifacts), so
35//!   both sides mark the socket with the Lower Effort DSCP before the handshake, best effort
36//!   ([`crate::net::mark_lower_effort`]).
37//!
38//! # After the handshake
39//!
40//! [`accept`] and [`connect`] keep the verified TLS stream and return it as a [`PeerChannel`],
41//! bound to the [`VerifiedPeer`] the hybrid check proved. There is no other path to a payload
42//! byte: nothing is ever sent outside the verified TLS session, and a failed check returns no
43//! channel at all.
44//!
45//! Over it the pair speaks small framed messages ([`Message`]): a one-byte tag, a big-endian
46//! `u32` length, and the payload — JSON for a control frame, raw bytes for a data frame. Every
47//! length is checked against its ceiling **before** a byte of the payload is read
48//! ([`MAX_FRAME`], [`MAX_DATA_FRAME`], [`MAX_RANGE`]), and every read and write is bounded in
49//! time, so a peer can neither make this device allocate without bound nor hold it forever.
50//!
51//! From [`OFFER_EXCHANGE_PROTOCOL`] the pulling side **opens** with its offer
52//! ([`PeerClient::open_offering`], read by [`PeerChannel::receive_offer`]): the padded, capped
53//! [offer pages](super::delta) of what it holds, or a frame saying it offers nothing. A pair
54//! below that version skips the opening, and the serving side lists what it would have offered
55//! without one.
56//!
57//! One side **serves** ([`serve`]): it lists the artifacts it offers ([`Offering`]), then
58//! answers ranged pulls of exactly those and takes acknowledgements, authorizing **each
59//! request** against the trust its [`TrustSource`] pins now ([`PeerSession::authorize`]), so a
60//! peer revoked mid-session is refused at its next request. The other side **pulls**
61//! ([`PeerClient`]): the transfer layer drives it through the shared resumable ranged fetch
62//! ([`super::pull_over_channel`]), which verifies the reassembled bytes against their content
63//! address. Every check runs against the identity the handshake verified
64//! ([`PeerChannel::peer`]), never against a device id a frame claims.
65//!
66//! [device directory]: https://docs/design/cryptography/keys/#device-directory
67
68use std::collections::BTreeMap;
69use std::fmt;
70use std::future::Future;
71use std::sync::Arc;
72use std::sync::atomic::{AtomicBool, Ordering};
73use std::time::{Duration, Instant};
74
75use bytes::Bytes;
76use capsule_core::crypto::keys::{
77    DeviceDirectory, DeviceEntry, HybridSignature, HybridVerifyingKey, Signer,
78};
79use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
80use rustls::crypto::{CryptoProvider, verify_tls12_signature, verify_tls13_signature};
81use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer, ServerName, UnixTime};
82use rustls::server::danger::{ClientCertVerified, ClientCertVerifier};
83use rustls::{
84    ClientConfig, DigitallySignedStruct, DistinguishedName, ServerConfig, SignatureScheme,
85};
86use serde::{Deserialize, Serialize};
87use tokio::io::{AsyncReadExt, AsyncWriteExt};
88use tokio::net::TcpStream;
89use tokio::sync::Mutex as AsyncMutex;
90use tokio_rustls::{TlsAcceptor, TlsConnector, TlsStream};
91use tracing::instrument;
92use uuid::Uuid;
93
94use super::PeeringError;
95use super::delegation::{DelegationError, HandOffAck};
96use super::delta::{MAX_OFFER_PAGE_BYTES, MAX_OFFER_PAGES, Offer, decode_offer_page};
97use super::session::{DirectoryVersions, HandshakeLimiter, PeerSession, TrustSource};
98use crate::net::negotiation::is_protocol_date;
99
100/// The newest peering **transport protocol** version this build speaks — the top of its
101/// [`VersionWindow`]. Date-based (`YYYY-MM-DD`), it shares the date grammar with the
102/// client-server protocol but is its **own version space**: peering values compare only against
103/// peering values, and the transport revs independently of the server protocol.
104pub const PEERING_PROTOCOL: &str = OFFER_EXCHANGE_PROTOCOL;
105
106/// The oldest peering transport protocol version this build still speaks — the bottom of its
107/// [`VersionWindow`]. `2026-10-23` added the framed exchange after the hello ([`Message`]); a
108/// peer older than that closes the channel after its hello and carries no payload, so it is
109/// outside the window and the pair is told which device to update.
110pub const PEERING_PROTOCOL_MIN: &str = "2026-10-23";
111
112/// The peering protocol version that added the **opening offer** ([`Message::Offer`]): on a
113/// channel negotiated at or above it, the pulling side opens with its offer (or says it offers
114/// nothing) before the serving side lists, so a sync artifact is cut to what the receiver is
115/// missing. A pair that negotiates below it exchanges no opening, and the serving side lists
116/// what it would have offered without one. The addition is additive: either version speaks the
117/// rest of the exchange unchanged.
118pub const OFFER_EXCHANGE_PROTOCOL: &str = "2026-10-29";
119
120/// How long a [`PeerClient`] that sent an opening waits for the listing: the serving side cuts
121/// and seals its artifact once it has read the opening (an offer, or that the receiver offers
122/// nothing) and only then lists, which can take far longer than one frame's I/O timeout. Added
123/// to that timeout.
124pub const LISTING_BUILD_ALLOWANCE: Duration = Duration::from_mins(10);
125
126/// The bound on the whole handshake: TLS, both hellos and the hybrid check. A peer that stalls
127/// it is dropped.
128pub const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(15);
129
130/// The default bound on every frame read and write after the handshake
131/// ([`PeerChannel::with_io_timeout`]).
132pub const DEFAULT_IO_TIMEOUT: Duration = Duration::from_secs(30);
133
134/// The slowest rate, in bytes per second, at which a [`PeerClient`] keeps pulling a ranged
135/// answer. Each answer of `len` bytes must arrive whole within the channel's I/O timeout plus
136/// `len` divided by this rate, so a peer that trickles frames just inside the per-frame timeout
137/// cannot hold the pulling side indefinitely.
138pub const MIN_PULL_RATE: u64 = 64 * 1024;
139
140/// The slowest rate, in bytes per second, at which a serving session expects its peer to verify
141/// and durably persist an artifact it pulled. While an offered artifact is unacknowledged, the
142/// session waits for the peer's next request for the channel's I/O timeout plus the largest such
143/// artifact's length at this rate ([`serve`]), so a large hand-off on slow storage is still
144/// acknowledged over the channel instead of timing out before its acknowledgement arrives.
145pub const MIN_PERSIST_RATE: u64 = 1024 * 1024;
146
147/// The largest data frame. A ranged answer is cut into frames of at most this many bytes.
148pub const MAX_DATA_FRAME: usize = 1024 * 1024;
149
150/// The most bytes one ranged request is answered with, whatever it asked for.
151pub const MAX_RANGE: u64 = crate::fetch::SINK_WINDOW;
152
153/// The most artifacts one [`Offering`] lists; it keeps a listing within [`MAX_FRAME`].
154pub const MAX_LISTING: usize = 256;
155
156/// The largest artifact an [`Offering`] lists and a [`PeerClient`] pulls.
157pub const MAX_ARTIFACT_LEN: u64 = 4 * 1024 * 1024 * 1024;
158
159/// The tag of a control frame: a JSON [`Message`].
160const TAG_CONTROL: u8 = 1;
161
162/// The tag of a data frame: raw bytes of the ranged answer in flight.
163const TAG_DATA: u8 = 2;
164
165/// Length of the exported channel-binding material the hybrid proof covers.
166const EXPORTER_LEN: usize = 32;
167
168/// The RFC 5705 exporter label. Distinct from any other exporter use so the derived material is
169/// domain-separated to peering's hybrid check.
170const EXPORTER_LABEL: &[u8] = b"EXPORTER-capsule-peering-hybrid-v1";
171
172/// The RFC 5705 exporter label the [`ArtifactSecret`] is derived under — distinct from
173/// [`EXPORTER_LABEL`], so the value that seals an artifact is never the value either side signed.
174const ARTIFACT_EXPORTER_LABEL: &[u8] = b"EXPORTER-capsule-peering-artifact-v1";
175
176/// The DNS name the client presents. The server verifier accepts any name — trust is the
177/// app-layer hybrid check — so this is only a syntactically-valid placeholder.
178const PEER_SNI: &str = "capsule-peer.local";
179
180/// Frame ceiling for the handshake hello (a `device_id`, a protocol string, and a hybrid
181/// signature) and for every control frame after it. Bounds a malicious length prefix.
182pub const MAX_FRAME: usize = 64 * 1024;
183
184/// The trust a device pins to authenticate its peers: the shared account's User IK and the
185/// IK-signed [`DeviceDirectory`]. Both same-user devices pin the *same* directory; a foreign
186/// device is simply absent from it, and a foreign directory fails to verify under our IK.
187#[derive(Debug, Clone)]
188pub struct PinnedTrust {
189    /// The shared account User IK public key — the directory's signer.
190    pub user_ik: HybridVerifyingKey,
191    /// The shared, IK-signed device directory listing this user's enrolled devices.
192    pub directory: DeviceDirectory,
193}
194
195impl PinnedTrust {
196    /// The `directory_version` of the pinned directory.
197    #[must_use]
198    pub fn directory_version(&self) -> u64 {
199        self.directory.core.directory_version
200    }
201}
202
203/// Admit the pinned directory: it must chain to the pinned User IK, and its version must not be
204/// below the highest this device has already verified (anti-rollback). An admitted version is
205/// recorded, so the floor only ever rises.
206pub(crate) fn admit_directory(
207    trust: &PinnedTrust,
208    versions: &dyn DirectoryVersions,
209) -> Result<(), PeeringError> {
210    if !trust.directory.verify(&trust.user_ik) {
211        return Err(PeeringError::ForeignIdentity);
212    }
213    let pinned = trust.directory_version();
214    let highest = versions.highest()?;
215    if pinned < highest {
216        tracing::warn!(
217            pinned,
218            highest,
219            "pinned device directory is older than one already verified; refusing"
220        );
221        return Err(PeeringError::DirectoryRollback { pinned, highest });
222    }
223    versions.record(pinned)?;
224    Ok(())
225}
226
227/// The directory entry for `device_id`, which must be present and un-revoked.
228pub(crate) fn admit_device(
229    trust: &PinnedTrust,
230    device_id: Uuid,
231) -> Result<&DeviceEntry, PeeringError> {
232    let entry = trust
233        .directory
234        .device(&device_id)
235        .ok_or(PeeringError::UnknownDevice(device_id))?;
236    if entry.revoked_at.is_some() {
237        return Err(PeeringError::RevokedDevice(device_id));
238    }
239    Ok(entry)
240}
241
242/// A device's supported peering-protocol window, `[min, max]`, both `YYYY-MM-DD`.
243#[derive(Debug, Clone, PartialEq, Eq)]
244pub struct VersionWindow {
245    /// The oldest peering protocol version spoken.
246    pub min: String,
247    /// The newest peering protocol version spoken.
248    pub max: String,
249}
250
251/// Which device must update for two disjoint windows to meet.
252#[derive(Debug, Clone, Copy, PartialEq, Eq)]
253pub enum UpdateDevice {
254    /// This device's window lies wholly below the peer's: update this device.
255    ThisDevice,
256    /// The peer's window lies wholly below this device's: update the peer.
257    Peer,
258}
259
260impl VersionWindow {
261    /// This build's window, [`PEERING_PROTOCOL_MIN`]`..=`[`PEERING_PROTOCOL`].
262    #[must_use]
263    pub fn ours() -> Self {
264        Self {
265            min: PEERING_PROTOCOL_MIN.to_string(),
266            max: PEERING_PROTOCOL.to_string(),
267        }
268    }
269
270    /// A window over two protocol dates. Refuses a value that is not `YYYY-MM-DD`, or a
271    /// `min` above `max`, as a codec error: such a hello cannot be negotiated against.
272    pub fn new(min: &str, max: &str) -> Result<Self, PeeringError> {
273        if !is_protocol_date(min) || !is_protocol_date(max) || min > max {
274            return Err(PeeringError::Codec(format!(
275                "malformed peering protocol window {min:?}..={max:?}"
276            )));
277        }
278        Ok(Self {
279            min: min.to_string(),
280            max: max.to_string(),
281        })
282    }
283
284    /// The highest version both windows contain, or [`PeeringError::VersionDisjoint`] naming
285    /// which device must update. Dates in `YYYY-MM-DD` order lexically.
286    pub fn negotiate(&self, theirs: &Self) -> Result<String, PeeringError> {
287        let high = self.max.as_str().min(theirs.max.as_str());
288        let low = self.min.as_str().max(theirs.min.as_str());
289        if high < low {
290            let update = if self.max < theirs.min {
291                UpdateDevice::ThisDevice
292            } else {
293                UpdateDevice::Peer
294            };
295            return Err(PeeringError::VersionDisjoint {
296                ours: self.clone(),
297                theirs: theirs.clone(),
298                update,
299            });
300        }
301        Ok(high.to_string())
302    }
303}
304
305impl fmt::Display for VersionWindow {
306    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
307        write!(f, "{}..={}", self.min, self.max)
308    }
309}
310
311/// The 256-bit secret that seals a peering sync artifact, derived from the channel's TLS exporter
312/// under its own peering label. Fresh per session, never stored, never a user passphrase; its
313/// `Debug` never prints the bytes.
314#[derive(Clone)]
315pub struct ArtifactSecret([u8; 32]);
316
317impl ArtifactSecret {
318    /// The secret's bytes, as the backup wrap takes them.
319    pub(crate) fn as_bytes(&self) -> &[u8; 32] {
320        &self.0
321    }
322
323    /// A secret over explicit bytes — only tests, which have no TLS session to export from.
324    #[cfg(test)]
325    pub(crate) fn from_bytes(bytes: [u8; 32]) -> Self {
326        Self(bytes)
327    }
328}
329
330impl fmt::Debug for ArtifactSecret {
331    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
332        f.write_str("ArtifactSecret(..)")
333    }
334}
335
336/// What this device brings to a handshake: who it is, the key it proves that with, the trust it
337/// pins, and where it keeps the highest directory version it has verified.
338#[derive(Clone, Copy)]
339pub struct LocalPeer<'a> {
340    /// This device's directory id.
341    pub device_id: Uuid,
342    /// This device's hybrid device-key signer.
343    pub signer: &'a dyn Signer,
344    /// The trust this device pins.
345    pub trust: &'a PinnedTrust,
346    /// The persisted anti-rollback floor.
347    pub versions: &'a dyn DirectoryVersions,
348}
349
350/// A peer whose hybrid identity was verified over the established channel.
351#[derive(Debug, Clone)]
352pub struct VerifiedPeer {
353    /// The peer's directory `device_id`, proven to hold the matching device key.
354    pub device_id: Uuid,
355    /// The peering protocol version the pair negotiated: the highest both windows contain.
356    pub protocol: String,
357    /// The channel-binding exporter material the proof covered (returned for provenance/tests).
358    pub exporter: [u8; EXPORTER_LEN],
359    /// The secret that seals this session's sync artifacts.
360    pub artifact_secret: ArtifactSecret,
361}
362
363/// The handshake hello each side sends over the encrypted channel: who it claims to be, the
364/// peering protocol window it speaks, the directory version it pins, and a hybrid signature over
365/// the channel-binding exporter material.
366#[derive(Debug, Clone, Serialize, Deserialize)]
367pub struct PeerHello {
368    /// The sender's directory device id.
369    pub device_id: Uuid,
370    /// The newest peering transport protocol version the sender speaks (its window's max).
371    pub peering_protocol: String,
372    /// The oldest version the sender speaks. Absent from a hello older than the window, which
373    /// spoke exactly `peering_protocol`.
374    #[serde(default, skip_serializing_if = "Option::is_none")]
375    pub peering_protocol_min: Option<String>,
376    /// The `directory_version` of the directory the sender pins. Absent (`0`) from a hello older
377    /// than the window.
378    #[serde(default)]
379    pub directory_version: u64,
380    /// A hybrid signature over the TLS exporter material — the proof this device holds the key
381    /// published for `device_id`.
382    pub proof: HybridSignature,
383}
384
385impl PeerHello {
386    /// The window this hello advertises.
387    pub fn window(&self) -> Result<VersionWindow, PeeringError> {
388        let max = self.peering_protocol.as_str();
389        VersionWindow::new(self.peering_protocol_min.as_deref().unwrap_or(max), max)
390    }
391}
392
393/// Which end of the channel a hello was sent from. The role is part of what the hybrid proof
394/// signs, so a hello one end sent never verifies as the other end's: a listener cannot reflect a
395/// dialer's own hello back at it.
396#[derive(Debug, Clone, Copy, PartialEq, Eq)]
397pub enum HandshakeRole {
398    /// The device that dialed ([`connect`]).
399    Dialer,
400    /// The device that accepted ([`accept`]).
401    Listener,
402}
403
404impl HandshakeRole {
405    /// The role at the other end of the channel.
406    #[must_use]
407    pub fn peer(self) -> Self {
408        match self {
409            Self::Dialer => Self::Listener,
410            Self::Listener => Self::Dialer,
411        }
412    }
413
414    fn tag(self) -> &'static [u8] {
415        match self {
416            Self::Dialer => b"dialer",
417            Self::Listener => b"listener",
418        }
419    }
420}
421
422/// The domain prefix of the message a hello's proof signs.
423const HELLO_PROOF_CONTEXT: &[u8] = b"capsule-peering-hello-v1/";
424
425/// The exact bytes a hello sent by `role` signs: a domain prefix, the sender's role, a
426/// separator, and the channel-binding `exporter`. Binding the role means the two hellos of one
427/// session sign different messages even though both ends derive the same exporter.
428pub(crate) fn hello_proof_message(role: HandshakeRole, exporter: &[u8; EXPORTER_LEN]) -> Vec<u8> {
429    let tag = role.tag();
430    let mut message = Vec::with_capacity(HELLO_PROOF_CONTEXT.len() + tag.len() + 1 + EXPORTER_LEN);
431    message.extend_from_slice(HELLO_PROOF_CONTEXT);
432    message.extend_from_slice(tag);
433    message.push(0);
434    message.extend_from_slice(exporter);
435    message
436}
437
438/// Build this device's hello as `role`: sign the role-bound channel-binding `exporter` with the
439/// device `signer`.
440fn build_hello(
441    local: &LocalPeer<'_>,
442    role: HandshakeRole,
443    exporter: &[u8; EXPORTER_LEN],
444) -> Result<PeerHello, PeeringError> {
445    let proof = local.signer.sign(&hello_proof_message(role, exporter))?;
446    Ok(PeerHello {
447        device_id: local.device_id,
448        peering_protocol: PEERING_PROTOCOL.to_string(),
449        peering_protocol_min: Some(PEERING_PROTOCOL_MIN.to_string()),
450        directory_version: local.trust.directory_version(),
451        proof,
452    })
453}
454
455/// The application-layer hybrid check — the whole security of the channel. Run **before any
456/// payload byte** against the locally-pinned trust. In order:
457///
458/// 1. **Version window.** The pair speaks the highest common version; disjoint windows abort
459///    with [`PeeringError::VersionDisjoint`] before any identity check.
460/// 2. **Directory chains to our IK.** The pinned directory must verify under our pinned User IK;
461///    a directory signed by a foreign IK is rejected outright.
462/// 3. **Anti-rollback.** The pinned directory must not be older than the highest this device has
463///    verified, and the peer must not present a version older than the one we pin.
464/// 4. **Not ourselves.** A hello claiming `local_device`, our own id, is refused with
465///    [`PeeringError::SelfPeer`]: a device never peers with itself.
466/// 5. **Enrolled + not revoked.** The claimed `device_id` must be present and un-revoked.
467/// 6. **Hybrid proof.** The peer's published device key must verify the hybrid signature over the
468///    exact exporter material *we* derived, bound to `from`: the role the peer holds on this
469///    channel, the opposite of ours. That binds the hybrid identity to
470///    this TLS session and to its far end, so a hello reflected back at its sender fails.
471///
472/// Returns the verified device id and the negotiated protocol version.
473pub fn verify_hello(
474    hello: &PeerHello,
475    from: HandshakeRole,
476    exporter: &[u8; EXPORTER_LEN],
477    local_device: Uuid,
478    trust: &PinnedTrust,
479    versions: &dyn DirectoryVersions,
480) -> Result<(Uuid, String), PeeringError> {
481    let protocol = VersionWindow::ours().negotiate(&hello.window()?)?;
482    admit_directory(trust, versions)?;
483    let ours = trust.directory_version();
484    if hello.directory_version < ours {
485        tracing::warn!(
486            device = %hello.device_id,
487            theirs = hello.directory_version,
488            ours,
489            "peer presented an older device directory; refusing"
490        );
491        return Err(PeeringError::PeerDirectoryStale {
492            theirs: hello.directory_version,
493            ours,
494        });
495    }
496    if hello.device_id == local_device {
497        tracing::warn!(
498            device = %hello.device_id,
499            "peer hello claims this device's own id; refusing"
500        );
501        return Err(PeeringError::SelfPeer(local_device));
502    }
503    let entry = admit_device(trust, hello.device_id)?;
504    if !entry
505        .dsk_public
506        .verify(&hello_proof_message(from, exporter), &hello.proof)
507    {
508        return Err(PeeringError::HybridCheckFailed);
509    }
510    tracing::debug!(
511        device = %hello.device_id,
512        %protocol,
513        "peer hybrid identity verified over the channel"
514    );
515    Ok((hello.device_id, protocol))
516}
517
518// ── mTLS config (CA-less; accept-any classical verifiers) ─────────────────────
519
520/// The pinned crypto provider (ring), so the peering stack never depends on an ambiguous
521/// process-default `CryptoProvider` when another (aws-lc-rs, via reqwest) is also linked.
522fn provider() -> Arc<CryptoProvider> {
523    Arc::new(rustls::crypto::ring::default_provider())
524}
525
526/// A fresh per-connection self-signed leaf + key. The certificate carries no trust — the peer's
527/// accept-any verifier accepts it and the hybrid check decides identity — so an ephemeral cert
528/// is exactly right.
529fn self_signed() -> Result<(CertificateDer<'static>, PrivateKeyDer<'static>), PeeringError> {
530    let certified = rcgen::generate_simple_self_signed(vec![PEER_SNI.to_string()])
531        .map_err(|e| PeeringError::Tls(e.to_string()))?;
532    let cert = CertificateDer::from(certified.cert.der().to_vec());
533    let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(
534        certified.signing_key.serialize_der(),
535    ));
536    Ok((cert, key))
537}
538
539/// A rustls server config: TLS 1.3 only, **mandatory** client auth, accept-any client cert.
540fn server_config() -> Result<ServerConfig, PeeringError> {
541    let (cert, key) = self_signed()?;
542    let p = provider();
543    let verifier = Arc::new(AcceptAnyPeerCert {
544        provider: p.clone(),
545    });
546    ServerConfig::builder_with_provider(p)
547        .with_protocol_versions(&[&rustls::version::TLS13])
548        .map_err(|e| PeeringError::Tls(e.to_string()))?
549        .with_client_cert_verifier(verifier)
550        .with_single_cert(vec![cert], key)
551        .map_err(|e| PeeringError::Tls(e.to_string()))
552}
553
554/// A rustls client config: TLS 1.3 only, accept-any server cert, presenting our client cert.
555fn client_config() -> Result<ClientConfig, PeeringError> {
556    let (cert, key) = self_signed()?;
557    let p = provider();
558    let verifier = Arc::new(AcceptAnyPeerCert {
559        provider: p.clone(),
560    });
561    ClientConfig::builder_with_provider(p)
562        .with_protocol_versions(&[&rustls::version::TLS13])
563        .map_err(|e| PeeringError::Tls(e.to_string()))?
564        .dangerous()
565        .with_custom_certificate_verifier(verifier)
566        .with_client_auth_cert(vec![cert], key)
567        .map_err(|e| PeeringError::Tls(e.to_string()))
568}
569
570/// The accept-any verifier used on **both** ends. It deliberately accepts every well-formed peer
571/// certificate: in a CA-less design the certificate proves only classical key possession, and
572/// *identity* is decided by the app-layer hybrid check. Signature checks (that the peer actually
573/// holds the presented cert's key) are still delegated to the crypto provider — the handshake
574/// remains a real mutual TLS 1.3 handshake.
575#[derive(Debug)]
576struct AcceptAnyPeerCert {
577    provider: Arc<CryptoProvider>,
578}
579
580impl ServerCertVerifier for AcceptAnyPeerCert {
581    fn verify_server_cert(
582        &self,
583        _end_entity: &CertificateDer<'_>,
584        _intermediates: &[CertificateDer<'_>],
585        _server_name: &ServerName<'_>,
586        _ocsp_response: &[u8],
587        _now: UnixTime,
588    ) -> Result<ServerCertVerified, rustls::Error> {
589        Ok(ServerCertVerified::assertion())
590    }
591
592    fn verify_tls12_signature(
593        &self,
594        message: &[u8],
595        cert: &CertificateDer<'_>,
596        dss: &DigitallySignedStruct,
597    ) -> Result<HandshakeSignatureValid, rustls::Error> {
598        verify_tls12_signature(
599            message,
600            cert,
601            dss,
602            &self.provider.signature_verification_algorithms,
603        )
604    }
605
606    fn verify_tls13_signature(
607        &self,
608        message: &[u8],
609        cert: &CertificateDer<'_>,
610        dss: &DigitallySignedStruct,
611    ) -> Result<HandshakeSignatureValid, rustls::Error> {
612        verify_tls13_signature(
613            message,
614            cert,
615            dss,
616            &self.provider.signature_verification_algorithms,
617        )
618    }
619
620    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
621        self.provider
622            .signature_verification_algorithms
623            .supported_schemes()
624    }
625}
626
627impl ClientCertVerifier for AcceptAnyPeerCert {
628    fn root_hint_subjects(&self) -> &[DistinguishedName] {
629        &[]
630    }
631
632    fn verify_client_cert(
633        &self,
634        _end_entity: &CertificateDer<'_>,
635        _intermediates: &[CertificateDer<'_>],
636        _now: UnixTime,
637    ) -> Result<ClientCertVerified, rustls::Error> {
638        Ok(ClientCertVerified::assertion())
639    }
640
641    fn verify_tls12_signature(
642        &self,
643        message: &[u8],
644        cert: &CertificateDer<'_>,
645        dss: &DigitallySignedStruct,
646    ) -> Result<HandshakeSignatureValid, rustls::Error> {
647        verify_tls12_signature(
648            message,
649            cert,
650            dss,
651            &self.provider.signature_verification_algorithms,
652        )
653    }
654
655    fn verify_tls13_signature(
656        &self,
657        message: &[u8],
658        cert: &CertificateDer<'_>,
659        dss: &DigitallySignedStruct,
660    ) -> Result<HandshakeSignatureValid, rustls::Error> {
661        verify_tls13_signature(
662            message,
663            cert,
664            dss,
665            &self.provider.signature_verification_algorithms,
666        )
667    }
668
669    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
670        self.provider
671            .signature_verification_algorithms
672            .supported_schemes()
673    }
674
675    fn offer_client_auth(&self) -> bool {
676        true
677    }
678
679    fn client_auth_mandatory(&self) -> bool {
680        true
681    }
682}
683
684// ── Handshake drivers ─────────────────────────────────────────────────────────
685
686fn io_err(e: std::io::Error) -> PeeringError {
687    PeeringError::Io(e.to_string())
688}
689
690async fn write_frame<W>(w: &mut W, payload: &[u8]) -> Result<(), PeeringError>
691where
692    W: AsyncWriteExt + Unpin,
693{
694    let len = u32::try_from(payload.len())
695        .map_err(|_| PeeringError::Codec("hello frame exceeds u32".into()))?;
696    w.write_u32(len).await.map_err(io_err)?;
697    w.write_all(payload).await.map_err(io_err)?;
698    w.flush().await.map_err(io_err)?;
699    Ok(())
700}
701
702async fn read_frame<R>(r: &mut R) -> Result<Vec<u8>, PeeringError>
703where
704    R: AsyncReadExt + Unpin,
705{
706    let len = r.read_u32().await.map_err(io_err)? as usize;
707    if len > MAX_FRAME {
708        return Err(PeeringError::Codec("hello frame too large".into()));
709    }
710    let mut buf = vec![0u8; len];
711    r.read_exact(&mut buf).await.map_err(io_err)?;
712    Ok(buf)
713}
714
715fn encode(hello: &PeerHello) -> Result<Vec<u8>, PeeringError> {
716    serde_json::to_vec(hello).map_err(|e| PeeringError::Codec(e.to_string()))
717}
718
719fn decode(bytes: &[u8]) -> Result<PeerHello, PeeringError> {
720    serde_json::from_slice(bytes).map_err(|e| PeeringError::Codec(e.to_string()))
721}
722
723/// Derive both exporter values from an established TLS session: the channel-binding material the
724/// hybrid proof signs, and the [`ArtifactSecret`] under its own label.
725fn derive_exporters(
726    export: impl Fn(&[u8]) -> Result<[u8; EXPORTER_LEN], rustls::Error>,
727) -> Result<([u8; EXPORTER_LEN], ArtifactSecret), PeeringError> {
728    let tls = |e: rustls::Error| PeeringError::Tls(e.to_string());
729    let binding = export(EXPORTER_LABEL).map_err(tls)?;
730    let secret = ArtifactSecret(export(ARTIFACT_EXPORTER_LABEL).map_err(tls)?);
731    Ok((binding, secret))
732}
733
734/// Verify the hello the peer sent while we hold `role`, and assemble the [`VerifiedPeer`].
735fn finish(
736    peer_bytes: &[u8],
737    role: HandshakeRole,
738    exporter: [u8; EXPORTER_LEN],
739    artifact_secret: ArtifactSecret,
740    local: &LocalPeer<'_>,
741) -> Result<VerifiedPeer, PeeringError> {
742    let peer_hello = decode(peer_bytes)?;
743    let (device_id, protocol) = verify_hello(
744        &peer_hello,
745        role.peer(),
746        &exporter,
747        local.device_id,
748        local.trust,
749        local.versions,
750    )?;
751    Ok(VerifiedPeer {
752        device_id,
753        protocol,
754        exporter,
755        artifact_secret,
756    })
757}
758
759/// Run `step`, refusing with [`PeeringError::Timeout`] naming `what` once `limit` passes.
760async fn within<T>(
761    limit: Duration,
762    what: &'static str,
763    step: impl Future<Output = Result<T, PeeringError>>,
764) -> Result<T, PeeringError> {
765    tokio::time::timeout(limit, step)
766        .await
767        .map_err(|_| PeeringError::Timeout(what))?
768}
769
770/// **Server side** of the peering handshake. Admits the source address through `limiter`
771/// (refusing with [`PeeringError::RateLimited`] before any TLS byte), completes a real mutual
772/// TLS 1.3 handshake over `tcp`, derives the channel-binding exporter, exchanges hellos
773/// (read-then-write, so the pair never deadlocks), and runs the [`verify_hello`] check, all
774/// within [`HANDSHAKE_TIMEOUT`]. Returns the verified channel or the specific rejection — a
775/// wrong/revoked/foreign/stale peer fails the whole handshake before any payload, and no channel
776/// exists to send one over.
777#[instrument(skip(tcp, local, limiter), fields(local = %local.device_id))]
778pub async fn accept(
779    tcp: TcpStream,
780    local: LocalPeer<'_>,
781    limiter: &HandshakeLimiter,
782) -> Result<PeerChannel, PeeringError> {
783    let source = tcp.peer_addr().map_err(io_err)?.ip();
784    if !limiter.admit(source, Instant::now()) {
785        tracing::warn!(%source, "peering handshake rate limit reached; refusing");
786        return Err(PeeringError::RateLimited(source));
787    }
788    crate::net::mark_lower_effort(&tcp);
789    let acceptor = TlsAcceptor::from(Arc::new(server_config()?));
790    within(HANDSHAKE_TIMEOUT, "the handshake", async {
791        let mut tls = acceptor.accept(tcp).await.map_err(io_err)?;
792
793        let (exporter, secret) = {
794            let (_io, conn) = tls.get_ref();
795            derive_exporters(|label| conn.export_keying_material([0u8; EXPORTER_LEN], label, None))?
796        };
797
798        let peer_bytes = read_frame(&mut tls).await?;
799        let our_hello = build_hello(&local, HandshakeRole::Listener, &exporter)?;
800        write_frame(&mut tls, &encode(&our_hello)?).await?;
801
802        let peer = finish(
803            &peer_bytes,
804            HandshakeRole::Listener,
805            exporter,
806            secret,
807            &local,
808        )?;
809        Ok(PeerChannel::new(TlsStream::Server(tls), peer))
810    })
811    .await
812}
813
814/// **Client side** of the peering handshake. The dialing device connects, drives the TLS 1.3
815/// handshake to completion, derives the same exporters, exchanges hellos (write-then-read), and
816/// runs the hybrid check, all within [`HANDSHAKE_TIMEOUT`]. See [`accept`] for the security
817/// contract.
818#[instrument(skip(tcp, local), fields(local = %local.device_id))]
819pub async fn connect(tcp: TcpStream, local: LocalPeer<'_>) -> Result<PeerChannel, PeeringError> {
820    crate::net::mark_lower_effort(&tcp);
821    let connector = TlsConnector::from(Arc::new(client_config()?));
822    let name = ServerName::try_from(PEER_SNI)
823        .map_err(|e| PeeringError::Tls(e.to_string()))?
824        .to_owned();
825    within(HANDSHAKE_TIMEOUT, "the handshake", async {
826        let mut tls = connector.connect(name, tcp).await.map_err(io_err)?;
827
828        let (exporter, secret) = {
829            let (_io, conn) = tls.get_ref();
830            derive_exporters(|label| conn.export_keying_material([0u8; EXPORTER_LEN], label, None))?
831        };
832
833        let our_hello = build_hello(&local, HandshakeRole::Dialer, &exporter)?;
834        write_frame(&mut tls, &encode(&our_hello)?).await?;
835        let peer_bytes = read_frame(&mut tls).await?;
836
837        let peer = finish(&peer_bytes, HandshakeRole::Dialer, exporter, secret, &local)?;
838        Ok(PeerChannel::new(TlsStream::Client(tls), peer))
839    })
840    .await
841}
842
843// ── The verified channel ──────────────────────────────────────────────────────
844
845/// An established, verified peering channel: the TLS 1.3 stream the handshake completed, bound to
846/// the peer whose hybrid identity it verified. Every frame after the handshake travels inside
847/// this TLS session and nowhere else.
848pub struct PeerChannel {
849    stream: TlsStream<TcpStream>,
850    peer: VerifiedPeer,
851    io_timeout: Duration,
852    /// Whether the opening offer has been sent or read, or the protocol has none.
853    opened: bool,
854}
855
856impl fmt::Debug for PeerChannel {
857    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
858        f.debug_struct("PeerChannel")
859            .field("peer", &self.peer.device_id)
860            .field("protocol", &self.peer.protocol)
861            .field("io_timeout", &self.io_timeout)
862            .finish_non_exhaustive()
863    }
864}
865
866impl PeerChannel {
867    fn new(stream: TlsStream<TcpStream>, peer: VerifiedPeer) -> Self {
868        tracing::debug!(peer = %peer.device_id, protocol = %peer.protocol, "peering channel established");
869        let opened = !speaks_offers(&peer.protocol);
870        Self {
871            stream,
872            peer,
873            io_timeout: DEFAULT_IO_TIMEOUT,
874            opened,
875        }
876    }
877
878    /// Test-only: speak `protocol` as if the pair had negotiated it, to stand in for an older
879    /// peer on a real channel.
880    #[cfg(test)]
881    #[must_use]
882    pub(crate) fn speaking(mut self, protocol: &str) -> Self {
883        self.peer.protocol = protocol.to_owned();
884        self.opened = !speaks_offers(protocol);
885        self
886    }
887
888    /// The serving side: read the pulling side's opening offer, before anything is listed.
889    ///
890    /// `None` when the pair negotiated a protocol below [`OFFER_EXCHANGE_PROTOCOL`] (an older
891    /// peer sends no opening, and nothing is read), or when the peer said it offers nothing. An
892    /// offer is at most [`MAX_OFFER_PAGES`] pages, each a data frame decoded by
893    /// [`decode_offer_page`], and all of them must carry the same cursor.
894    ///
895    /// # Errors
896    ///
897    /// [`PeeringError::Codec`] for an opening read twice, a frame that is not an offer, too
898    /// many pages, or a malformed page; [`PeeringError::PeerRefused`] when the peer refused the
899    /// session; or the channel's I/O or timeout failure.
900    #[instrument(skip_all, fields(peer = %self.peer.device_id))]
901    pub async fn receive_offer(&mut self) -> Result<Option<Offer>, PeeringError> {
902        if !speaks_offers(&self.peer.protocol) {
903            tracing::debug!(protocol = %self.peer.protocol, "peering: the peer's protocol carries no offer");
904            return Ok(None);
905        }
906        if self.opened {
907            return Err(PeeringError::Codec(
908                "the opening offer was already exchanged".into(),
909            ));
910        }
911        self.opened = true;
912        let pages = match self.recv().await? {
913            Message::Offer { pages } => pages as usize,
914            Message::Refused { kind, message } => {
915                return Err(PeeringError::PeerRefused { kind, message });
916            }
917            other => {
918                return Err(PeeringError::Codec(format!(
919                    "expected an offer, the peer sent {}",
920                    other.name()
921                )));
922            }
923        };
924        if pages == 0 {
925            tracing::debug!("peering: the peer offers nothing");
926            return Ok(None);
927        }
928        if pages > MAX_OFFER_PAGES {
929            return Err(PeeringError::Codec(format!(
930                "an offer of {pages} pages exceeds the {MAX_OFFER_PAGES}-page ceiling"
931            )));
932        }
933        let mut decoded = Vec::with_capacity(pages);
934        for _ in 0..pages {
935            let page = self.recv_data(MAX_OFFER_PAGE_BYTES).await?;
936            decoded.push(decode_offer_page(&page)?);
937        }
938        let offer = Offer::from_pages(&decoded)?;
939        tracing::info!(
940            pages,
941            addresses = offer.addresses.len(),
942            cursor = offer.cursor,
943            "peering: the peer's offer received"
944        );
945        Ok(Some(offer))
946    }
947
948    /// The pulling side: send the opening — `offer`'s pages, or that it offers nothing — when
949    /// the pair's protocol carries one and it has not been sent. Returns whether an opening
950    /// went: the serving side builds its listing only once it has read one, whether it offers
951    /// pages or nothing (an offer over the page ceiling degrades to nothing), so the caller
952    /// waits for the listing with [`LISTING_BUILD_ALLOWANCE`] in either case.
953    async fn send_opening(&mut self, offer: Option<&Offer>) -> Result<bool, PeeringError> {
954        if self.opened {
955            return Ok(false);
956        }
957        self.opened = true;
958        let pages = match offer.map(Offer::encode_pages) {
959            Some(pages) if pages.len() > MAX_OFFER_PAGES => {
960                // A whole-library listing is still correct (ingest makes a held asset a no-op),
961                // so an offer too large to carry degrades to none rather than ending the session.
962                tracing::warn!(
963                    pages = pages.len(),
964                    "peering: the offer exceeds the page ceiling; offering nothing"
965                );
966                Vec::new()
967            }
968            Some(pages) => pages,
969            None => Vec::new(),
970        };
971        // `pages.len() <= MAX_OFFER_PAGES`, which fits a u32.
972        self.send(&Message::Offer {
973            pages: pages.len() as u32,
974        })
975        .await?;
976        for page in &pages {
977            self.send_data(page).await?;
978        }
979        tracing::debug!(pages = pages.len(), "peering: opening sent");
980        Ok(true)
981    }
982
983    /// The peer the handshake verified. Every authorization on this channel is decided against
984    /// this identity, never against a device id a frame claims.
985    #[must_use]
986    pub fn peer(&self) -> &VerifiedPeer {
987        &self.peer
988    }
989
990    /// The verified peer, dropping the stream (closing the channel).
991    #[must_use]
992    pub fn into_peer(self) -> VerifiedPeer {
993        self.peer
994    }
995
996    /// Bound every later frame read and write by `timeout` instead of [`DEFAULT_IO_TIMEOUT`].
997    #[must_use]
998    pub fn with_io_timeout(mut self, timeout: Duration) -> Self {
999        self.io_timeout = timeout;
1000        self
1001    }
1002
1003    /// Send one control message.
1004    pub(crate) async fn send(&mut self, message: &Message) -> Result<(), PeeringError> {
1005        let payload =
1006            serde_json::to_vec(message).map_err(|e| PeeringError::Codec(e.to_string()))?;
1007        if payload.len() > MAX_FRAME {
1008            return Err(PeeringError::Codec(
1009                "control frame exceeds its ceiling".into(),
1010            ));
1011        }
1012        tracing::trace!(peer = %self.peer.device_id, kind = message.name(), "peering: send");
1013        self.write_tagged(TAG_CONTROL, &payload).await
1014    }
1015
1016    /// Receive one control message.
1017    pub(crate) async fn recv(&mut self) -> Result<Message, PeeringError> {
1018        self.recv_within(self.io_timeout).await
1019    }
1020
1021    /// Receive one control message, waiting at most `limit` for the whole frame rather than the
1022    /// channel's I/O timeout.
1023    pub(crate) async fn recv_within(&mut self, limit: Duration) -> Result<Message, PeeringError> {
1024        let payload = self.read_tagged(TAG_CONTROL, MAX_FRAME, limit).await?;
1025        let message: Message =
1026            serde_json::from_slice(&payload).map_err(|e| PeeringError::Codec(e.to_string()))?;
1027        tracing::trace!(peer = %self.peer.device_id, kind = message.name(), "peering: received");
1028        Ok(message)
1029    }
1030
1031    /// Send one data frame (at most [`MAX_DATA_FRAME`] bytes).
1032    pub(crate) async fn send_data(&mut self, bytes: &[u8]) -> Result<(), PeeringError> {
1033        if bytes.len() > MAX_DATA_FRAME {
1034            return Err(PeeringError::Codec("data frame exceeds its ceiling".into()));
1035        }
1036        self.write_tagged(TAG_DATA, bytes).await
1037    }
1038
1039    /// Receive one data frame of at most `at_most` bytes.
1040    pub(crate) async fn recv_data(&mut self, at_most: usize) -> Result<Vec<u8>, PeeringError> {
1041        self.read_tagged(TAG_DATA, at_most.min(MAX_DATA_FRAME), self.io_timeout)
1042            .await
1043    }
1044
1045    /// Close the sending half, so the peer reads end-of-stream rather than waiting out its
1046    /// timeout. Best effort: the channel is being dropped either way.
1047    pub(crate) async fn close(&mut self) {
1048        let timeout = self.io_timeout;
1049        let _closed = tokio::time::timeout(timeout, self.stream.shutdown()).await;
1050    }
1051
1052    async fn write_tagged(&mut self, tag: u8, payload: &[u8]) -> Result<(), PeeringError> {
1053        let len = u32::try_from(payload.len())
1054            .map_err(|_| PeeringError::Codec("frame exceeds u32".into()))?;
1055        let stream = &mut self.stream;
1056        within(self.io_timeout, "writing a frame", async {
1057            stream.write_u8(tag).await.map_err(io_err)?;
1058            stream.write_u32(len).await.map_err(io_err)?;
1059            stream.write_all(payload).await.map_err(io_err)?;
1060            stream.flush().await.map_err(io_err)
1061        })
1062        .await
1063    }
1064
1065    /// Read one frame within `limit`, which must carry `tag` and at most `max` bytes. The length
1066    /// is checked before any of the payload is read or allocated.
1067    async fn read_tagged(
1068        &mut self,
1069        tag: u8,
1070        max: usize,
1071        limit: Duration,
1072    ) -> Result<Vec<u8>, PeeringError> {
1073        let stream = &mut self.stream;
1074        within(limit, "reading a frame", async {
1075            let found = stream.read_u8().await.map_err(io_err)?;
1076            if found != tag {
1077                return Err(PeeringError::Codec(format!(
1078                    "expected a frame tagged {tag}, the peer sent {found}"
1079                )));
1080            }
1081            let len = stream.read_u32().await.map_err(io_err)? as usize;
1082            if len > max {
1083                return Err(PeeringError::Codec(format!(
1084                    "a {len}-byte frame exceeds the {max}-byte ceiling"
1085                )));
1086            }
1087            let mut payload = vec![0u8; len];
1088            stream.read_exact(&mut payload).await.map_err(io_err)?;
1089            Ok(payload)
1090        })
1091        .await
1092    }
1093}
1094
1095/// One artifact a serving peer offers: its content address and length. Both are the server's
1096/// claims until the pulled bytes hash to the address.
1097#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1098pub struct Offered {
1099    /// The artifact's content address (SHA-256, lowercase hex).
1100    pub address: String,
1101    /// Its length in bytes.
1102    pub len: u64,
1103}
1104
1105/// The control messages the channel carries after the handshake. From
1106/// [`OFFER_EXCHANGE_PROTOCOL`] the pulling side opens with [`Offer`](Self::Offer); the serving
1107/// side then sends [`Listing`](Self::Listing); the pulling side then sends requests, each
1108/// answered before the next is sent.
1109#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1110#[serde(tag = "type", rename_all = "snake_case")]
1111pub enum Message {
1112    /// Client → server, first, from [`OFFER_EXCHANGE_PROTOCOL`]: the pulling side's offer
1113    /// follows in `pages` data frames, each one padded page ([`Offer::encode_pages`]). `0`
1114    /// says it offers nothing, and takes whatever is listed.
1115    Offer {
1116        /// How many page frames follow, at most [`MAX_OFFER_PAGES`].
1117        pages: u32,
1118    },
1119    /// Server → client: the artifacts this session serves. Nothing else is served.
1120    Listing {
1121        /// The offered artifacts.
1122        artifacts: Vec<Offered>,
1123    },
1124    /// Client → server: bytes of `address` from `start`, at most `max_len` (or [`MAX_RANGE`]).
1125    Range {
1126        /// The artifact's content address.
1127        address: String,
1128        /// The first byte wanted.
1129        start: u64,
1130        /// The most bytes wanted; the server never sends more than [`MAX_RANGE`].
1131        max_len: Option<u64>,
1132    },
1133    /// Server → client: `len` bytes follow, in data frames.
1134    RangeReply {
1135        /// How many bytes follow.
1136        len: u64,
1137    },
1138    /// Client → server: the delegate verified and durably persisted a hand-off.
1139    Ack {
1140        /// The acknowledgement.
1141        ack: HandOffAck,
1142    },
1143    /// Server → client: the acknowledgement was taken.
1144    Acked,
1145    /// Server → client: the request was refused. `kind` is a stable name
1146    /// ([`PeeringError::kind`], [`DelegationError::kind`]).
1147    Refused {
1148        /// The stable name of the refusal.
1149        kind: String,
1150        /// The English detail.
1151        message: String,
1152    },
1153    /// Client → server: the session is over.
1154    Done,
1155}
1156
1157impl Message {
1158    /// The message's type, for logs.
1159    fn name(&self) -> &'static str {
1160        match self {
1161            Self::Offer { .. } => "offer",
1162            Self::Listing { .. } => "listing",
1163            Self::Range { .. } => "range",
1164            Self::RangeReply { .. } => "range_reply",
1165            Self::Ack { .. } => "ack",
1166            Self::Acked => "acked",
1167            Self::Refused { .. } => "refused",
1168            Self::Done => "done",
1169        }
1170    }
1171}
1172
1173/// Whether a channel negotiated at `protocol` carries the opening offer. Dates in `YYYY-MM-DD`
1174/// order lexically.
1175fn speaks_offers(protocol: &str) -> bool {
1176    protocol >= OFFER_EXCHANGE_PROTOCOL
1177}
1178
1179/// Whether `address` is a SHA-256 content address in its canonical spelling.
1180fn is_address(address: &str) -> bool {
1181    address.len() == 64
1182        && address
1183            .bytes()
1184            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
1185}
1186
1187// ── Serving ───────────────────────────────────────────────────────────────────
1188
1189/// The artifacts one serving session offers, each under the content address this device
1190/// computed over its bytes.
1191#[derive(Default)]
1192pub struct Offering {
1193    artifacts: BTreeMap<String, Bytes>,
1194    /// Test-only: sever the channel once this many data bytes have been sent.
1195    #[cfg(test)]
1196    pub(crate) sever_after: Option<u64>,
1197}
1198
1199impl fmt::Debug for Offering {
1200    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1201        f.debug_list().entries(self.listing()).finish()
1202    }
1203}
1204
1205impl Offering {
1206    /// An empty offering.
1207    #[must_use]
1208    pub fn new() -> Self {
1209        Self::default()
1210    }
1211
1212    /// Offer `bytes`, returning the content address it is served under. The offering shares
1213    /// `bytes` rather than copying them: a `Vec<u8>` converts without a copy, and a [`Bytes`]
1214    /// the caller keeps is the same allocation.
1215    ///
1216    /// # Errors
1217    ///
1218    /// [`PeeringError::Codec`] past [`MAX_LISTING`] artifacts or for an artifact over
1219    /// [`MAX_ARTIFACT_LEN`].
1220    pub fn offer(&mut self, bytes: impl Into<Bytes>) -> Result<String, PeeringError> {
1221        let bytes = bytes.into();
1222        if bytes.len() as u64 > MAX_ARTIFACT_LEN {
1223            return Err(PeeringError::Codec(
1224                "an artifact exceeds the offer ceiling".into(),
1225            ));
1226        }
1227        let address = super::transfer::artifact_address(&bytes);
1228        if !self.artifacts.contains_key(&address) && self.artifacts.len() >= MAX_LISTING {
1229            return Err(PeeringError::Codec(format!(
1230                "an offering lists at most {MAX_LISTING} artifacts"
1231            )));
1232        }
1233        self.artifacts.insert(address.clone(), bytes);
1234        Ok(address)
1235    }
1236
1237    /// Test-only: the bytes served under `address`.
1238    #[cfg(test)]
1239    pub(crate) fn served(&self, address: &str) -> Option<&Bytes> {
1240        self.artifacts.get(address)
1241    }
1242
1243    /// Whether `address` is offered.
1244    #[must_use]
1245    pub fn contains(&self, address: &str) -> bool {
1246        self.artifacts.contains_key(address)
1247    }
1248
1249    /// What the listing frame carries.
1250    #[must_use]
1251    pub fn listing(&self) -> Vec<Offered> {
1252        self.artifacts
1253            .iter()
1254            .map(|(address, bytes)| Offered {
1255                address: address.clone(),
1256                len: bytes.len() as u64,
1257            })
1258            .collect()
1259    }
1260
1261    /// How long a serving session waits for the peer's next request once `acks` are taken:
1262    /// `io_timeout`, plus the largest offered artifact no acknowledgement names yet at
1263    /// [`MIN_PERSIST_RATE`] — the peer may be verifying and persisting it before it asks again.
1264    /// Once every artifact is acknowledged, the wait is `io_timeout` alone.
1265    pub(crate) fn request_budget(&self, io_timeout: Duration, acks: &[HandOffAck]) -> Duration {
1266        let pending = self
1267            .artifacts
1268            .iter()
1269            .filter(|(address, _)| !acks.iter().any(|ack| &ack.hand_off == *address))
1270            .map(|(_, bytes)| bytes.len() as u64)
1271            .max()
1272            .unwrap_or(0);
1273        io_timeout.saturating_add(Duration::from_millis(
1274            pending.saturating_mul(1000) / MIN_PERSIST_RATE,
1275        ))
1276    }
1277}
1278
1279/// One ranged answer a serving session sent.
1280#[derive(Debug, Clone, PartialEq, Eq)]
1281pub struct ServedRange {
1282    /// The artifact.
1283    pub address: String,
1284    /// The first byte sent.
1285    pub start: u64,
1286    /// How many bytes were sent.
1287    pub len: u64,
1288}
1289
1290/// What a serving session did.
1291#[derive(Debug, Clone, Default)]
1292pub struct ServeReport {
1293    /// Every ranged answer, in order.
1294    pub served: Vec<ServedRange>,
1295    /// Every acknowledgement taken, in order.
1296    pub acks: Vec<HandOffAck>,
1297}
1298
1299/// Serve `offering` to the channel's verified peer until it says it is done.
1300///
1301/// Reads the peer's opening offer first when the caller has not ([`PeerChannel::receive_offer`])
1302/// and sets it aside, then sends the listing, then answers each request in turn:
1303///
1304/// - **Every request is authorized first** against the trust `trust` pins now
1305///   ([`PeerSession::authorize`]): a peer revoked, or gone from the directory, since the
1306///   handshake is refused and the session ends — as it does when `trust` cannot produce current
1307///   trust (fail closed).
1308/// - **A ranged pull** is answered only for an offered address, with at most [`MAX_RANGE`]
1309///   bytes in data frames of at most [`MAX_DATA_FRAME`].
1310/// - **An acknowledgement** is taken only when it names the verified peer as the delegate and an
1311///   offered address; then `on_ack` decides it. Its refusal is reported to the peer and the
1312///   session goes on.
1313/// - **The wait for each request** is the channel's I/O timeout plus the largest
1314///   unacknowledged offered artifact at [`MIN_PERSIST_RATE`]: the peer verifies and persists a
1315///   pulled artifact before it acknowledges it, and that takes longer than one frame's timeout
1316///   for a large artifact on slow storage.
1317///
1318/// # Errors
1319///
1320/// The [`PeeringError`] that ended the session: an authorization refusal, a malformed or
1321/// unexpected frame, a timeout, or the channel failing.
1322#[instrument(skip_all, fields(peer = %channel.peer.device_id, offered = offering.artifacts.len()))]
1323pub async fn serve<T, F>(
1324    channel: &mut PeerChannel,
1325    offering: &Offering,
1326    trust: &T,
1327    versions: &dyn DirectoryVersions,
1328    mut on_ack: F,
1329) -> Result<ServeReport, PeeringError>
1330where
1331    T: TrustSource,
1332    F: FnMut(&HandOffAck) -> Result<(), DelegationError> + Send,
1333{
1334    let mut session = PeerSession::new(&channel.peer);
1335    let mut report = ServeReport::default();
1336    #[cfg(test)]
1337    let mut sent_data: u64 = 0;
1338    if !channel.opened {
1339        // The caller cut its offering without the peer's offer (a delegation does), so the
1340        // opening is read and set aside: the offering is what this session serves either way.
1341        let offer = channel.receive_offer().await?;
1342        tracing::debug!(
1343            offered = offer.as_ref().map(|offer| offer.addresses.len()),
1344            "peering: an opening offer set aside"
1345        );
1346    }
1347    channel
1348        .send(&Message::Listing {
1349            artifacts: offering.listing(),
1350        })
1351        .await?;
1352    loop {
1353        let budget = offering.request_budget(channel.io_timeout, &report.acks);
1354        tracing::trace!(?budget, "peering: awaiting the next request");
1355        let request = channel.recv_within(budget).await?;
1356        if request == Message::Done {
1357            tracing::info!(
1358                served = report.served.len(),
1359                acks = report.acks.len(),
1360                "peering: session done"
1361            );
1362            channel.close().await;
1363            return Ok(report);
1364        }
1365        let authorized = match trust.current().await {
1366            Ok(now) => session.authorize(&now, versions),
1367            Err(error) => Err(error),
1368        };
1369        if let Err(error) = authorized {
1370            tracing::warn!(%error, "peering: request refused; ending the session");
1371            refuse(channel, error.kind(), &error.to_string()).await;
1372            channel.close().await;
1373            return Err(error);
1374        }
1375        match request {
1376            Message::Range {
1377                address,
1378                start,
1379                max_len,
1380            } => {
1381                let Some(bytes) = offering.artifacts.get(&address) else {
1382                    refuse(channel, "not_offered", "the artifact is not offered").await;
1383                    continue;
1384                };
1385                let total = bytes.len() as u64;
1386                if start > total {
1387                    refuse(
1388                        channel,
1389                        "range_not_satisfiable",
1390                        "the range starts past the end",
1391                    )
1392                    .await;
1393                    continue;
1394                }
1395                let len = max_len
1396                    .unwrap_or(MAX_RANGE)
1397                    .min(MAX_RANGE)
1398                    .min(total - start);
1399                channel.send(&Message::RangeReply { len }).await?;
1400                let from = usize::try_from(start)
1401                    .map_err(|_| PeeringError::Codec("range start exceeds usize".into()))?;
1402                let to = from
1403                    + usize::try_from(len)
1404                        .map_err(|_| PeeringError::Codec("range exceeds usize".into()))?;
1405                for frame in bytes[from..to].chunks(MAX_DATA_FRAME) {
1406                    #[cfg(test)]
1407                    if let Some(limit) = offering.sever_after
1408                        && sent_data + frame.len() as u64 > limit
1409                    {
1410                        let keep = usize::try_from(limit.saturating_sub(sent_data)).unwrap_or(0);
1411                        channel.send_data(&frame[..keep]).await?;
1412                        channel.close().await;
1413                        return Err(PeeringError::Io("severed by the test".into()));
1414                    }
1415                    channel.send_data(frame).await?;
1416                    #[cfg(test)]
1417                    {
1418                        sent_data += frame.len() as u64;
1419                    }
1420                }
1421                tracing::debug!(%address, start, len, "peering: served a range");
1422                report.served.push(ServedRange {
1423                    address,
1424                    start,
1425                    len,
1426                });
1427            }
1428            Message::Ack { ack } => {
1429                let verdict = if ack.delegate_device != channel.peer.device_id
1430                    || !offering.contains(&ack.hand_off)
1431                {
1432                    // An acknowledgement speaks for the verified peer about what this session
1433                    // offered, or for nothing.
1434                    Err(DelegationError::AckMismatch)
1435                } else {
1436                    on_ack(&ack)
1437                };
1438                match verdict {
1439                    Ok(()) => {
1440                        channel.send(&Message::Acked).await?;
1441                        tracing::info!(asset_id = %ack.asset_id, hand_off = %ack.hand_off, "peering: acknowledgement taken");
1442                        report.acks.push(ack);
1443                    }
1444                    Err(error) => {
1445                        tracing::warn!(%error, "peering: acknowledgement refused");
1446                        refuse(channel, error.kind(), &error.to_string()).await;
1447                    }
1448                }
1449            }
1450            other => {
1451                let error = PeeringError::Codec(format!(
1452                    "the peer sent {} where a request belongs",
1453                    other.name()
1454                ));
1455                refuse(channel, error.kind(), &error.to_string()).await;
1456                channel.close().await;
1457                return Err(error);
1458            }
1459        }
1460    }
1461}
1462
1463/// Tell the peer its request was refused. Best effort: a channel that cannot carry the refusal
1464/// is ending anyway.
1465async fn refuse(channel: &mut PeerChannel, kind: &str, message: &str) {
1466    let refusal = Message::Refused {
1467        kind: kind.to_owned(),
1468        message: message.to_owned(),
1469    };
1470    if let Err(error) = channel.send(&refusal).await {
1471        tracing::debug!(%error, "peering: could not deliver a refusal");
1472    }
1473}
1474
1475// ── Pulling ───────────────────────────────────────────────────────────────────
1476
1477/// A ranged pull that failed, with the bytes that arrived before it did, so a resumed pull
1478/// starts after them.
1479#[derive(Debug)]
1480pub struct RangeFailure {
1481    /// The bytes received before the failure, from the requested start.
1482    pub received: Vec<u8>,
1483    /// Why it failed.
1484    pub error: PeeringError,
1485}
1486
1487/// The pulling side of a verified channel: it reads the serving peer's listing, then makes
1488/// requests one at a time. Its requests take `&self`, so it can back a
1489/// [`BlobSource`](crate::fetch::BlobSource) ([`super::ChannelBlobSource`]).
1490///
1491/// Once any exchange fails part-way, the stream's framing can no longer be trusted: the client
1492/// is **broken** and refuses every later request rather than reading a stray frame as an answer.
1493pub struct PeerClient {
1494    channel: AsyncMutex<PeerChannel>,
1495    peer: VerifiedPeer,
1496    listing: Vec<Offered>,
1497    broken: AtomicBool,
1498}
1499
1500impl fmt::Debug for PeerClient {
1501    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1502        f.debug_struct("PeerClient")
1503            .field("peer", &self.peer.device_id)
1504            .field("listing", &self.listing)
1505            .field("broken", &self.is_broken())
1506            .finish_non_exhaustive()
1507    }
1508}
1509
1510impl PeerClient {
1511    /// Read the serving peer's listing, first saying this device offers nothing where the
1512    /// pair's protocol carries an opening offer. A listing with more than [`MAX_LISTING`]
1513    /// artifacts, an address that is not a content address, or an artifact longer than
1514    /// [`MAX_ARTIFACT_LEN`] is refused whole.
1515    ///
1516    /// # Errors
1517    ///
1518    /// [`PeeringError::Codec`] for a malformed listing, [`PeeringError::PeerRefused`] when the
1519    /// peer refused the session, or the channel's I/O or timeout failure.
1520    pub async fn open(channel: PeerChannel) -> Result<Self, PeeringError> {
1521        Self::open_with(channel, None).await
1522    }
1523
1524    /// As [`open`](Self::open), first sending `offer` — what this device holds and its cursor —
1525    /// so the serving side lists an artifact cut to what this device is missing. On a channel
1526    /// negotiated below [`OFFER_EXCHANGE_PROTOCOL`] nothing is sent, and the peer lists what it
1527    /// would have without an offer. Once an opening is sent — this offer, or nothing where the
1528    /// offer exceeds [`MAX_OFFER_PAGES`] — the listing is awaited for the I/O timeout plus
1529    /// [`LISTING_BUILD_ALLOWANCE`], while the peer cuts and seals its artifact; so is the
1530    /// listing [`open`](Self::open) awaits on a channel that carries an opening.
1531    ///
1532    /// # Errors
1533    ///
1534    /// As [`open`](Self::open), and the channel's failure while sending the offer.
1535    pub async fn open_offering(channel: PeerChannel, offer: &Offer) -> Result<Self, PeeringError> {
1536        Self::open_with(channel, Some(offer)).await
1537    }
1538
1539    #[instrument(skip_all, fields(peer = %channel.peer.device_id, offering = offer.is_some()))]
1540    async fn open_with(
1541        mut channel: PeerChannel,
1542        offer: Option<&Offer>,
1543    ) -> Result<Self, PeeringError> {
1544        let offered = channel.send_opening(offer).await?;
1545        let wait = if offered {
1546            channel.io_timeout.saturating_add(LISTING_BUILD_ALLOWANCE)
1547        } else {
1548            channel.io_timeout
1549        };
1550        let listing = match channel.recv_within(wait).await? {
1551            Message::Listing { artifacts } => artifacts,
1552            Message::Refused { kind, message } => {
1553                return Err(PeeringError::PeerRefused { kind, message });
1554            }
1555            other => {
1556                return Err(PeeringError::Codec(format!(
1557                    "expected a listing, the peer sent {}",
1558                    other.name()
1559                )));
1560            }
1561        };
1562        if listing.len() > MAX_LISTING
1563            || listing
1564                .iter()
1565                .any(|offered| !is_address(&offered.address) || offered.len > MAX_ARTIFACT_LEN)
1566        {
1567            return Err(PeeringError::Codec(
1568                "the peer's listing is malformed".into(),
1569            ));
1570        }
1571        tracing::debug!(peer = %channel.peer.device_id, offered = listing.len(), "peering: listing received");
1572        Ok(Self {
1573            peer: channel.peer.clone(),
1574            channel: AsyncMutex::new(channel),
1575            listing,
1576            broken: AtomicBool::new(false),
1577        })
1578    }
1579
1580    /// The peer the handshake verified.
1581    #[must_use]
1582    pub fn peer(&self) -> &VerifiedPeer {
1583        &self.peer
1584    }
1585
1586    /// What the peer offers.
1587    #[must_use]
1588    pub fn listing(&self) -> &[Offered] {
1589        &self.listing
1590    }
1591
1592    /// Whether an exchange failed part-way, so the client refuses every later request.
1593    #[must_use]
1594    pub fn is_broken(&self) -> bool {
1595        self.broken.load(Ordering::Acquire)
1596    }
1597
1598    fn check_usable(&self) -> Result<(), PeeringError> {
1599        if self.is_broken() {
1600            return Err(PeeringError::Io("the channel broke earlier".into()));
1601        }
1602        Ok(())
1603    }
1604
1605    /// Run one exchange; any failure but a clean refusal breaks the client.
1606    fn settle<T>(&self, result: Result<T, PeeringError>) -> Result<T, PeeringError> {
1607        if let Err(error) = &result
1608            && !matches!(error, PeeringError::PeerRefused { .. })
1609        {
1610            self.broken.store(true, Ordering::Release);
1611        }
1612        result
1613    }
1614
1615    /// Pull bytes of `address` from `start`: at most `max_len`, and never more than
1616    /// [`MAX_RANGE`]. The bytes are the peer's until the whole artifact hashes to its address.
1617    /// The answer must arrive whole within the channel's I/O timeout plus its length at
1618    /// [`MIN_PULL_RATE`].
1619    ///
1620    /// # Errors
1621    ///
1622    /// A [`RangeFailure`] carrying whatever arrived before the failure; its error is
1623    /// [`PeeringError::Timeout`] when a frame, or the whole answer, came too slowly.
1624    pub async fn range(
1625        &self,
1626        address: &str,
1627        start: u64,
1628        max_len: Option<u64>,
1629    ) -> Result<Vec<u8>, RangeFailure> {
1630        let fail = |received, error| RangeFailure { received, error };
1631        if let Err(error) = self.check_usable() {
1632            return Err(fail(Vec::new(), error));
1633        }
1634        let cap = max_len.unwrap_or(MAX_RANGE).min(MAX_RANGE);
1635        let mut channel = self.channel.lock().await;
1636        let reply = async {
1637            channel
1638                .send(&Message::Range {
1639                    address: address.to_owned(),
1640                    start,
1641                    max_len: Some(cap),
1642                })
1643                .await?;
1644            match channel.recv().await? {
1645                Message::RangeReply { len } if len <= cap => Ok(len),
1646                Message::RangeReply { len } => Err(PeeringError::Codec(format!(
1647                    "the peer answered {len} bytes to a request for at most {cap}"
1648                ))),
1649                Message::Refused { kind, message } => {
1650                    Err(PeeringError::PeerRefused { kind, message })
1651                }
1652                other => Err(PeeringError::Codec(format!(
1653                    "expected a range reply, the peer sent {}",
1654                    other.name()
1655                ))),
1656            }
1657        }
1658        .await;
1659        let len = match self.settle(reply) {
1660            Ok(len) => len,
1661            Err(error) => return Err(fail(Vec::new(), error)),
1662        };
1663        let budget = channel.io_timeout.saturating_add(Duration::from_millis(
1664            len.saturating_mul(1000) / MIN_PULL_RATE,
1665        ));
1666        let deadline = tokio::time::Instant::now() + budget;
1667        tracing::trace!(peer = %self.peer.device_id, len, ?budget, "peering: pulling a range");
1668        let mut received = Vec::new();
1669        while (received.len() as u64) < len {
1670            let remaining = usize::try_from(len - received.len() as u64).unwrap_or(usize::MAX);
1671            let Ok(frame) = tokio::time::timeout_at(deadline, channel.recv_data(remaining)).await
1672            else {
1673                // Every frame arrived inside its own timeout, but too slowly overall: the peer
1674                // is holding this pull open without making progress worth waiting for.
1675                self.broken.store(true, Ordering::Release);
1676                tracing::warn!(peer = %self.peer.device_id, len, received = received.len(), "peering: a range fell below the minimum pull rate");
1677                let error = PeeringError::Timeout("pulling a range below the minimum rate");
1678                return Err(fail(received, error));
1679            };
1680            match self.settle(frame) {
1681                Ok(frame) if frame.is_empty() => {
1682                    // An empty frame makes no progress: a peer sending them would hold this
1683                    // loop for ever.
1684                    self.broken.store(true, Ordering::Release);
1685                    let error = PeeringError::Codec("the peer sent an empty data frame".into());
1686                    return Err(fail(received, error));
1687                }
1688                Ok(frame) => received.extend_from_slice(&frame),
1689                Err(error) => return Err(fail(received, error)),
1690            }
1691        }
1692        Ok(received)
1693    }
1694
1695    /// Deliver an acknowledgement and wait for the peer to take it.
1696    ///
1697    /// # Errors
1698    ///
1699    /// [`PeeringError::PeerRefused`] when the peer refused it, or the channel's failure.
1700    pub async fn acknowledge(&self, ack: &HandOffAck) -> Result<(), PeeringError> {
1701        self.check_usable()?;
1702        let mut channel = self.channel.lock().await;
1703        let result = async {
1704            channel.send(&Message::Ack { ack: ack.clone() }).await?;
1705            match channel.recv().await? {
1706                Message::Acked => Ok(()),
1707                Message::Refused { kind, message } => {
1708                    Err(PeeringError::PeerRefused { kind, message })
1709                }
1710                other => Err(PeeringError::Codec(format!(
1711                    "expected an acknowledgement reply, the peer sent {}",
1712                    other.name()
1713                ))),
1714            }
1715        }
1716        .await;
1717        self.settle(result)
1718    }
1719
1720    /// End the session: tell the peer, and close the stream.
1721    ///
1722    /// # Errors
1723    ///
1724    /// The channel's failure, when the peer could not be told.
1725    pub async fn finish(&self) -> Result<(), PeeringError> {
1726        self.check_usable()?;
1727        let mut channel = self.channel.lock().await;
1728        let sent = channel.send(&Message::Done).await;
1729        channel.close().await;
1730        self.settle(sent)
1731    }
1732}