Skip to main content

iroh_live_rooms/
ticket.rs

1//! The ticket that identifies a room and bootstraps its gossip topic.
2
3use std::str::FromStr;
4
5use iroh::EndpointId;
6use iroh_gossip::TopicId;
7use serde::{Deserialize, Serialize};
8
9/// A room: its gossip topic and the peers to contact first.
10///
11/// Its string form is an `iroh_tickets` ticket of kind `room2`. The kind
12/// names the version of the room's gossip messages, which carry no version of
13/// their own, so a ticket of an earlier format fails to parse instead of
14/// joining a room whose messages its peers cannot read.
15#[derive(Debug, Clone, PartialEq, Eq, derive_more::Display, Serialize, Deserialize)]
16#[display("{}", iroh_tickets::Ticket::encode_string(self))]
17pub struct RoomTicket {
18    bootstrap: Vec<EndpointId>,
19    topic_id: TopicId,
20}
21
22impl RoomTicket {
23    /// Creates a ticket for `topic_id`, bootstrapping from `bootstrap`.
24    #[must_use]
25    pub fn new(topic_id: TopicId, bootstrap: impl IntoIterator<Item = EndpointId>) -> Self {
26        Self {
27            bootstrap: bootstrap.into_iter().collect(),
28            topic_id,
29        }
30    }
31
32    /// Creates a ticket for a new room with a random topic.
33    #[must_use]
34    pub fn generate() -> Self {
35        Self::new(TopicId::from_bytes(rand::random()), [])
36    }
37
38    /// Returns the gossip topic that identifies the room.
39    #[must_use]
40    pub fn topic_id(&self) -> TopicId {
41        self.topic_id
42    }
43
44    /// Returns the peers a joiner contacts first.
45    #[must_use]
46    pub fn bootstrap(&self) -> &[EndpointId] {
47        &self.bootstrap
48    }
49
50    /// Returns this ticket with `peer` as its only bootstrap peer.
51    pub(crate) fn with_bootstrap(&self, peer: EndpointId) -> Self {
52        Self::new(self.topic_id, [peer])
53    }
54}
55
56impl FromStr for RoomTicket {
57    type Err = iroh_tickets::ParseError;
58
59    fn from_str(s: &str) -> Result<Self, Self::Err> {
60        iroh_tickets::Ticket::decode_string(s)
61    }
62}
63
64impl iroh_tickets::Ticket for RoomTicket {
65    /// Bumped from `room` when the gossip announcements changed format.
66    const KIND: &'static str = "room2";
67
68    fn encode_bytes(&self) -> Vec<u8> {
69        postcard::to_stdvec(self).expect("RoomTicket serialization is infallible")
70    }
71
72    fn decode_bytes(bytes: &[u8]) -> Result<Self, iroh_tickets::ParseError> {
73        Ok(postcard::from_bytes(bytes)?)
74    }
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80
81    #[test]
82    fn a_ticket_round_trips_through_its_string() {
83        let peer = iroh::SecretKey::from_bytes(&[5; 32]).public();
84        let ticket = RoomTicket::generate().with_bootstrap(peer);
85        let parsed: RoomTicket = ticket.to_string().parse().expect("parse");
86        assert_eq!(parsed, ticket);
87        assert!(ticket.to_string().starts_with("room2"));
88        assert_eq!(parsed.bootstrap(), [peer]);
89    }
90
91    /// A ticket of the earlier `room` kind fails with a kind error, not a room that cannot talk.
92    #[test]
93    fn a_ticket_of_the_earlier_format_is_refused_by_kind() {
94        let peer = iroh::SecretKey::from_bytes(&[5; 32]).public();
95        let ticket = RoomTicket::generate().with_bootstrap(peer);
96        // The same bytes under the earlier kind.
97        let encoded = ticket.to_string();
98        let stale = format!("room{}", encoded.strip_prefix("room2").expect("the kind"));
99        let err = stale.parse::<RoomTicket>().expect_err("a stale ticket");
100        assert!(
101            matches!(
102                err,
103                iroh_tickets::ParseError::Kind {
104                    expected: "room2",
105                    ..
106                }
107            ),
108            "{err}"
109        );
110    }
111}