gift_wrap.rs (9437B)
1 //! Wrap an already obtained seal without invoking a participant signer. 2 //! The caller must retain the result before transport; construction proves no 3 //! admission, recipient authorization, route approval or durable capture. 4 5 use alloc::vec; 6 use base64::Engine; 7 use core::{fmt, num::NonZeroU64}; 8 use nostr::{ 9 JsonUtil, 10 hashes::{Hash, sha256}, 11 }; 12 use radroots_event::{ 13 SignedEvent, 14 wire::{EventWireLimits, Nip01EventWire}, 15 }; 16 use radroots_identity::PublicKey; 17 use radroots_protocol::chat::{GiftWrapBudget, SIGNED_MAX_BYTES}; 18 use radroots_signing::provider::NonceSource; 19 use zeroize::Zeroizing; 20 21 const MAX_TIME: u64 = 253_402_300_799; 22 const PAST_SECONDS: u64 = 172_800; 23 const ENTROPY_DRAWS: usize = 16; 24 25 /// Fixed failures without input, ciphertext, key or dependency diagnostics. 26 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 27 pub enum WrapError { 28 /// The original representation is not an authentic supported kind-13 seal. 29 InvalidSeal, 30 /// The exact nested representation exceeds the supported event budget. 31 LimitExceeded, 32 /// The supplied current time is outside the supported positive range. 33 InvalidTime, 34 /// The injected entropy source failed or exhausted bounded rejection draws. 35 EntropyUnavailable, 36 /// Cryptography or exact output validation failed. 37 CryptoFailure, 38 } 39 impl fmt::Display for WrapError { 40 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 41 f.write_str(match self { 42 Self::InvalidSeal => "invalid retained seal", 43 Self::LimitExceeded => "gift wrap byte limit exceeded", 44 Self::InvalidTime => "invalid wrapping time", 45 Self::EntropyUnavailable => "wrapping entropy unavailable", 46 Self::CryptoFailure => "gift wrapping failed", 47 }) 48 } 49 } 50 impl core::error::Error for WrapError {} 51 52 /// One obtained outer representation awaiting protected durable capture. 53 /// It is neither cloneable nor automatically serializable. Temporary wrapping 54 /// material belongs to this attempt, never to a participant identity. 55 pub struct PendingGiftWrap { 56 event: SignedEvent, 57 recipient: PublicKey, 58 seal_digest: [u8; 32], 59 seal_event_id: [u8; 32], 60 wrapping_key: Zeroizing<[u8; 32]>, 61 } 62 impl fmt::Debug for PendingGiftWrap { 63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 64 f.write_str("PendingGiftWrap(<redacted>)") 65 } 66 } 67 impl PendingGiftWrap { 68 /// Exact complete signed bytes; retry these bytes after durable capture. 69 pub fn signed_json(&self) -> &str { 70 self.event.raw_json() 71 } 72 /// Actual outer event ID, distinct from seal and logical message IDs. 73 pub fn event_id(&self) -> [u8; 32] { 74 *self.event.envelope().id().as_bytes() 75 } 76 /// Selected recipient. This is not proof of the original operation binding. 77 pub const fn recipient(&self) -> PublicKey { 78 self.recipient 79 } 80 /// SHA-256 of the exact original seal representation, including whitespace. 81 pub const fn seal_digest(&self) -> [u8; 32] { 82 self.seal_digest 83 } 84 /// Original independently verified seal event ID. 85 pub const fn seal_event_id(&self) -> [u8; 32] { 86 self.seal_event_id 87 } 88 /// Borrows this attempt's temporary key for independent capture verification. 89 /// The callback must not log, publish or retain this key as participant custody. 90 pub fn with_wrapping_key<T>(&self, verify: impl FnOnce(&[u8; 32]) -> T) -> T { 91 verify(&self.wrapping_key) 92 } 93 } 94 95 fn entropy(source: &dyn NonceSource) -> Result<Zeroizing<[u8; 32]>, WrapError> { 96 source 97 .next_nonce() 98 .map(Zeroizing::new) 99 .map_err(|_| WrapError::EntropyUnavailable) 100 } 101 102 fn past_time(now: u64, source: &dyn NonceSource) -> Result<u64, WrapError> { 103 let range = now.min(PAST_SECONDS + 1); 104 let threshold = range.wrapping_neg() % range; 105 for _ in 0..ENTROPY_DRAWS { 106 let bytes = entropy(source)?; 107 let mut selected = [0; 8]; 108 selected.copy_from_slice(&bytes[..8]); 109 let draw = u64::from_be_bytes(selected); 110 if draw >= threshold { 111 return Ok(now - draw % range); 112 } 113 } 114 Err(WrapError::EntropyUnavailable) 115 } 116 117 /// Draws a positive timestamp within the NIP-59 two-day past interval using 118 /// bounded unbiased sampling. The injected source must be a qualified CSPRNG. 119 pub fn randomized_past_time( 120 now: NonZeroU64, 121 source: &dyn NonceSource, 122 ) -> Result<NonZeroU64, WrapError> { 123 if now.get() > MAX_TIME { 124 return Err(WrapError::InvalidTime); 125 } 126 NonZeroU64::new(past_time(now.get(), source)?).ok_or(WrapError::InvalidTime) 127 } 128 129 fn wrapping_keys( 130 source: &dyn NonceSource, 131 author: PublicKey, 132 recipient: PublicKey, 133 ) -> Result<(Zeroizing<[u8; 32]>, nostr::Keys), WrapError> { 134 for _ in 0..ENTROPY_DRAWS { 135 let bytes = entropy(source)?; 136 let Ok(secret) = nostr::SecretKey::from_slice(bytes.as_ref()) else { 137 continue; 138 }; 139 let keys = nostr::Keys::new(secret); 140 let public = keys.public_key().to_bytes(); 141 if public != *author.as_bytes() && public != *recipient.as_bytes() { 142 return Ok((bytes, keys)); 143 } 144 } 145 Err(WrapError::EntropyUnavailable) 146 } 147 148 fn exact_event(raw: &str) -> Result<SignedEvent, WrapError> { 149 let limits = EventWireLimits { 150 max_raw_json_bytes: SIGNED_MAX_BYTES, 151 ..Default::default() 152 }; 153 let wire = Nip01EventWire::parse_json_exact_with_limits(raw, limits) 154 .map_err(|_| WrapError::InvalidSeal)?; 155 let event = 156 SignedEvent::from_wire_verified_id(wire, raw).map_err(|_| WrapError::InvalidSeal)?; 157 if crate::event_verify::verify_event(event.envelope()) 158 != crate::event_verify::Verification::Verified 159 { 160 return Err(WrapError::InvalidSeal); 161 } 162 Ok(event) 163 } 164 165 /// Authenticates the bounded original seal and encrypts its exact bytes into a 166 /// signed kind-1059 envelope with one `p` tag. No participant signer, ambient 167 /// clock, transport, database or background task is accessed. Envelope key, 168 /// timestamp, nonce and signing auxiliary randomness use the injected source; 169 /// upstream secp256k1 context blinding retains its own initialization contract. 170 /// The source must provide qualified CSPRNG output; deterministic sources are test-only. 171 pub fn wrap_retained_seal( 172 raw_seal: &str, 173 recipient: PublicKey, 174 now: NonZeroU64, 175 source: &dyn NonceSource, 176 ) -> Result<PendingGiftWrap, WrapError> { 177 if now.get() > MAX_TIME { 178 return Err(WrapError::InvalidTime); 179 } 180 if raw_seal.len() > SIGNED_MAX_BYTES { 181 return Err(WrapError::LimitExceeded); 182 } 183 let budget = GiftWrapBudget::for_seal(raw_seal.len(), recipient).map_err(|e| match e { 184 radroots_protocol::nip01::WireError::LimitExceeded => WrapError::LimitExceeded, 185 radroots_protocol::nip01::WireError::InvalidInput => WrapError::InvalidSeal, 186 })?; 187 let seal = exact_event(raw_seal)?; 188 let fields = seal.envelope(); 189 if fields.kind_u32() != 13 190 || !fields.tags_as_vec().is_empty() 191 || fields.created_at_u64() == 0 192 || fields.created_at_u64() > now.get() 193 || fields.created_at_u64() > MAX_TIME 194 { 195 return Err(WrapError::InvalidSeal); 196 } 197 let sealed_payload = base64::engine::general_purpose::STANDARD 198 .decode(fields.content()) 199 .map_err(|_| WrapError::InvalidSeal)?; 200 if sealed_payload.len() < 99 201 || sealed_payload.first() != Some(&2) 202 || (sealed_payload.len() - 67) % 32 != 0 203 { 204 return Err(WrapError::InvalidSeal); 205 } 206 let created_at = past_time(now.get(), source)?; 207 let (wrapping_key, keys) = wrapping_keys(source, *fields.author(), recipient)?; 208 let peer = crate::key::public_key_to_nostr(recipient).map_err(|_| WrapError::InvalidSeal)?; 209 let nonce = entropy(source)?; 210 let payload = super::private::encrypt_payload(keys.secret_key(), &peer, raw_seal, *nonce) 211 .map_err(|_| WrapError::CryptoFailure)?; 212 let content = base64::engine::general_purpose::STANDARD.encode(payload); 213 if content.len() != budget.ciphertext_bytes() { 214 return Err(WrapError::CryptoFailure); 215 } 216 let tags = nostr::Tags::from_list(vec![nostr::Tag::public_key(peer)]); 217 let mut unsigned = nostr::UnsignedEvent { 218 id: None, 219 pubkey: keys.public_key(), 220 created_at: nostr::Timestamp::from_secs(created_at), 221 kind: nostr::Kind::GiftWrap, 222 tags, 223 content, 224 }; 225 let aux = entropy(source)?; 226 let message = nostr::secp256k1::Message::from_digest(unsigned.id().to_bytes()); 227 let mut signing_key = 228 nostr::secp256k1::Keypair::from_secret_key(nostr::SECP256K1, keys.secret_key()); 229 let signature = nostr::SECP256K1.sign_schnorr_with_aux_rand(&message, &signing_key, &aux); 230 signing_key.non_secure_erase(); 231 let outer = unsigned 232 .add_signature(signature) 233 .map_err(|_| WrapError::CryptoFailure)?; 234 let raw = Zeroizing::new(outer.as_json()); 235 if raw.len() > budget.signed_max_bytes() { 236 return Err(WrapError::CryptoFailure); 237 } 238 let event = exact_event(&raw).map_err(|_| WrapError::CryptoFailure)?; 239 Ok(PendingGiftWrap { 240 event, 241 recipient, 242 seal_digest: sha256::Hash::hash(raw_seal.as_bytes()).to_byte_array(), 243 seal_event_id: *fields.id().as_bytes(), 244 wrapping_key, 245 }) 246 } 247 248 #[cfg(test)] 249 mod tests;