nip01.rs (7656B)
1 //! Canonical NIP-01 bytes. These data codecs authenticate no event or command. 2 3 use alloc::{ 4 string::{String, ToString}, 5 vec::Vec, 6 }; 7 use core::fmt; 8 use radroots_identity::PublicKey; 9 use sha2::{Digest, Sha256}; 10 use zeroize::Zeroizing; 11 12 /// Fixed codec failures, without private input in diagnostics. 13 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 14 pub enum WireError { 15 /// Data does not fit the selected profile. 16 InvalidInput, 17 /// Complete serialized output exceeds its selected byte budget. 18 LimitExceeded, 19 } 20 impl fmt::Display for WireError { 21 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 22 f.write_str(match self { 23 Self::InvalidInput => "invalid event profile", 24 Self::LimitExceeded => "event byte limit exceeded", 25 }) 26 } 27 } 28 impl core::error::Error for WireError {} 29 30 /// Borrowed exact fields. No registry, clock, participant or grant is inferred. 31 pub struct EventFields<'a> { 32 /// Validated x-only author key. 33 pub author: PublicKey, 34 /// Exact NIP-01 integer timestamp; business profiles apply their own bounds. 35 pub created_at: u64, 36 /// Exact NIP-01 kind. 37 pub kind: u32, 38 /// Ordered tags and fields, without sorting or normalization. 39 pub tags: &'a [Vec<String>], 40 /// Exact UTF-8 content. 41 pub content: &'a str, 42 } 43 impl fmt::Debug for EventFields<'_> { 44 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 45 f.write_str("EventFields(<redacted>)") 46 } 47 } 48 49 fn add(total: &mut usize, amount: usize, limit: usize) -> Result<(), WireError> { 50 *total = total 51 .checked_add(amount) 52 .filter(|n| *n <= limit) 53 .ok_or(WireError::LimitExceeded)?; 54 Ok(()) 55 } 56 fn string_len(value: &str, total: &mut usize, limit: usize) -> Result<(), WireError> { 57 add(total, 2, limit)?; 58 for byte in value.bytes() { 59 add( 60 total, 61 match byte { 62 b'"' | b'\\' | b'\n' | b'\r' | b'\t' | 8 | 12 => 2, 63 0..=31 => 6, 64 _ => 1, 65 }, 66 limit, 67 )?; 68 } 69 Ok(()) 70 } 71 /// Counts complete canonical preimage bytes before allocating the output. 72 pub fn preimage_len(fields: &EventFields<'_>, limit: usize) -> Result<usize, WireError> { 73 let mut size = 3 + 66 + 1; 74 add( 75 &mut size, 76 fields.created_at.checked_ilog10().unwrap_or(0) as usize + 1, 77 limit, 78 )?; 79 add( 80 &mut size, 81 1 + fields.kind.checked_ilog10().unwrap_or(0) as usize + 1 + 2, 82 limit, 83 )?; 84 for (index, tag) in fields.tags.iter().enumerate() { 85 add(&mut size, 2 + usize::from(index != 0), limit)?; 86 for (index, value) in tag.iter().enumerate() { 87 add(&mut size, usize::from(index != 0), limit)?; 88 string_len(value, &mut size, limit)?; 89 } 90 } 91 add(&mut size, 2, limit)?; 92 string_len(fields.content, &mut size, limit)?; 93 add(&mut size, 1, limit)?; 94 Ok(size) 95 } 96 97 fn push_string(target: &mut String, value: &str) { 98 target.push('"'); 99 const HEX: &[u8; 16] = b"0123456789abcdef"; 100 for character in value.chars() { 101 match character { 102 '"' => target.push_str("\\\""), 103 '\\' => target.push_str("\\\\"), 104 '\n' => target.push_str("\\n"), 105 '\r' => target.push_str("\\r"), 106 '\t' => target.push_str("\\t"), 107 '\u{08}' => target.push_str("\\b"), 108 '\u{0c}' => target.push_str("\\f"), 109 '\u{00}'..='\u{1f}' => { 110 let value = character as usize; 111 target.push_str("\\u00"); 112 target.push(HEX[value >> 4] as char); 113 target.push(HEX[value & 15] as char); 114 } 115 _ => target.push(character), 116 } 117 } 118 target.push('"'); 119 } 120 fn push_tags(target: &mut String, tags: &[Vec<String>]) { 121 target.push('['); 122 for (index, tag) in tags.iter().enumerate() { 123 if index != 0 { 124 target.push(','); 125 } 126 target.push('['); 127 for (index, value) in tag.iter().enumerate() { 128 if index != 0 { 129 target.push(','); 130 } 131 push_string(target, value); 132 } 133 target.push(']'); 134 } 135 target.push(']'); 136 } 137 fn append_preimage(target: &mut String, fields: &EventFields<'_>) { 138 target.push_str("[0,"); 139 push_string(target, &fields.author.to_hex()); 140 target.push(','); 141 target.push_str(&fields.created_at.to_string()); 142 target.push(','); 143 target.push_str(&fields.kind.to_string()); 144 target.push(','); 145 push_tags(target, fields.tags); 146 target.push(','); 147 push_string(target, fields.content); 148 target.push(']'); 149 } 150 /// Retains the original wire-v1 serialization semantics, including unrestricted 151 /// NIP-01 integer timestamps. Callers must bound their input; new private 152 /// profiles use the explicitly bounded encoder instead. 153 pub fn canonical_preimage(fields: &EventFields<'_>) -> String { 154 let mut target = String::new(); 155 append_preimage(&mut target, fields); 156 target 157 } 158 /// Checks the complete preimage before allocating private serialized bytes. 159 pub(crate) fn bounded_preimage( 160 fields: &EventFields<'_>, 161 limit: usize, 162 ) -> Result<Zeroizing<String>, WireError> { 163 let size = preimage_len(fields, limit)?; 164 let mut target = Zeroizing::new(String::with_capacity(size)); 165 append_preimage(&mut target, fields); 166 Ok(target) 167 } 168 /// Counts complete signed JSON, including the exact ID and 64-byte signature. 169 pub fn signed_json_len(fields: &EventFields<'_>, limit: usize) -> Result<usize, WireError> { 170 let mut size = preimage_len(fields, limit)?; 171 add(&mut size, 253, limit)?; 172 Ok(size) 173 } 174 fn hex(bytes: &[u8; 32]) -> String { 175 const HEX: &[u8; 16] = b"0123456789abcdef"; 176 let mut output = String::with_capacity(64); 177 for byte in bytes { 178 output.push(HEX[(byte >> 4) as usize] as char); 179 output.push(HEX[(byte & 15) as usize] as char); 180 } 181 output 182 } 183 /// Owned exact unsigned JSON and its computed event ID; no signature or 184 /// authenticated participant claim is supplied by this value. 185 pub struct UnsignedEvent { 186 id: [u8; 32], 187 json: Zeroizing<String>, 188 } 189 impl UnsignedEvent { 190 /// Checks the complete rumor/object size before creating private output. 191 pub fn encode(fields: &EventFields<'_>, limit: usize) -> Result<Self, WireError> { 192 let preimage = bounded_preimage( 193 fields, 194 limit.checked_sub(116).ok_or(WireError::LimitExceeded)?, 195 )?; 196 let id = Sha256::digest(preimage.as_bytes()).into(); 197 let mut json = Zeroizing::new(String::with_capacity(preimage.len() + 116)); 198 json.push_str("{\"id\":"); 199 push_string(&mut json, &hex(&id)); 200 json.push_str(",\"pubkey\":"); 201 push_string(&mut json, &fields.author.to_hex()); 202 json.push_str(",\"created_at\":"); 203 json.push_str(&fields.created_at.to_string()); 204 json.push_str(",\"kind\":"); 205 json.push_str(&fields.kind.to_string()); 206 json.push_str(",\"tags\":"); 207 push_tags(&mut json, fields.tags); 208 json.push_str(",\"content\":"); 209 push_string(&mut json, fields.content); 210 json.push('}'); 211 Ok(Self { id, json }) 212 } 213 /// Returns the exact SHA-256 event ID. 214 pub const fn event_id(&self) -> [u8; 32] { 215 self.id 216 } 217 /// Borrows the exact unsigned JSON, without cloning private content. 218 pub fn json(&self) -> &str { 219 &self.json 220 } 221 } 222 impl fmt::Debug for UnsignedEvent { 223 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 224 f.write_str("UnsignedEvent(<redacted>)") 225 } 226 }