Skip to main content

tlsn/
session.rs

1use std::{
2    future::Future,
3    pin::Pin,
4    sync::{
5        Arc, Mutex,
6        atomic::{AtomicBool, Ordering},
7    },
8    task::{Context, Poll, Waker},
9};
10
11use futures::{AsyncRead, AsyncWrite};
12use mpz_common::{Session as MpzSession, ThreadPool, ThreadPoolBuildError, io::Io, mux::Mux};
13use tlsn_core::config::{prover::ProverConfig, verifier::VerifierConfig};
14use tlsn_mux::{Connection, Handle};
15
16use crate::{
17    Error, Result,
18    prover::{Prover, state as prover_state},
19    verifier::{Verifier, state as verifier_state},
20};
21
22/// Configuration for a [`Session`].
23#[derive(Debug, Clone)]
24pub struct SessionConfig {
25    mux: tlsn_mux::Config,
26}
27
28impl SessionConfig {
29    /// Creates a new builder.
30    pub fn builder() -> SessionConfigBuilder {
31        SessionConfigBuilder::default()
32    }
33
34    /// Returns the underlying [`tlsn_mux::Config`].
35    fn to_mux_config(&self) -> tlsn_mux::Config {
36        self.mux.clone()
37    }
38}
39
40impl Default for SessionConfig {
41    fn default() -> Self {
42        Self {
43            mux: session_mux_config(None).expect("default mux config is valid"),
44        }
45    }
46}
47
48/// Builds a [`tlsn_mux::Config`] with the session's fixed settings applied.
49///
50/// All mux-specific invariants (e.g. the receive window / stream limit
51/// coupling) are validated by [`tlsn_mux::ConfigBuilder`].
52fn session_mux_config(
53    max_num_streams: Option<usize>,
54) -> Result<tlsn_mux::Config, tlsn_mux::ConfigError> {
55    let mut builder = tlsn_mux::Config::builder()
56        .keep_alive(true)
57        .close_sync(true);
58
59    if let Some(max_num_streams) = max_num_streams {
60        builder = builder.max_num_streams(max_num_streams);
61    }
62
63    builder.build()
64}
65
66/// Builder for [`SessionConfig`].
67#[derive(Debug, Default)]
68pub struct SessionConfigBuilder {
69    max_num_streams: Option<usize>,
70}
71
72impl SessionConfigBuilder {
73    /// Sets the maximum number of concurrent streams per session.
74    ///
75    /// Defaults to the mux default (512) when unset. The limit is bounded by
76    /// the session's receive window (1 GiB by default); higher values are
77    /// rejected by [`build`](Self::build).
78    pub fn max_num_streams(mut self, max_num_streams: usize) -> Self {
79        self.max_num_streams = Some(max_num_streams);
80        self
81    }
82
83    /// Builds the configuration.
84    ///
85    /// Returns an error if the requested stream limit exceeds what the
86    /// session's receive window supports.
87    pub fn build(self) -> Result<SessionConfig, SessionConfigError> {
88        Ok(SessionConfig {
89            mux: session_mux_config(self.max_num_streams)?,
90        })
91    }
92}
93
94/// Error for [`SessionConfig`].
95#[derive(Debug, thiserror::Error)]
96#[error(transparent)]
97pub struct SessionConfigError(#[from] tlsn_mux::ConfigError);
98
99/// Tracks whether the session connection has ended.
100///
101/// Protocol participants register their waker here so they can be cancelled
102/// when the connection is lost, even if no I/O they currently own would wake
103/// them.
104#[derive(Debug, Default)]
105pub(crate) struct SessionClosure {
106    closed: AtomicBool,
107    wakers: Mutex<Vec<Waker>>,
108}
109
110impl SessionClosure {
111    /// Marks the session as closed and wakes all registered participants.
112    fn close(&self) {
113        if self.closed.swap(true, Ordering::AcqRel) {
114            return;
115        }
116        let wakers: Vec<Waker> = self.wakers.lock().unwrap().drain(..).collect();
117        for waker in wakers {
118            waker.wake();
119        }
120    }
121
122    /// Returns whether the session has closed.
123    pub(crate) fn is_closed(&self) -> bool {
124        self.closed.load(Ordering::Acquire)
125    }
126
127    /// Registers a waker to be woken if the session closes.
128    pub(crate) fn register(&self, waker: &Waker) {
129        let mut wakers = self.wakers.lock().unwrap();
130
131        // Re-check under the lock: `close()` may have run between the caller's
132        // own check and this registration.
133        if self.is_closed() {
134            drop(wakers);
135            waker.wake_by_ref();
136            return;
137        }
138
139        if !wakers.iter().any(|w| w.will_wake(waker)) {
140            wakers.push(waker.clone());
141        }
142    }
143
144    /// Returns a future that resolves when the session closes.
145    pub(crate) fn closed(&self) -> Closed<'_> {
146        Closed { closure: self }
147    }
148}
149
150/// Future that resolves once the session connection has closed.
151pub(crate) struct Closed<'a> {
152    closure: &'a SessionClosure,
153}
154
155impl Future for Closed<'_> {
156    type Output = ();
157
158    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
159        self.closure.register(cx.waker());
160        if self.closure.is_closed() {
161            Poll::Ready(())
162        } else {
163            Poll::Pending
164        }
165    }
166}
167
168/// Closes the session when dropped.
169///
170/// This is a field rather than a [`Drop`] implementation on [`Session`] so
171/// that [`Session::split`] can still move the session's fields into the
172/// driver and handle.
173struct ClosureGuard(Arc<SessionClosure>);
174
175impl ClosureGuard {
176    fn share(&self) -> Arc<SessionClosure> {
177        self.0.clone()
178    }
179
180    fn close(&self) {
181        self.0.close();
182    }
183}
184
185impl Drop for ClosureGuard {
186    fn drop(&mut self) {
187        // The session may be dropped without ever completing (e.g. the task
188        // driving it is aborted). Participants must still learn that the
189        // session is gone.
190        self.0.close();
191    }
192}
193
194/// A TLSNotary session over a communication channel.
195///
196/// Wraps an async IO stream and provides multiplexing for the protocol. Use
197/// [`new_prover`](Self::new_prover) or [`new_verifier`](Self::new_verifier) to
198/// create protocol participants.
199///
200/// The session must be polled continuously (either directly or via
201/// [`split`](Self::split)) to drive the underlying connection. After the
202/// session closes, the underlying IO can be reclaimed with
203/// [`try_take`](Self::try_take).
204///
205/// **Important**: The order in which provers and verifiers are created must
206/// match on both sides. For example, if the prover side calls `new_prover`
207/// then `new_verifier`, the verifier side must call `new_verifier` then
208/// `new_prover`.
209#[must_use = "session must be polled continuously to make progress, including during closing."]
210pub struct Session<Io> {
211    conn: Option<Connection<Io>>,
212    executor: MpzSession,
213    handle: Handle,
214    closure: ClosureGuard,
215}
216
217impl<Io> Session<Io>
218where
219    Io: AsyncRead + AsyncWrite + Unpin,
220{
221    /// Creates a new session over `io`, the prover ↔ verifier channel.
222    ///
223    /// On TCP transports, disable Nagle's algorithm; see
224    /// [Performance](crate#performance).
225    pub fn new(io: Io) -> Self {
226        Self::new_with_config(io, SessionConfig::default())
227    }
228
229    /// Creates a new session over `io` with the given configuration.
230    ///
231    /// On TCP transports, disable Nagle's algorithm; see
232    /// [Performance](crate#performance).
233    pub fn new_with_config(io: Io, config: SessionConfig) -> Self {
234        let mux_config = config.to_mux_config();
235
236        let conn = tlsn_mux::Connection::new(io, mux_config);
237        let handle = conn.handle().expect("handle should be available");
238        let executor = build_executor(MuxHandle {
239            handle: handle.clone(),
240        });
241
242        Self {
243            conn: Some(conn),
244            executor,
245            handle,
246            closure: ClosureGuard(Arc::new(SessionClosure::default())),
247        }
248    }
249
250    /// Creates a new prover.
251    pub fn new_prover(
252        &mut self,
253        config: ProverConfig,
254    ) -> Result<Prover<prover_state::Initialized>> {
255        let ctx = self.executor.new_context().map_err(|e| {
256            Error::internal()
257                .with_msg("failed to create new prover")
258                .with_source(e)
259        })?;
260
261        Ok(Prover::new(
262            ctx,
263            self.handle.clone(),
264            config,
265            self.closure.share(),
266        ))
267    }
268
269    /// Creates a new verifier.
270    pub fn new_verifier(
271        &mut self,
272        config: VerifierConfig,
273    ) -> Result<Verifier<verifier_state::Initialized>> {
274        let ctx = self.executor.new_context().map_err(|e| {
275            Error::internal()
276                .with_msg("failed to create new verifier")
277                .with_source(e)
278        })?;
279
280        Ok(Verifier::new(
281            ctx,
282            self.handle.clone(),
283            config,
284            self.closure.share(),
285        ))
286    }
287
288    /// Returns `true` if the session is closed.
289    pub fn is_closed(&self) -> bool {
290        self.conn
291            .as_ref()
292            .map(|mux| mux.is_complete())
293            .unwrap_or_default()
294    }
295
296    /// Closes the session.
297    ///
298    /// This will cause the session to begin closing. Session must continue to
299    /// be polled until completion.
300    pub fn close(&mut self) {
301        if let Some(conn) = self.conn.as_mut() {
302            conn.close()
303        }
304    }
305
306    /// Attempts to take the IO, returning an error if it is not available.
307    pub fn try_take(&mut self) -> Result<Io> {
308        let conn = self.conn.take().ok_or_else(|| {
309            Error::io().with_msg("failed to take the session io, it was already taken")
310        })?;
311
312        match conn.try_into_io() {
313            Err(conn) => {
314                self.conn = Some(conn);
315                Err(Error::io()
316                    .with_msg("failed to take the session io, session was not completed yet"))
317            }
318            Ok(conn) => Ok(conn),
319        }
320    }
321
322    /// Polls the session.
323    pub fn poll(&mut self, cx: &mut Context<'_>) -> Poll<Result<()>> {
324        let poll = self
325            .conn
326            .as_mut()
327            .ok_or_else(|| {
328                Error::io()
329                    .with_msg("failed to poll the session connection because it has been taken")
330            })?
331            .poll(cx)
332            .map_err(|e| {
333                Error::io()
334                    .with_msg("error occurred while polling the session connection")
335                    .with_source(e)
336            });
337
338        if poll.is_ready() {
339            self.closure.close();
340        }
341
342        poll
343    }
344
345    /// Splits the session into a driver and handle.
346    ///
347    /// The driver must be polled to make progress. The handle is used
348    /// for creating provers/verifiers and closing the session.
349    pub fn split(self) -> (SessionDriver<Io>, SessionHandle) {
350        let should_close = Arc::new(AtomicBool::new(false));
351        let waker = Arc::new(Mutex::new(None::<Waker>));
352        let handle_closure = self.closure.share();
353
354        (
355            SessionDriver {
356                conn: self.conn,
357                should_close: should_close.clone(),
358                waker: waker.clone(),
359                closure: self.closure,
360            },
361            SessionHandle {
362                executor: self.executor,
363                should_close,
364                waker,
365                handle: self.handle,
366                closure: handle_closure,
367            },
368        )
369    }
370}
371
372impl<Io> Future for Session<Io>
373where
374    Io: AsyncRead + AsyncWrite + Unpin,
375{
376    type Output = Result<()>;
377
378    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
379        Session::poll(&mut (*self), cx)
380    }
381}
382
383/// The polling half of a split session.
384///
385/// Must be polled continuously to drive the session. Returns the underlying
386/// IO when the session closes.
387#[must_use = "driver must be polled to make progress"]
388pub struct SessionDriver<Io> {
389    conn: Option<Connection<Io>>,
390    should_close: Arc<AtomicBool>,
391    waker: Arc<Mutex<Option<Waker>>>,
392    closure: ClosureGuard,
393}
394
395impl<Io> SessionDriver<Io>
396where
397    Io: AsyncRead + AsyncWrite + Unpin,
398{
399    /// Polls the driver.
400    pub fn poll(&mut self, cx: &mut Context<'_>) -> Poll<Result<Io>> {
401        // Store the waker so the handle can wake us when close() is called.
402        {
403            let mut waker_guard = self.waker.lock().unwrap();
404            *waker_guard = Some(cx.waker().clone());
405        }
406
407        let conn = self
408            .conn
409            .as_mut()
410            .ok_or_else(|| Error::io().with_msg("session driver already completed"))?;
411
412        if self.should_close.load(Ordering::Acquire) {
413            conn.close();
414        }
415
416        match conn.poll(cx) {
417            Poll::Ready(Ok(())) => {
418                self.closure.close();
419            }
420            Poll::Ready(Err(e)) => {
421                self.closure.close();
422                return Poll::Ready(Err(Error::io()
423                    .with_msg("error polling session connection")
424                    .with_source(e)));
425            }
426            Poll::Pending => return Poll::Pending,
427        }
428
429        let conn = self.conn.take().unwrap();
430        Poll::Ready(
431            conn.try_into_io()
432                .map_err(|_| Error::io().with_msg("failed to take session io")),
433        )
434    }
435}
436
437impl<Io> Future for SessionDriver<Io>
438where
439    Io: AsyncRead + AsyncWrite + Unpin,
440{
441    type Output = Result<Io>;
442
443    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
444        SessionDriver::poll(&mut *self, cx)
445    }
446}
447
448/// The control half of a split session.
449///
450/// Used to create provers/verifiers and control the session lifecycle.
451pub struct SessionHandle {
452    executor: MpzSession,
453    should_close: Arc<AtomicBool>,
454    waker: Arc<Mutex<Option<Waker>>>,
455    handle: Handle,
456    closure: Arc<SessionClosure>,
457}
458
459impl SessionHandle {
460    /// Creates a new prover.
461    pub fn new_prover(
462        &mut self,
463        config: ProverConfig,
464    ) -> Result<Prover<prover_state::Initialized>> {
465        let ctx = self.executor.new_context().map_err(|e| {
466            Error::internal()
467                .with_msg("failed to create new prover")
468                .with_source(e)
469        })?;
470
471        Ok(Prover::new(
472            ctx,
473            self.handle.clone(),
474            config,
475            self.closure.clone(),
476        ))
477    }
478
479    /// Creates a new verifier.
480    pub fn new_verifier(
481        &mut self,
482        config: VerifierConfig,
483    ) -> Result<Verifier<verifier_state::Initialized>> {
484        let ctx = self.executor.new_context().map_err(|e| {
485            Error::internal()
486                .with_msg("failed to create new verifier")
487                .with_source(e)
488        })?;
489
490        Ok(Verifier::new(
491            ctx,
492            self.handle.clone(),
493            config,
494            self.closure.clone(),
495        ))
496    }
497
498    /// Signals the session to close.
499    ///
500    /// The driver must continue to be polled until it completes.
501    pub fn close(&self) {
502        self.should_close.store(true, Ordering::Release);
503        if let Some(waker) = self.waker.lock().unwrap().take() {
504            waker.wake();
505        }
506    }
507}
508
509/// Multiplexer controller providing streams.
510struct MuxHandle {
511    handle: Handle,
512}
513
514impl std::fmt::Debug for MuxHandle {
515    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
516        f.debug_struct("MuxHandle").finish_non_exhaustive()
517    }
518}
519
520impl Mux for MuxHandle {
521    fn open(&self, id: &[u8]) -> Result<Io, std::io::Error> {
522        let stream = self.handle.new_stream(id).map_err(std::io::Error::other)?;
523        let io = Io::from_io(stream);
524
525        Ok(io)
526    }
527}
528
529/// Builds a session backed by the process-wide global thread pool, with the
530/// given muxer.
531fn build_executor(mux: MuxHandle) -> MpzSession {
532    #[cfg(all(feature = "web", target_arch = "wasm32"))]
533    let cores = web_spawn::available_parallelism().map(|n| n.get());
534
535    #[cfg(not(all(feature = "web", target_arch = "wasm32")))]
536    let cores = std::thread::available_parallelism().map(|n| n.get());
537
538    let builder = ThreadPool::builder().num_threads(cores.unwrap_or(8));
539
540    #[cfg(all(feature = "web", target_arch = "wasm32"))]
541    let builder = builder.spawn(|f| {
542        let _ = web_spawn::spawn(f);
543        Ok(())
544    });
545
546    // Install our configured pool as the process-wide global pool on first
547    // use.
548    match builder.build_global() {
549        Ok(()) | Err(ThreadPoolBuildError::AlreadyInitialized) => {}
550        Err(e) => panic!("failed to build global thread pool: {e}"),
551    }
552
553    MpzSession::builder()
554        .pool(ThreadPool::global())
555        .build(mux)
556        .expect("session should build")
557}
558
559#[cfg(test)]
560mod tests {
561    use super::*;
562
563    #[test]
564    fn default_config_is_valid() {
565        assert!(SessionConfig::builder().build().is_ok());
566    }
567
568    #[test]
569    fn oversized_max_num_streams_is_rejected() {
570        let err = SessionConfig::builder()
571            .max_num_streams(usize::MAX)
572            .build()
573            .unwrap_err();
574        assert!(matches!(
575            err.0,
576            tlsn_mux::ConfigError::ReceiveWindowTooSmall { .. }
577        ));
578    }
579
580    #[test]
581    fn unsplit_session_drop_closes_closure() {
582        let session = Session::new(futures::io::Cursor::new(Vec::<u8>::new()));
583        let closure = session.closure.share();
584        assert!(!closure.is_closed());
585
586        drop(session);
587
588        assert!(closure.is_closed());
589    }
590
591    #[test]
592    fn handle_drop_does_not_close_session() {
593        let session = Session::new(futures::io::Cursor::new(Vec::<u8>::new()));
594        let closure = session.closure.share();
595
596        let (driver, handle) = session.split();
597        drop(handle);
598        assert!(
599            !closure.is_closed(),
600            "dropping the handle must not end the session"
601        );
602
603        drop(driver);
604        assert!(closure.is_closed());
605    }
606}