nip59.rs (7824B)
1 //! Shared bounded NIP44/NIP59 authoring data. No signature, encryption MAC, 2 //! participant authority or completed store transaction is proved here. 3 use crate::nip01::{EventFields, WireError}; 4 use alloc::{string::String, vec}; 5 use core::fmt; 6 use radroots_domain::{PublicKey, UnixSeconds}; 7 use sha2::{Digest, Sha256}; 8 use zeroize::Zeroizing; 9 pub(crate) const MAX_TIME: u64 = 253_402_300_799; 10 const RANDOMIZED_PAST_SECONDS: u64 = 172_800; 11 /// Complete unsigned-rumor bound shared by supported private profiles. 12 pub const RUMOR_MAX_BYTES: usize = crate::profile::UNSIGNED_RUMOR_MAX_BYTES; 13 /// Complete signed seal/gift-wrap bound, including final JSON. 14 pub const SIGNED_MAX_BYTES: usize = crate::profile::SIGNED_EVENT_MAX_BYTES; 15 fn payload_shape(plaintext_bytes: usize) -> Result<(usize, usize), WireError> { 16 // The qualified small-payload profile uses the two-byte length prefix. 17 // This does not claim support for the newer extended NIP-44 prefix. 18 if !(1..=65_535).contains(&plaintext_bytes) { 19 return Err(WireError::InvalidInput); 20 } 21 let padded = if plaintext_bytes <= 32 { 22 32 23 } else { 24 let power = plaintext_bytes.next_power_of_two(); 25 let chunk = if power <= 256 { 32 } else { power / 8 }; 26 plaintext_bytes.div_ceil(chunk) * chunk 27 }; 28 let raw = padded + 67; 29 Ok((raw.div_ceil(3) * 4, (3 - raw % 3) % 3)) 30 } 31 /// Exact encoded size of the qualified two-byte-prefix NIP-44 v2 payload. 32 /// This is a size calculation, without encryption or a MAC-validity claim. 33 pub fn nip44_v2_payload_len(plaintext_bytes: usize) -> Result<usize, WireError> { 34 Ok(payload_shape(plaintext_bytes)?.0) 35 } 36 37 /// Conservative complete nested sizes using the largest supported timestamp. 38 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 39 pub struct PrivateEnvelopeBudget { 40 rumor_ciphertext_bytes: usize, 41 signed_seal_max_bytes: usize, 42 envelope_ciphertext_max_bytes: usize, 43 signed_envelope_max_bytes: usize, 44 } 45 impl PrivateEnvelopeBudget { 46 /// Measures both nesting layers before any business seal signing. 47 pub fn for_rumor(rumor_bytes: usize, participant: PublicKey) -> Result<Self, WireError> { 48 if rumor_bytes > RUMOR_MAX_BYTES { 49 return Err(WireError::LimitExceeded); 50 } 51 let rumor_ciphertext_bytes = nip44_v2_payload_len(rumor_bytes)?; 52 let fields = EventFields { 53 author: participant, 54 created_at: MAX_TIME, 55 kind: 13, 56 tags: &[], 57 content: "", 58 }; 59 let signed_seal_max_bytes = 60 crate::nip01::signed_json_len(&fields, SIGNED_MAX_BYTES)? + rumor_ciphertext_bytes; 61 let envelope_ciphertext_max_bytes = nip44_v2_payload_len(signed_seal_max_bytes)?; 62 let tags = [vec![String::from("p"), participant.to_hex()]]; 63 let fields = EventFields { 64 author: participant, 65 created_at: MAX_TIME, 66 kind: 1059, 67 tags: &tags, 68 content: "", 69 }; 70 let signed_envelope_max_bytes = crate::nip01::signed_json_len(&fields, SIGNED_MAX_BYTES)? 71 + envelope_ciphertext_max_bytes; 72 if signed_seal_max_bytes > SIGNED_MAX_BYTES || signed_envelope_max_bytes > SIGNED_MAX_BYTES 73 { 74 return Err(WireError::LimitExceeded); 75 } 76 Ok(Self { 77 rumor_ciphertext_bytes, 78 signed_seal_max_bytes, 79 envelope_ciphertext_max_bytes, 80 signed_envelope_max_bytes, 81 }) 82 } 83 /// Exact encoded rumor ciphertext size. 84 pub const fn rumor_ciphertext_bytes(self) -> usize { 85 self.rumor_ciphertext_bytes 86 } 87 /// Maximum complete seal JSON size. 88 pub const fn signed_seal_max_bytes(self) -> usize { 89 self.signed_seal_max_bytes 90 } 91 /// Maximum outer encoded ciphertext size. 92 pub const fn envelope_ciphertext_max_bytes(self) -> usize { 93 self.envelope_ciphertext_max_bytes 94 } 95 /// Maximum complete signed gift-wrap size. 96 pub const fn signed_envelope_max_bytes(self) -> usize { 97 self.signed_envelope_max_bytes 98 } 99 } 100 101 fn sextet(byte: u8) -> Option<u8> { 102 match byte { 103 b'A'..=b'Z' => Some(byte - b'A'), 104 b'a'..=b'z' => Some(byte - b'a' + 26), 105 b'0'..=b'9' => Some(byte - b'0' + 52), 106 b'+' => Some(62), 107 b'/' => Some(63), 108 _ => None, 109 } 110 } 111 fn ciphertext_shape(value: &str, plaintext_bytes: usize) -> Result<(), WireError> { 112 let (size, padding) = payload_shape(plaintext_bytes)?; 113 if value.len() != size { 114 return Err(WireError::InvalidInput); 115 } 116 let bytes = value.as_bytes(); 117 let split = size - padding; 118 if !bytes[..split].iter().all(|b| sextet(*b).is_some()) 119 || !bytes[split..].iter().all(|b| *b == b'=') 120 || bytes[0] != b'A' 121 || !(b'g'..=b'v').contains(&bytes[1]) 122 { 123 return Err(WireError::InvalidInput); 124 } 125 let last = sextet(bytes[split - 1]).ok_or(WireError::InvalidInput)?; 126 if (padding == 1 && last & 3 != 0) || (padding == 2 && last & 15 != 0) { 127 return Err(WireError::InvalidInput); 128 } 129 Ok(()) 130 } 131 132 /// Exact bounded kind13 preimage for one declared private recipient. This is 133 /// structural data: the caller separately proves plaintext/encryption binding, 134 /// recipient membership, current permission and actual durable T1 retention. 135 pub struct PrivateSeal { 136 author: PublicKey, 137 recipient: PublicKey, 138 created_at: UnixSeconds, 139 ciphertext: Zeroizing<String>, 140 event_id: [u8; 32], 141 } 142 impl PrivateSeal { 143 /// Validates the initial-authoring timestamp and both complete nesting 144 /// budgets before copying. A supplied ciphertext remains a claim until 145 /// qualified encryption verifies its exact original plaintext/recipient. 146 pub fn new( 147 author: PublicKey, 148 recipient: PublicKey, 149 created_at: UnixSeconds, 150 rumor_created_at: UnixSeconds, 151 rumor_bytes: usize, 152 ciphertext: &str, 153 ) -> Result<Self, WireError> { 154 if created_at.get() == 0 155 || rumor_created_at.get() == 0 156 || created_at > rumor_created_at 157 || rumor_created_at.get() - created_at.get() > RANDOMIZED_PAST_SECONDS 158 { 159 return Err(WireError::InvalidInput); 160 } 161 PrivateEnvelopeBudget::for_rumor(rumor_bytes, author)?; 162 ciphertext_shape(ciphertext, rumor_bytes)?; 163 let fields = EventFields { 164 author, 165 created_at: created_at.get(), 166 kind: 13, 167 tags: &[], 168 content: ciphertext, 169 }; 170 crate::nip01::signed_json_len(&fields, SIGNED_MAX_BYTES)?; 171 let preimage = crate::nip01::bounded_preimage(&fields, SIGNED_MAX_BYTES)?; 172 let event_id = Sha256::digest(preimage.as_bytes()).into(); 173 Ok(Self { 174 author, 175 recipient, 176 created_at, 177 ciphertext: Zeroizing::new(String::from(ciphertext)), 178 event_id, 179 }) 180 } 181 /// Borrows the exact immutable preimage fields, with an empty tag set. 182 pub fn fields(&self) -> EventFields<'_> { 183 EventFields { 184 author: self.author, 185 created_at: self.created_at.get(), 186 kind: 13, 187 tags: &[], 188 content: &self.ciphertext, 189 } 190 } 191 /// Exact declared private recipient, distinct from public seal tags. 192 pub const fn recipient(&self) -> PublicKey { 193 self.recipient 194 } 195 /// NIP01 identity of these exact fields, without a signature claim. 196 pub const fn event_id(&self) -> [u8; 32] { 197 self.event_id 198 } 199 } 200 impl fmt::Debug for PrivateSeal { 201 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 202 f.write_str("PrivateSeal(<redacted>)") 203 } 204 } 205 206 mod routes; 207 pub use routes::{CapturedDmRoute, DmRelayAdvertisement};