lib

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

plan_signing.rs (6562B)


      1 //! Exact Nostr unsigned-event construction and completion for authored plans.
      2 
      3 #![forbid(unsafe_code)]
      4 
      5 use crate::{
      6     error::Error,
      7     types::{
      8         RadrootsNostrEvent, RadrootsNostrEventId, RadrootsNostrKind, RadrootsNostrPublicKey,
      9         RadrootsNostrTag, RadrootsNostrTimestamp,
     10     },
     11 };
     12 use radroots_event_codec::authoring::AuthoredEventPlan;
     13 #[cfg(feature = "signing")]
     14 use radroots_signing::SignRequest;
     15 
     16 #[cfg(feature = "signing")]
     17 use nostr::JsonUtil;
     18 #[cfg(feature = "signing")]
     19 use radroots_event::{SignedEvent, wire::Nip01EventWire};
     20 
     21 pub(crate) fn unsigned_event_from_plan(
     22     plan: &AuthoredEventPlan,
     23 ) -> Result<nostr::UnsignedEvent, Error> {
     24     let kind = u16::try_from(plan.body().kind()).map_err(|_| Error::KindOutOfRange {
     25         kind: plan.body().kind(),
     26         max: u16::MAX,
     27     })?;
     28     let tags = plan
     29         .body()
     30         .tags()
     31         .iter()
     32         .cloned()
     33         .map(RadrootsNostrTag::parse)
     34         .collect::<Result<alloc::vec::Vec<_>, _>>()
     35         .map_err(|_| Error::TagConversion)?;
     36     let expected_event_id = RadrootsNostrEventId::from_slice(plan.expected_event_id().as_bytes())
     37         .map_err(|_| Error::EventConversion {
     38         field: "expected_event_id",
     39     })?;
     40     let expected_public_key = RadrootsNostrPublicKey::from_slice(plan.author().as_bytes())
     41         .map_err(|_| Error::EventConversion { field: "author" })?;
     42 
     43     let unsigned = nostr::UnsignedEvent {
     44         id: Some(expected_event_id),
     45         pubkey: expected_public_key,
     46         created_at: RadrootsNostrTimestamp::from_secs(plan.created_at()),
     47         kind: RadrootsNostrKind::Custom(kind),
     48         tags: nostr::Tags::from_list(tags),
     49         content: plan.body().content().into(),
     50     };
     51     validate_unsigned_event_matches_plan(&unsigned, plan)?;
     52     Ok(unsigned)
     53 }
     54 
     55 #[cfg(feature = "signing")]
     56 pub(crate) fn unsigned_event_from_fields(
     57     fields: radroots_protocol::nip01::EventFields<'_>,
     58     expected_id: radroots_event::id::EventId,
     59 ) -> Result<nostr::UnsignedEvent, Error> {
     60     let kind = u16::try_from(fields.kind).map_err(|_| Error::KindOutOfRange {
     61         kind: fields.kind,
     62         max: u16::MAX,
     63     })?;
     64     let tags = fields
     65         .tags
     66         .iter()
     67         .cloned()
     68         .map(RadrootsNostrTag::parse)
     69         .collect::<Result<alloc::vec::Vec<_>, _>>()
     70         .map_err(|_| Error::TagConversion)?;
     71     let pubkey = RadrootsNostrPublicKey::from_slice(fields.author.as_bytes())
     72         .map_err(|_| Error::EventConversion { field: "author" })?;
     73     let created_at = RadrootsNostrTimestamp::from_secs(fields.created_at);
     74     let kind = RadrootsNostrKind::Custom(kind);
     75     let tags = nostr::Tags::from_list(tags);
     76     let id = RadrootsNostrEventId::new(&pubkey, &created_at, &kind, &tags, fields.content);
     77     if id.as_bytes() != expected_id.as_bytes() {
     78         return Err(Error::ExternalSigningPlanMismatch {
     79             field: "expected_event_id",
     80         });
     81     }
     82     Ok(nostr::UnsignedEvent {
     83         id: Some(id),
     84         pubkey,
     85         created_at,
     86         kind,
     87         tags,
     88         content: fields.content.into(),
     89     })
     90 }
     91 
     92 #[cfg(feature = "signing")]
     93 fn unsigned_event_from_request(request: &SignRequest) -> Result<nostr::UnsignedEvent, Error> {
     94     let kind = u16::try_from(request.kind()).map_err(|_| Error::KindOutOfRange {
     95         kind: request.kind(),
     96         max: u16::MAX,
     97     })?;
     98     let tags = request
     99         .tags()
    100         .iter()
    101         .cloned()
    102         .map(RadrootsNostrTag::parse)
    103         .collect::<Result<alloc::vec::Vec<_>, _>>()
    104         .map_err(|_| Error::TagConversion)?;
    105     let expected_event_id =
    106         RadrootsNostrEventId::from_slice(request.expected_event_id().as_bytes()).map_err(|_| {
    107             Error::EventConversion {
    108                 field: "expected_event_id",
    109             }
    110         })?;
    111     let expected_public_key =
    112         RadrootsNostrPublicKey::from_slice(request.expected_author().as_bytes())
    113             .map_err(|_| Error::EventConversion { field: "author" })?;
    114     Ok(nostr::UnsignedEvent {
    115         id: Some(expected_event_id),
    116         pubkey: expected_public_key,
    117         created_at: RadrootsNostrTimestamp::from_secs(request.created_at()),
    118         kind: RadrootsNostrKind::Custom(kind),
    119         tags: nostr::Tags::from_list(tags),
    120         content: request.content().into(),
    121     })
    122 }
    123 
    124 #[cfg(feature = "signing")]
    125 pub(crate) fn sign_request(
    126     keys: &nostr::Keys,
    127     request: &SignRequest,
    128 ) -> Result<SignedEvent, Error> {
    129     let event = unsigned_event_from_request(request)?.sign_with_keys(keys)?;
    130     let raw_json = event.as_json();
    131     let wire = Nip01EventWire::parse_json(&raw_json)?;
    132     SignedEvent::from_wire_verified_id(wire, raw_json).map_err(Into::into)
    133 }
    134 
    135 pub(crate) fn validate_signed_event_matches_plan(
    136     event: &RadrootsNostrEvent,
    137     plan: &AuthoredEventPlan,
    138 ) -> Result<(), Error> {
    139     validate_exact_fields(
    140         event.pubkey,
    141         event.created_at,
    142         event.kind,
    143         &event.tags,
    144         &event.content,
    145         plan,
    146     )
    147 }
    148 
    149 fn validate_unsigned_event_matches_plan(
    150     event: &nostr::UnsignedEvent,
    151     plan: &AuthoredEventPlan,
    152 ) -> Result<(), Error> {
    153     if event.id.map(|id| id.to_bytes()) != Some(*plan.expected_event_id().as_bytes()) {
    154         return Err(Error::ExternalSigningPlanMismatch {
    155             field: "expected_event_id",
    156         });
    157     }
    158     validate_exact_fields(
    159         event.pubkey,
    160         event.created_at,
    161         event.kind,
    162         &event.tags,
    163         &event.content,
    164         plan,
    165     )
    166 }
    167 
    168 fn validate_exact_fields(
    169     author: RadrootsNostrPublicKey,
    170     created_at: RadrootsNostrTimestamp,
    171     kind: RadrootsNostrKind,
    172     tags: &nostr::Tags,
    173     content: &str,
    174     plan: &AuthoredEventPlan,
    175 ) -> Result<(), Error> {
    176     if author.to_bytes() != *plan.author().as_bytes() {
    177         return Err(Error::ExternalSigningPlanMismatch { field: "author" });
    178     }
    179     if created_at.as_secs() != plan.created_at() {
    180         return Err(Error::ExternalSigningPlanMismatch {
    181             field: "created_at",
    182         });
    183     }
    184     if u32::from(kind.as_u16()) != plan.body().kind() {
    185         return Err(Error::ExternalSigningPlanMismatch { field: "kind" });
    186     }
    187     if tags.len() != plan.body().tags().len()
    188         || tags
    189             .iter()
    190             .zip(plan.body().tags())
    191             .any(|(actual, expected)| actual.as_slice() != expected)
    192     {
    193         return Err(Error::ExternalSigningPlanMismatch { field: "tags" });
    194     }
    195     if content != plan.body().content() {
    196         return Err(Error::ExternalSigningPlanMismatch { field: "content" });
    197     }
    198     Ok(())
    199 }