lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

draft.rs (18958B)


      1 #![forbid(unsafe_code)]
      2 
      3 #[cfg(all(not(feature = "std"), not(test)))]
      4 use alloc::{string::String, vec::Vec};
      5 
      6 #[cfg(any(feature = "std", test))]
      7 use std::{string::String, vec::Vec};
      8 
      9 use radroots_identity::PublicKey;
     10 
     11 use crate::contract::registry_v7::ContractValidationError;
     12 use crate::envelope::{EventEnvelope, EventEnvelopeError};
     13 use crate::id::{EventId, EventSignature, ParseError, parse_public_key};
     14 use crate::wire::v1::{
     15     CanonicalEventIdError, EventWireError, Nip01EventWire, canonical_nip01_event_id_preimage,
     16     compute_canonical_nip01_event_id,
     17 };
     18 use core::fmt;
     19 
     20 #[derive(Clone, Debug, PartialEq, Eq)]
     21 pub enum DraftError {
     22     UnknownContract(String),
     23     ContractKindMismatch {
     24         contract_id: String,
     25         expected_kind: u32,
     26         actual_kind: u32,
     27     },
     28     ContractNotDraftAuthorable {
     29         contract_id: String,
     30     },
     31     ContractRegistryVersionMismatch {
     32         expected: u32,
     33         actual: u32,
     34     },
     35     DraftExpectedEventIdMismatch {
     36         expected_event_id: String,
     37         actual_event_id: String,
     38     },
     39     ContractShape {
     40         contract_id: String,
     41         error: ContractValidationError,
     42     },
     43     IdParse(ParseError),
     44     CanonicalEventId(CanonicalEventIdError),
     45     Envelope(EventEnvelopeError),
     46     SignedEvent(SignedEventError),
     47 }
     48 
     49 impl fmt::Display for DraftError {
     50     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     51         match self {
     52             Self::UnknownContract(contract_id) => {
     53                 write!(f, "unknown event contract `{contract_id}`")
     54             }
     55             Self::ContractKindMismatch {
     56                 contract_id,
     57                 expected_kind,
     58                 actual_kind,
     59             } => write!(
     60                 f,
     61                 "event contract `{contract_id}` expects kind {expected_kind}, got {actual_kind}"
     62             ),
     63             Self::ContractNotDraftAuthorable { contract_id } => write!(
     64                 f,
     65                 "event contract `{contract_id}` is not authorable through generic frozen drafts"
     66             ),
     67             Self::ContractRegistryVersionMismatch { expected, actual } => write!(
     68                 f,
     69                 "event contract registry version mismatch: expected {expected}, got {actual}"
     70             ),
     71             Self::DraftExpectedEventIdMismatch {
     72                 expected_event_id,
     73                 actual_event_id,
     74             } => write!(
     75                 f,
     76                 "frozen draft event ID mismatch: expected {expected_event_id}, got {actual_event_id}"
     77             ),
     78             Self::ContractShape { contract_id, error } => write!(
     79                 f,
     80                 "event contract `{contract_id}` shape validation failed with code {}",
     81                 error.code()
     82             ),
     83             Self::IdParse(error) => write!(f, "{error}"),
     84             Self::CanonicalEventId(error) => write!(f, "{error}"),
     85             Self::Envelope(error) => write!(f, "{error}"),
     86             Self::SignedEvent(error) => write!(f, "{error}"),
     87         }
     88     }
     89 }
     90 
     91 #[cfg(feature = "std")]
     92 impl std::error::Error for DraftError {}
     93 
     94 impl From<ParseError> for DraftError {
     95     fn from(value: ParseError) -> Self {
     96         Self::IdParse(value)
     97     }
     98 }
     99 
    100 impl From<CanonicalEventIdError> for DraftError {
    101     fn from(value: CanonicalEventIdError) -> Self {
    102         match value {
    103             CanonicalEventIdError::InvalidPubkey(error) => Self::IdParse(error),
    104             error => Self::CanonicalEventId(error),
    105         }
    106     }
    107 }
    108 
    109 impl From<EventEnvelopeError> for DraftError {
    110     fn from(value: EventEnvelopeError) -> Self {
    111         Self::Envelope(value)
    112     }
    113 }
    114 
    115 impl From<SignedEventError> for DraftError {
    116     fn from(value: SignedEventError) -> Self {
    117         Self::SignedEvent(value)
    118     }
    119 }
    120 
    121 #[cfg_attr(
    122     any(feature = "serde", test),
    123     derive(serde::Serialize, serde::Deserialize)
    124 )]
    125 #[derive(Clone, Debug, PartialEq, Eq)]
    126 pub struct SignedEventParts {
    127     pub id: String,
    128     pub pubkey: String,
    129     pub created_at: u64,
    130     pub kind: u32,
    131     pub tags: Vec<Vec<String>>,
    132     pub content: String,
    133     pub sig: String,
    134     pub raw_json: String,
    135 }
    136 
    137 #[derive(Clone, Debug, PartialEq, Eq)]
    138 pub struct SignedEvent {
    139     envelope: EventEnvelope,
    140     wire: Nip01EventWire,
    141     raw_json: String,
    142 }
    143 
    144 #[cfg(any(feature = "serde", test))]
    145 impl serde::Serialize for SignedEvent {
    146     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    147     where
    148         S: serde::Serializer,
    149     {
    150         use serde::ser::SerializeStruct;
    151 
    152         let mut state = serializer.serialize_struct("SignedEvent", 2)?;
    153         state.serialize_field("wire", &self.wire)?;
    154         state.serialize_field("raw_json", &self.raw_json)?;
    155         state.end()
    156     }
    157 }
    158 
    159 #[cfg(any(feature = "serde", test))]
    160 impl<'de> serde::Deserialize<'de> for SignedEvent {
    161     fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    162     where
    163         D: serde::Deserializer<'de>,
    164     {
    165         #[derive(serde::Deserialize)]
    166         struct SignedEventSerde {
    167             wire: Nip01EventWire,
    168             raw_json: String,
    169         }
    170 
    171         let value = SignedEventSerde::deserialize(deserializer)?;
    172         SignedEvent::from_wire_verified_id(value.wire, value.raw_json)
    173             .map_err(serde::de::Error::custom)
    174     }
    175 }
    176 
    177 #[derive(Clone, Debug, PartialEq, Eq)]
    178 pub enum SignedEventError {
    179     Wire(EventWireError),
    180     RawJson(EventWireError),
    181     RawJsonMismatch,
    182     Envelope(EventEnvelopeError),
    183 }
    184 
    185 impl fmt::Display for SignedEventError {
    186     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    187         match self {
    188             Self::Wire(error) => write!(f, "signed event wire is invalid: {error}"),
    189             Self::RawJson(error) => write!(f, "signed event raw JSON is invalid: {error}"),
    190             Self::RawJsonMismatch => {
    191                 write!(
    192                     f,
    193                     "signed event raw JSON does not match the provided wire event"
    194                 )
    195             }
    196             Self::Envelope(error) => write!(f, "signed event envelope is invalid: {error}"),
    197         }
    198     }
    199 }
    200 
    201 #[cfg(feature = "std")]
    202 impl std::error::Error for SignedEventError {}
    203 
    204 impl From<EventEnvelopeError> for SignedEventError {
    205     fn from(value: EventEnvelopeError) -> Self {
    206         Self::Envelope(value)
    207     }
    208 }
    209 
    210 impl SignedEvent {
    211     pub fn new(parts: SignedEventParts) -> Result<Self, SignedEventError> {
    212         let id = EventId::parse(parts.id)
    213             .map_err(EventEnvelopeError::InvalidId)?
    214             .into_string();
    215         let pubkey = parse_public_key(parts.pubkey)
    216             .map_err(EventEnvelopeError::InvalidAuthor)?
    217             .to_hex();
    218         let sig = EventSignature::parse(parts.sig)
    219             .map_err(EventEnvelopeError::InvalidSignature)?
    220             .into_string();
    221         let wire = Nip01EventWire {
    222             id,
    223             pubkey,
    224             created_at: parts.created_at,
    225             kind: parts.kind,
    226             tags: parts.tags,
    227             content: parts.content,
    228             sig,
    229             extra: Default::default(),
    230         };
    231         Self::from_wire_verified_id(wire, parts.raw_json)
    232     }
    233 
    234     pub fn from_wire_verified_id(
    235         wire: Nip01EventWire,
    236         raw_json: impl Into<String>,
    237     ) -> Result<Self, SignedEventError> {
    238         wire.verify_id().map_err(SignedEventError::Wire)?;
    239         let raw_json = raw_json.into();
    240         let parsed =
    241             Nip01EventWire::parse_json(raw_json.as_str()).map_err(SignedEventError::RawJson)?;
    242         crate::require_invariant(parsed == wire, &|| SignedEventError::RawJsonMismatch)?;
    243         let envelope = wire
    244             .clone()
    245             .into_unverified_envelope()
    246             .map_err(SignedEventError::Envelope)?;
    247         Ok(Self {
    248             envelope,
    249             wire,
    250             raw_json,
    251         })
    252     }
    253 
    254     /// Checks exact raw/wire containment and the canonical ID under explicit
    255     /// caller-owned bounds. Signature verification remains a separate step.
    256     /// The legacy constructor and its default profile remain unchanged.
    257     pub fn from_wire_verified_id_with_limits(
    258         wire: Nip01EventWire,
    259         raw_json: impl Into<String>,
    260         limits: crate::wire::EventWireLimits,
    261     ) -> Result<Self, SignedEventError> {
    262         let raw_json = raw_json.into();
    263         let parsed = Nip01EventWire::parse_json_with_limits(&raw_json, limits)
    264             .map_err(SignedEventError::RawJson)?;
    265         crate::require_invariant(parsed == wire, &|| SignedEventError::RawJsonMismatch)?;
    266         wire.verify_id().map_err(SignedEventError::Wire)?;
    267         let envelope = EventEnvelope::new_with_limits(
    268             crate::envelope::EventEnvelopeParts {
    269                 id: wire.id.clone(),
    270                 author: wire.pubkey.clone(),
    271                 created_at: wire.created_at,
    272                 kind: wire.kind,
    273                 tags: wire.tags.clone(),
    274                 content: wire.content.clone(),
    275                 sig: wire.sig.clone(),
    276             },
    277             crate::envelope::EventEnvelopeLimits {
    278                 max_content_bytes: limits.max_content_bytes,
    279                 max_tag_count: limits.max_tag_count,
    280                 max_total_tag_elements: limits.max_total_tag_elements,
    281                 max_tag_element_bytes: limits.max_tag_element_bytes,
    282                 max_total_tag_bytes: limits.max_total_tag_bytes,
    283             },
    284         )
    285         .map_err(SignedEventError::Envelope)?;
    286         Ok(Self {
    287             envelope,
    288             wire,
    289             raw_json,
    290         })
    291     }
    292 
    293     #[inline]
    294     pub fn envelope(&self) -> &EventEnvelope {
    295         &self.envelope
    296     }
    297 
    298     #[inline]
    299     pub fn wire(&self) -> &Nip01EventWire {
    300         &self.wire
    301     }
    302 
    303     #[inline]
    304     pub fn raw_json(&self) -> &str {
    305         self.raw_json.as_str()
    306     }
    307 
    308     #[inline]
    309     pub fn id(&self) -> &EventId {
    310         self.envelope.id()
    311     }
    312 
    313     /// Returns the canonical NIP-01 event-id encoding retained by the wire boundary.
    314     #[inline]
    315     pub fn id_str(&self) -> &str {
    316         self.wire.id.as_str()
    317     }
    318 
    319     #[inline]
    320     pub fn id_hex(&self) -> String {
    321         self.envelope.id().to_hex()
    322     }
    323 
    324     #[inline]
    325     pub fn pubkey(&self) -> &PublicKey {
    326         self.envelope.author()
    327     }
    328 
    329     #[inline]
    330     pub fn created_at(&self) -> u64 {
    331         self.envelope.created_at_u64()
    332     }
    333 
    334     #[inline]
    335     pub fn kind(&self) -> u32 {
    336         self.envelope.kind_u32()
    337     }
    338 
    339     pub fn tags_as_vec(&self) -> Vec<Vec<String>> {
    340         self.envelope.tags_as_vec()
    341     }
    342 
    343     #[inline]
    344     pub fn content(&self) -> &str {
    345         self.envelope.content()
    346     }
    347 
    348     #[inline]
    349     pub fn sig(&self) -> &EventSignature {
    350         self.envelope.sig()
    351     }
    352 
    353     /// Returns the canonical NIP-01 signature encoding retained by the wire boundary.
    354     #[inline]
    355     pub fn sig_str(&self) -> &str {
    356         self.wire.sig.as_str()
    357     }
    358 
    359     #[inline]
    360     pub fn signature_hex(&self) -> String {
    361         self.envelope.sig().to_hex()
    362     }
    363 }
    364 
    365 pub fn compute_nip01_event_id(
    366     pubkey: &str,
    367     created_at: u64,
    368     kind: u32,
    369     tags: &[Vec<String>],
    370     content: &str,
    371 ) -> Result<EventId, DraftError> {
    372     parse_public_key(pubkey)?;
    373     Ok(compute_nip01_event_id_for_valid_pubkey(
    374         pubkey, created_at, kind, tags, content,
    375     ))
    376 }
    377 
    378 pub fn nip01_event_id_preimage(
    379     pubkey: &str,
    380     created_at: u64,
    381     kind: u32,
    382     tags: &[Vec<String>],
    383     content: &str,
    384 ) -> Result<String, DraftError> {
    385     parse_public_key(pubkey)?;
    386     Ok(nip01_event_id_preimage_for_valid_pubkey(
    387         pubkey, created_at, kind, tags, content,
    388     ))
    389 }
    390 
    391 #[cfg_attr(coverage_nightly, coverage(off))]
    392 fn compute_nip01_event_id_for_valid_pubkey(
    393     pubkey: &str,
    394     created_at: u64,
    395     kind: u32,
    396     tags: &[Vec<String>],
    397     content: &str,
    398 ) -> EventId {
    399     compute_canonical_nip01_event_id(pubkey, created_at, kind, tags, content)
    400         .expect("a validated public key always produces a canonical event id")
    401 }
    402 
    403 #[cfg_attr(coverage_nightly, coverage(off))]
    404 fn nip01_event_id_preimage_for_valid_pubkey(
    405     pubkey: &str,
    406     created_at: u64,
    407     kind: u32,
    408     tags: &[Vec<String>],
    409     content: &str,
    410 ) -> String {
    411     canonical_nip01_event_id_preimage(pubkey, created_at, kind, tags, content)
    412         .expect("a validated public key always produces a canonical preimage")
    413 }
    414 
    415 #[cfg(test)]
    416 #[cfg_attr(coverage_nightly, coverage(off))]
    417 mod tests {
    418     use super::*;
    419     use crate::envelope::kind::KIND_POST;
    420 
    421     fn hex_64(character: char) -> String {
    422         crate::test_valid_hex_64(character)
    423     }
    424 
    425     fn hex_128(character: char) -> String {
    426         core::iter::repeat_n(character, 128).collect()
    427     }
    428 
    429     fn verified_wire(content: &str) -> Nip01EventWire {
    430         let pubkey = hex_64('a');
    431         let id = compute_canonical_nip01_event_id(&pubkey, 1_700_000_000, KIND_POST, &[], content)
    432             .expect("event id")
    433             .into_string();
    434         Nip01EventWire {
    435             id,
    436             pubkey,
    437             created_at: 1_700_000_000,
    438             kind: KIND_POST,
    439             tags: Vec::new(),
    440             content: content.to_owned(),
    441             sig: hex_128('b'),
    442             extra: Default::default(),
    443         }
    444     }
    445 
    446     fn raw_json_for_wire(wire: &Nip01EventWire) -> String {
    447         serde_json::to_string(&serde_json::json!({
    448             "id": wire.id,
    449             "pubkey": wire.pubkey,
    450             "created_at": wire.created_at,
    451             "kind": wire.kind,
    452             "tags": wire.tags,
    453             "content": wire.content,
    454             "sig": wire.sig,
    455         }))
    456         .expect("raw JSON")
    457     }
    458 
    459     #[test]
    460     fn signed_event_preserves_verified_wire_and_typed_accessors() {
    461         let wire = verified_wire("hello");
    462         let raw_json = raw_json_for_wire(&wire);
    463         let signed = SignedEvent::from_wire_verified_id(wire.clone(), raw_json.clone())
    464             .expect("signed event");
    465 
    466         assert_eq!(signed.wire(), &wire);
    467         assert_eq!(signed.raw_json(), raw_json);
    468         assert_eq!(signed.envelope().id_hex(), signed.id_hex());
    469         assert_eq!(signed.id().to_hex(), signed.id_hex());
    470         assert_eq!(signed.pubkey().to_hex(), wire.pubkey);
    471         assert_eq!(signed.created_at(), wire.created_at);
    472         assert_eq!(signed.kind(), wire.kind);
    473         assert_eq!(signed.tags_as_vec(), wire.tags);
    474         assert_eq!(signed.content(), wire.content);
    475         assert_eq!(signed.sig().to_hex(), signed.signature_hex());
    476         assert_eq!(signed.sig_str(), wire.sig);
    477     }
    478 
    479     #[test]
    480     fn explicit_wire_budget_preserves_exact_raw_and_default_limits_remain_unchanged() {
    481         let mut wire = verified_wire("public content");
    482         wire.tags = vec![vec!["radroots:listing".into(), "x".repeat(4097)]];
    483         wire.id = compute_canonical_nip01_event_id(
    484             &wire.pubkey,
    485             wire.created_at,
    486             wire.kind,
    487             &wire.tags,
    488             &wire.content,
    489         )
    490         .unwrap()
    491         .into_string();
    492         let raw = format!(" \n{} \t", raw_json_for_wire(&wire));
    493         assert!(SignedEvent::from_wire_verified_id(wire.clone(), raw.clone()).is_err());
    494         let limits = crate::wire::EventWireLimits {
    495             max_raw_json_bytes: raw.len(),
    496             max_tag_element_bytes: 4097,
    497             ..Default::default()
    498         };
    499         let event =
    500             SignedEvent::from_wire_verified_id_with_limits(wire.clone(), raw.clone(), limits)
    501                 .unwrap();
    502         assert_eq!(event.raw_json(), raw);
    503         assert_eq!(event.wire(), &wire);
    504         assert_eq!(event.envelope().tags_as_vec(), wire.tags);
    505         for reduced in [
    506             crate::wire::EventWireLimits {
    507                 max_raw_json_bytes: raw.len() - 1,
    508                 ..limits
    509             },
    510             crate::wire::EventWireLimits {
    511                 max_tag_element_bytes: 4096,
    512                 ..limits
    513             },
    514         ] {
    515             assert!(
    516                 SignedEvent::from_wire_verified_id_with_limits(wire.clone(), raw.clone(), reduced)
    517                     .is_err()
    518             );
    519         }
    520         let other = verified_wire("different exact input");
    521         assert_eq!(
    522             SignedEvent::from_wire_verified_id_with_limits(wire, raw_json_for_wire(&other), limits)
    523                 .unwrap_err(),
    524             SignedEventError::RawJsonMismatch
    525         );
    526     }
    527 
    528     #[test]
    529     fn signed_event_rejects_noncanonical_or_mismatched_wire() {
    530         let wire = verified_wire("hello");
    531         let raw_json = raw_json_for_wire(&wire);
    532         let mut different_wire = verified_wire("different");
    533         let error =
    534             SignedEvent::from_wire_verified_id(wire.clone(), raw_json_for_wire(&different_wire))
    535                 .expect_err("raw JSON mismatch");
    536         assert_eq!(error, SignedEventError::RawJsonMismatch);
    537 
    538         different_wire.id = hex_64('c');
    539         let error = SignedEvent::from_wire_verified_id(
    540             different_wire.clone(),
    541             raw_json_for_wire(&different_wire),
    542         )
    543         .expect_err("event id mismatch");
    544         assert!(matches!(error, SignedEventError::Wire(_)));
    545 
    546         let error = SignedEvent::new(SignedEventParts {
    547             id: "not-hex".to_owned(),
    548             pubkey: hex_64('a'),
    549             created_at: 1,
    550             kind: KIND_POST,
    551             tags: Vec::new(),
    552             content: String::new(),
    553             sig: hex_128('b'),
    554             raw_json,
    555         })
    556         .expect_err("invalid id");
    557         assert!(matches!(
    558             error,
    559             SignedEventError::Envelope(EventEnvelopeError::InvalidId(_))
    560         ));
    561     }
    562 
    563     #[test]
    564     fn event_id_helpers_are_canonical_and_reject_invalid_pubkeys() {
    565         let expected = "bb46df8e0d14e08773c7c6c88dfbb0925e6432048a2f2e82592afa415462d62a";
    566         let event_id = compute_nip01_event_id(&hex_64('a'), 1_700_000_000, KIND_POST, &[], "hello")
    567             .expect("event id");
    568         assert_eq!(event_id.to_hex(), expected);
    569         assert_eq!(
    570             nip01_event_id_preimage(&hex_64('a'), 1_700_000_000, KIND_POST, &[], "hello")
    571                 .expect("preimage"),
    572             "[0,\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",1700000000,1,[],\"hello\"]"
    573         );
    574 
    575         assert!(matches!(
    576             compute_nip01_event_id("not-hex", 1, KIND_POST, &[], ""),
    577             Err(DraftError::IdParse(_))
    578         ));
    579         assert!(matches!(
    580             nip01_event_id_preimage("not-hex", 1, KIND_POST, &[], ""),
    581             Err(DraftError::IdParse(_))
    582         ));
    583     }
    584 
    585     #[test]
    586     fn errors_have_stable_nonempty_messages() {
    587         let errors = [
    588             DraftError::UnknownContract("missing".to_owned()),
    589             DraftError::ContractNotDraftAuthorable {
    590                 contract_id: "typed-only".to_owned(),
    591             },
    592             DraftError::from(ParseError::Empty),
    593             DraftError::from(EventEnvelopeError::NonCanonicalId),
    594             DraftError::from(SignedEventError::RawJsonMismatch),
    595         ];
    596         for error in errors {
    597             assert!(!error.to_string().is_empty());
    598         }
    599     }
    600 }