1use std::collections::BTreeSet;
8
9use nostr::prelude::*;
10
11use crate::params::MAX_LIST_COORDS;
12use crate::params::{DISCOVERY_TAG, REGISTRATION_KIND};
13pub use crate::params::{LIST_KIND, ORGS_SET_D, VERIFIED_SET_D};
14use crate::registration::valid_slug;
15
16pub fn coord(operator_hex: &str, slug: &str) -> String {
17 format!("{REGISTRATION_KIND}:{operator_hex}:{slug}")
18}
19
20pub fn parse_coord(raw: &str) -> Option<(String, String)> {
22 let mut parts = raw.splitn(3, ':');
23 let (kind, key, slug) = (parts.next()?, parts.next()?, parts.next()?);
24 let hex_ok = key.len() == 64 && key.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'));
25 if kind != REGISTRATION_KIND.to_string() || !hex_ok || !valid_slug(slug) {
26 return None;
27 }
28 Some((key.to_string(), slug.to_string()))
29}
30
31fn build_list(
32 keys: &Keys,
33 d: &str,
34 title: &str,
35 coords: &[String],
36 created_at: Timestamp,
37) -> Result<Event, String> {
38 let tag = |parts: &[&str]| Tag::parse(parts).map_err(|e| format!("could not build tag: {e}"));
39 let sorted: BTreeSet<&String> = coords
40 .iter()
41 .filter(|c| parse_coord(c).is_some())
42 .take(MAX_LIST_COORDS)
43 .collect();
44 let mut tags = vec![Tag::identifier(d), tag(&["title", title])?];
45 for c in sorted {
46 tags.push(tag(&["a", c])?);
47 }
48 tags.push(tag(&["t", DISCOVERY_TAG])?);
49 EventBuilder::new(Kind::from(LIST_KIND as u16), "", tags)
50 .custom_created_at(created_at)
51 .to_event(keys)
52 .map_err(|e| format!("could not sign the list: {e}"))
53}
54
55pub fn build_org_set(keys: &Keys, coords: &[String]) -> Result<Event, String> {
57 build_org_set_at(keys, coords, Timestamp::now())
58}
59
60pub fn build_org_set_at(
63 keys: &Keys,
64 coords: &[String],
65 created_at: Timestamp,
66) -> Result<Event, String> {
67 build_list(
68 keys,
69 ORGS_SET_D,
70 "MoreInLaw organizations",
71 coords,
72 created_at,
73 )
74}
75
76pub fn build_verified_list(
78 keys: &Keys,
79 coords: &[String],
80 host_name: &str,
81) -> Result<Event, String> {
82 build_list(
83 keys,
84 VERIFIED_SET_D,
85 &format!("Organizations verified by {host_name}"),
86 coords,
87 Timestamp::now(),
88 )
89}
90
91pub fn parse_list(
93 event: &Event,
94 expected_d: &str,
95 expected_pubkey: &PublicKey,
96) -> Result<Vec<String>, String> {
97 if event.kind.as_u64() != LIST_KIND {
98 return Err("not a list event".to_string());
99 }
100 event
101 .verify()
102 .map_err(|_| "the list's signature does not verify".to_string())?;
103 if &event.pubkey != expected_pubkey {
104 return Err("the list was signed by a different key".to_string());
105 }
106 let mut d = None;
107 let mut coords = BTreeSet::new();
108 for tag in event.tags() {
109 let parts = tag.as_vec();
110 match (
111 parts.first().map(String::as_str),
112 parts.get(1).map(String::as_str),
113 ) {
114 (Some("d"), Some(v)) if d.is_none() => d = Some(v.to_string()),
115 (Some("a"), Some(v)) if parse_coord(v).is_some() => {
116 coords.insert(v.to_string());
117 }
118 _ => {}
119 }
120 }
121 if d.as_deref() != Some(expected_d) {
122 return Err("the list has an unexpected 'd' tag".to_string());
123 }
124 Ok(coords.into_iter().take(MAX_LIST_COORDS).collect())
125}
126
127#[cfg(test)]
128mod tests {
129 use super::*;
130
131 fn hex(c: char) -> String {
132 c.to_string().repeat(64)
133 }
134
135 fn coords() -> Vec<String> {
136 vec![
137 coord(&hex('b'), "beta-law"),
138 coord(&hex('a'), "alpha-law"),
139 coord(&hex('a'), "alpha-law"),
140 "garbage".to_string(),
141 format!("30779:{}:Bad_Slug", hex('c')),
142 ]
143 }
144
145 fn d_of(ev: &Event) -> Option<String> {
146 ev.tags().iter().find_map(|t| {
147 let v = t.as_vec();
148 (v[0] == "d").then(|| v[1].clone())
149 })
150 }
151
152 #[test]
153 fn org_set_is_sorted_deduped_tagged_and_roundtrips() {
154 let keys = Keys::generate();
155 let ev = build_org_set(&keys, &coords()).unwrap();
156 assert_eq!(ev.kind.as_u64(), 30003);
157 assert_eq!(d_of(&ev).as_deref(), Some(ORGS_SET_D));
158 let a_tags: Vec<String> = ev
159 .tags()
160 .iter()
161 .filter(|t| t.as_vec()[0] == "a")
162 .map(|t| t.as_vec()[1].clone())
163 .collect();
164 assert_eq!(
165 a_tags,
166 vec![coord(&hex('a'), "alpha-law"), coord(&hex('b'), "beta-law")]
167 );
168 assert!(ev
169 .tags()
170 .iter()
171 .any(|t| t.as_vec() == vec!["t".to_string(), "moreinlaw".to_string()]));
172 assert!(ev.tags().iter().any(
173 |t| t.as_vec() == vec!["title".to_string(), "MoreInLaw organizations".to_string()]
174 ));
175 assert_eq!(
176 parse_list(&ev, ORGS_SET_D, &keys.public_key()).unwrap(),
177 a_tags
178 );
179 }
180
181 #[test]
182 fn verified_list_uses_its_own_d_and_title() {
183 let keys = Keys::generate();
184 let ev = build_verified_list(&keys, &coords(), "main-dev Law").unwrap();
185 assert_eq!(d_of(&ev).as_deref(), Some(VERIFIED_SET_D));
186 assert!(ev.tags().iter().any(|t| t.as_vec()
187 == vec![
188 "title".to_string(),
189 "Organizations verified by main-dev Law".to_string()
190 ]));
191 assert!(parse_list(&ev, ORGS_SET_D, &keys.public_key()).is_err());
192 }
193
194 #[test]
195 fn parse_list_rejects_wrong_author_kind_and_tampering() {
196 let keys = Keys::generate();
197 let ev = build_org_set(&keys, &coords()).unwrap();
198 assert!(parse_list(&ev, ORGS_SET_D, &Keys::generate().public_key()).is_err());
199
200 let other_kind =
201 EventBuilder::new(Kind::Custom(30004), "", vec![Tag::identifier(ORGS_SET_D)])
202 .to_event(&keys)
203 .unwrap();
204 assert!(parse_list(&other_kind, ORGS_SET_D, &keys.public_key()).is_err());
205
206 let json = ev.as_json().replace("alpha-law", "alpha-lax");
207 if let Ok(t) = Event::from_json(&json) {
208 assert!(parse_list(&t, ORGS_SET_D, &keys.public_key()).is_err());
209 }
210 }
211
212 #[test]
213 fn parse_list_caps_the_number_of_coordinates() {
214 let keys = Keys::generate();
215 let tags: Vec<Tag> = std::iter::once(Tag::identifier(ORGS_SET_D))
216 .chain((0..2100).map(|n| {
217 Tag::parse(&["a".to_string(), coord(&hex('a'), &format!("org-{n:04}"))]).unwrap()
218 }))
219 .collect();
220 let ev = EventBuilder::new(Kind::from(LIST_KIND as u16), "", tags)
221 .to_event(&keys)
222 .unwrap();
223 assert_eq!(
224 parse_list(&ev, ORGS_SET_D, &keys.public_key())
225 .unwrap()
226 .len(),
227 MAX_LIST_COORDS
228 );
229 }
230
231 #[test]
232 fn coords_parse_only_in_the_exact_shape() {
233 assert_eq!(
234 parse_coord(&coord(&hex('a'), "alpha-law")),
235 Some((hex('a'), "alpha-law".to_string()))
236 );
237 for bad in [
238 "30778:".to_string() + &hex('a') + ":alpha-law",
239 coord(&hex('A'), "alpha-law"),
240 coord("abc", "alpha-law"),
241 coord(&hex('a'), "x"),
242 coord(&hex('a'), "has space"),
243 ] {
244 assert!(parse_coord(&bad).is_none(), "{bad}");
245 }
246 }
247}