codec.rs (2155B)
1 //! Stateless convenience entrypoints for the canonical codec stages. 2 3 #[cfg(feature = "json")] 4 use crate::{DecodeError, EncodeError, decode, encode}; 5 use crate::{VerificationError, verify}; 6 #[cfg(all(not(feature = "std"), feature = "json"))] 7 use alloc::string::String; 8 #[cfg(all(feature = "std", feature = "json"))] 9 use std::string::String; 10 11 /// Stateless convenience entrypoints for the canonical codec stages. 12 /// 13 /// The methods preserve the same explicit typestate transitions as their 14 /// module-level counterparts; using `Codec` never combines or skips stages. 15 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] 16 pub struct Codec; 17 18 impl Codec { 19 /// Decodes compact NIP-01 JSON into an unverified event. 20 #[cfg(feature = "json")] 21 pub fn decode_event(raw_json: &str) -> Result<verify::RawEvent, DecodeError> { 22 decode::event(raw_json) 23 } 24 25 /// Decodes canonical NIP-01 JSON and verifies its declared event ID. 26 #[cfg(feature = "json")] 27 pub fn decode_signed_event(raw_json: &str) -> Result<radroots_event::SignedEvent, DecodeError> { 28 decode::signed_event(raw_json) 29 } 30 31 /// Encodes a native event envelope as compact NIP-01 JSON. 32 #[cfg(feature = "json")] 33 pub fn encode_event( 34 event: &radroots_event::envelope::EventEnvelope, 35 ) -> Result<String, EncodeError> { 36 encode::event(event) 37 } 38 39 /// Verifies an event's canonical identifier. 40 pub fn verify_id( 41 event: verify::RawEvent, 42 ) -> Result<verify::IdVerifiedEvent, VerificationError> { 43 verify::id(event) 44 } 45 46 /// Verifies an event signature through an explicit verifier. 47 pub fn verify_signature<V>( 48 event: verify::IdVerifiedEvent, 49 verifier: &V, 50 ) -> Result<verify::SignatureVerifiedEvent, VerificationError> 51 where 52 V: verify::SignatureVerifier + ?Sized, 53 { 54 verify::signature(event, verifier) 55 } 56 57 /// Validates an already signature-verified event contract. 58 pub fn verify_contract( 59 event: verify::SignatureVerifiedEvent, 60 ) -> Result<verify::ContractValidatedEvent, VerificationError> { 61 verify::contract(event) 62 } 63 }