1use std::cell::RefCell;
9
10use nostr_sdk::prelude::{Event, EventId, Kind, PublicKey, Signature, Tag, Timestamp, UnsignedEvent};
11
12thread_local! {
13 static PARSER: RefCell<nostr_parse::Parser> = RefCell::new(nostr_parse::Parser::new());
15}
16
17pub fn event(json: &str) -> Result<Event, nostr::error::Error> {
19 fast_event(json).map_or_else(|| Event::from_json(json), Ok)
20}
21
22pub fn unsigned(json: &str) -> Result<UnsignedEvent, nostr::error::Error> {
24 fast_unsigned(json).map_or_else(|| UnsignedEvent::from_json(json), Ok)
25}
26
27fn fast_event(json: &str) -> Option<Event> {
28 let e = PARSER.with(|p| p.borrow_mut().parse(json)).ok()?;
29 let sig = Signature::from_byte_array(e.sig?);
30 Some(Event::new(
31 EventId::from_byte_array(e.id),
32 PublicKey::from_byte_array(e.pubkey),
33 Timestamp::from_secs(e.created_at),
34 Kind::from_u16(e.kind),
35 tags(e.tags)?,
36 e.content,
37 sig,
38 ))
39}
40
41fn fast_unsigned(json: &str) -> Option<UnsignedEvent> {
42 let e = PARSER.with(|p| p.borrow_mut().parse_unsigned(json)).ok()?;
43 let mut rumor = UnsignedEvent::new(
44 PublicKey::from_byte_array(e.pubkey),
45 Timestamp::from_secs(e.created_at),
46 Kind::from_u16(e.kind),
47 tags(e.tags)?,
48 e.content,
49 );
50 rumor.id = e.id.map(EventId::from_byte_array);
51 Some(rumor)
52}
53
54fn tags(raw: Vec<Vec<String>>) -> Option<Vec<Tag>> {
56 raw.into_iter().map(|t| Tag::parse(t).ok()).collect()
57}
58
59#[cfg(test)]
60mod tests {
61 use super::*;
62 use crate::event_ext::FinalizeUnsignedWithId;
63 use nostr_sdk::prelude::{nip44, EventBuilder, FinalizeEvent, FinalizeUnsignedEvent, GiftWrapBuilder, Keys, ToBech32};
64
65 const ID: &str = "70b10f70c1318967eddf12527799411b1a9780ad9c43858f5e5fcd45486a13a5";
66 const PUBKEY: &str = "379e863e8357163b5bce5d2688dc4f1dcc2d505222fb8d74db600f30535dfdfe";
67 const SIG: &str = "273a9cd5d11455590f4359500bccb7a89428262b96b3ea87a756b770964472f8c3e87f5d5e64d8d2e859a71462a3f477b554565c4f2f326cb01dd7620db71502";
68
69 fn contents() -> Vec<String> {
70 vec![
71 String::new(),
72 "hi".into(),
73 "quotes \" and \\ backslashes, a tab\t, a newline\n and \u{1F680} \u{00e9}".into(),
74 "\\u0041 stays literal; </script> too".into(),
75 "long ".repeat(400),
76 ]
77 }
78
79 fn rumors(me: &Keys, them: &Keys) -> Vec<UnsignedEvent> {
80 let mut out = Vec::new();
81 for (i, text) in contents().into_iter().enumerate() {
82 let mut tags = vec![Tag::parse(["p", &them.public_key().to_hex()]).unwrap()];
83 if i % 2 == 0 {
84 tags.push(Tag::parse(["e", ID, "", "reply"]).unwrap());
85 tags.push(Tag::parse(["emoji", "cat", "https://example.com/c.png?a=1&b=\"2\""]).unwrap());
86 }
87 let builder = EventBuilder::new(Kind::PrivateDirectMessage, text).tags(tags);
88 out.push(builder.clone().finalize_unsigned_with_id(me.public_key()));
89 out.push(builder.finalize_unsigned(me.public_key()));
90 }
91 out
92 }
93
94 fn seals_and_wraps(me: &Keys, them: &Keys) -> Vec<String> {
96 let mut out = Vec::new();
97 for rumor in rumors(me, them) {
98 let wrap = GiftWrapBuilder::new(them.public_key(), rumor).finalize(me).unwrap();
99 out.push(nip44::decrypt(them.secret_key(), &wrap.pubkey, &wrap.content).unwrap());
100 out.push(wrap.as_json());
101 }
102 out
103 }
104
105 fn same_event(json: &str) {
106 match (event(json), Event::from_json(json)) {
107 (Ok(ours), Ok(theirs)) => {
108 assert_eq!(ours, theirs, "{json}");
109 assert_eq!(ours.as_json(), theirs.as_json(), "{json}");
110 }
111 (Err(_), Err(_)) => {}
112 (ours, theirs) => panic!("ours {ours:?}, rust-nostr {theirs:?}: {json}"),
113 }
114 }
115
116 fn same_unsigned(json: &str) {
117 match (unsigned(json), UnsignedEvent::from_json(json)) {
118 (Ok(ours), Ok(theirs)) => assert_eq!(ours, theirs, "{json}"),
119 (Err(_), Err(_)) => {}
120 (ours, theirs) => panic!("ours {ours:?}, rust-nostr {theirs:?}: {json}"),
121 }
122 }
123
124 #[test]
125 fn rumors_as_rust_nostr_writes_them_take_the_fast_path() {
126 let (me, them) = (Keys::generate(), Keys::generate());
127 for rumor in rumors(&me, &them) {
128 let json = rumor.as_json();
129 assert!(!json.contains("\"sig\""), "{json}");
130 assert_eq!(fast_unsigned(&json).as_ref(), Some(&rumor), "{json}");
131 same_unsigned(&json);
132 }
133 }
134
135 #[test]
136 fn seals_and_wraps_take_the_fast_path() {
137 let (me, them) = (Keys::generate(), Keys::generate());
138 for json in seals_and_wraps(&me, &them) {
139 assert_eq!(fast_event(&json), Some(Event::from_json(&json).unwrap()), "{json}");
140 same_event(&json);
141 }
142 }
143
144 #[test]
145 fn what_nostr_parse_refuses_still_reads_as_rust_nostr_reads_it() {
146 let upper_id = format!(r#"{{"id":"{}","pubkey":"{PUBKEY}","created_at":1,"kind":14,"tags":[],"content":"x"}}"#, ID.to_uppercase());
147 let npub = PublicKey::from_hex(PUBKEY).unwrap().to_bech32().unwrap();
148 let bech32_key = format!(r#"{{"id":"{ID}","pubkey":"{npub}","created_at":1,"kind":14,"tags":[],"content":"x"}}"#);
149 for json in [&upper_id, &bech32_key] {
150 assert!(fast_unsigned(json).is_none(), "{json}");
151 assert_eq!(unsigned(json).unwrap(), UnsignedEvent::from_json(json).unwrap(), "{json}");
152 }
153
154 let upper_sig = format!(r#"{{"id":"{ID}","pubkey":"{PUBKEY}","created_at":1,"kind":1,"tags":[],"content":"x","sig":"{}"}}"#, SIG.to_uppercase());
155 assert!(fast_event(&upper_sig).is_none());
156 assert_eq!(event(&upper_sig).unwrap(), Event::from_json(&upper_sig).unwrap());
157 }
158
159 #[test]
160 fn rust_nostr_and_these_agree_on_every_spelling() {
161 let base = |id: &str, extra: &str, tags: &str, sig: &str| {
162 format!(r#"{{{id}"pubkey":"{PUBKEY}","created_at":1612809991,"kind":14,"tags":{tags},"content":"a \"b\" \\ c"{extra}{sig}}}"#)
163 };
164 let ids = [format!(r#""id":"{ID}","#), r#""id":null,"#.to_string(), String::new(), r#""id":"","#.to_string(), r#""id":7,"#.to_string()];
165 let sigs = [String::new(), format!(r#","sig":"{SIG}""#), r#","sig":"""#.into(), r#","sig":null"#.into(), r#","sig":[1,{"a":2}]"#.into(), r#","sig":"","sig":"""#.into()];
166 let extras = ["", r#","relays":["wss://x"]"#, r#","deep":[[[[{"a":[1,2,{"b":null}]}]]]]"#, r#","kind":1"#];
167 let escaped = format!("[[\"{}u0070\",\"{}ud83d{}ude80\"]]", '\\', '\\', '\\');
168 let tags = ["[]", r#"[["p","x"],["e","y","","reply"]]"#, "[[]]", r#"[["p",1]]"#, r#"[["p","🚀"]]"#, &escaped, "[\"p\"]"];
169 let (mut n, mut fast_rumors, mut fast_events) = (0, 0, 0);
170 for id in &ids {
171 for sig in &sigs {
172 for extra in extras {
173 for tag in tags {
174 let json = base(id, extra, tag, sig);
175 same_unsigned(&json);
176 same_event(&json);
177 same_unsigned(&format!(" \n{json}\t"));
178 fast_rumors += usize::from(fast_unsigned(&json).is_some());
179 fast_events += usize::from(fast_event(&json).is_some());
180 n += 1;
181 }
182 }
183 }
184 }
185 assert_eq!(n, ids.len() * sigs.len() * extras.len() * tags.len());
186 assert!(fast_rumors >= 100 && fast_events >= 10, "{fast_rumors} rumors, {fast_events} events");
188
189 for json in ["", "{}", "[]", "null", "{\"id\":", "\u{feff}{}", r#"{"id":"ab"}"#] {
190 same_unsigned(json);
191 same_event(json);
192 }
193 }
194}