iroh_live_rooms/
ticket.rs1use std::str::FromStr;
4
5use iroh::EndpointId;
6use iroh_gossip::TopicId;
7use serde::{Deserialize, Serialize};
8
9#[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 #[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 #[must_use]
34 pub fn generate() -> Self {
35 Self::new(TopicId::from_bytes(rand::random()), [])
36 }
37
38 #[must_use]
40 pub fn topic_id(&self) -> TopicId {
41 self.topic_id
42 }
43
44 #[must_use]
46 pub fn bootstrap(&self) -> &[EndpointId] {
47 &self.bootstrap
48 }
49
50 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 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 #[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 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}