decode.rs (9493B)
1 //! Deterministic event decoding boundary. 2 //! 3 //! Decoding validates the wire structure and returns a [`RawEvent`]. It does 4 //! not verify the event identifier, signature, or contract. Those transitions 5 //! remain explicit under [`crate::verify`]. 6 7 use core::fmt; 8 use radroots_event::{envelope::EventEnvelopeError, wire::EventWireError}; 9 10 // Domain-specific parsers live behind the canonical decoding namespace. 11 pub use crate::error::EventParseError; 12 pub use crate::parsed::{RadrootsParsedData, RadrootsParsedEvent}; 13 14 pub mod event_ref { 15 pub use crate::event_ref::*; 16 } 17 18 pub mod parsed { 19 pub use crate::parsed::*; 20 } 21 22 pub mod wire { 23 pub use crate::wire::*; 24 } 25 26 macro_rules! decode_domain { 27 ($name:ident, $source:path) => { 28 pub mod $name { 29 pub use $source::*; 30 } 31 }; 32 } 33 34 decode_domain!(app_data, crate::app_data::decode); 35 decode_domain!(article, crate::article::decode); 36 decode_domain!(calendar, crate::calendar::decode); 37 #[cfg(feature = "json")] 38 decode_domain!(coop, crate::coop::decode); 39 #[cfg(feature = "json")] 40 decode_domain!(document, crate::document::decode); 41 #[cfg(feature = "json")] 42 decode_domain!(farm_crdt, crate::farm_crdt::decode); 43 decode_domain!(farm_file, crate::farm_file::decode); 44 #[cfg(feature = "json")] 45 decode_domain!(farm_workspace, crate::farm_workspace::decode); 46 decode_domain!(file_metadata, crate::file_metadata::decode); 47 decode_domain!(follow, crate::follow::decode); 48 decode_domain!(geochat, crate::geochat::decode); 49 decode_domain!(gift_wrap, crate::gift_wrap::decode); 50 decode_domain!(group, crate::group::decode); 51 decode_domain!(http_auth, crate::http_auth::decode); 52 decode_domain!(list, crate::list::decode); 53 decode_domain!(list_set, crate::list_set::decode); 54 decode_domain!(message, crate::message::decode); 55 decode_domain!(message_file, crate::message_file::decode); 56 #[cfg(feature = "json")] 57 decode_domain!(plot, crate::plot::decode); 58 decode_domain!(reaction, crate::reaction::decode); 59 decode_domain!(relay_auth, crate::relay_auth::decode); 60 #[cfg(feature = "json")] 61 decode_domain!(relay_document, crate::relay_document::decode); 62 decode_domain!(report, crate::report::decode); 63 decode_domain!(repost, crate::repost::decode); 64 #[cfg(feature = "json")] 65 decode_domain!(resource_area, crate::resource_area::decode); 66 #[cfg(feature = "json")] 67 decode_domain!(resource_cap, crate::resource_cap::decode); 68 decode_domain!(seal, crate::seal::decode); 69 70 pub mod comment { 71 pub use crate::comment::inbound::*; 72 } 73 74 pub mod deletion { 75 pub use crate::deletion::inbound::*; 76 pub use crate::deletion::reconciliation_v1::inbound as reconciliation_v1; 77 } 78 79 #[cfg(feature = "json")] 80 pub mod farm { 81 pub use crate::farm::decode::*; 82 } 83 84 pub mod food_availability { 85 pub use crate::food_availability::inbound::*; 86 } 87 88 pub mod job { 89 pub use crate::job::error::*; 90 pub use crate::job::traits::*; 91 pub use crate::job::util::*; 92 93 pub mod feedback { 94 pub use crate::job::feedback::decode::*; 95 } 96 pub mod request { 97 pub use crate::job::request::decode::*; 98 } 99 pub mod result { 100 pub use crate::job::result::decode::*; 101 } 102 } 103 104 #[cfg(feature = "knowledge")] 105 pub mod knowledge { 106 pub use crate::knowledge::decode::*; 107 } 108 109 pub mod operational_listing { 110 pub use crate::operational_listing::decode::*; 111 } 112 113 #[cfg(feature = "json")] 114 pub mod order { 115 pub use crate::order::decode::*; 116 } 117 118 pub mod post { 119 pub use crate::post::inbound::*; 120 } 121 122 #[cfg(feature = "json")] 123 pub mod profile { 124 pub use crate::profile::inbound::*; 125 } 126 127 pub mod reply { 128 pub use crate::reply::inbound::*; 129 } 130 131 #[cfg(feature = "json")] 132 pub mod rhi { 133 pub use crate::rhi::{ 134 RadrootsRhiEvidenceAttestationError, RadrootsRhiEvidenceAttestationOutcomeV1, 135 RadrootsRhiEvidenceAttestationSupersessionV1, RadrootsRhiEvidenceAttestationV1, 136 rhi_evidence_attestation_from_event, rhi_evidence_attestation_from_verified_event, 137 validate_rhi_evidence_attestation_supersession, validate_rhi_evidence_attestation_tags, 138 }; 139 } 140 141 #[cfg(feature = "json")] 142 pub mod trade { 143 pub use crate::trade::{ 144 RadrootsTradeMutationError, trade_mutation_from_event, trade_mutation_from_verified_event, 145 validate_trade_mutation_tags, 146 }; 147 } 148 149 #[cfg(feature = "json")] 150 pub use radroots_event::wire::EventWireLimits; 151 #[cfg(feature = "json")] 152 use radroots_event::{ 153 SignedEvent, 154 admission::RawEvent, 155 wire::{DEFAULT_RAW_JSON_MAX_BYTES, Nip01EventWire}, 156 }; 157 158 /// Maximum compact NIP-01 event JSON size accepted by [`event`]. 159 #[cfg(feature = "json")] 160 pub const MAX_EVENT_JSON_BYTES: usize = DEFAULT_RAW_JSON_MAX_BYTES; 161 162 /// A failure while decoding an untrusted event representation. 163 #[non_exhaustive] 164 #[derive(Clone, Debug, PartialEq, Eq)] 165 pub enum DecodeError { 166 /// The encoded event exceeds the public input budget. 167 InputTooLarge { max: usize, actual: usize }, 168 /// The input is not a structurally valid event JSON object. 169 InvalidJson, 170 /// A decoded field violates the native event-envelope contract. 171 InvalidEnvelope(EventEnvelopeError), 172 /// A decoded field violates the bounded NIP-01 wire contract. 173 InvalidWire(EventWireError), 174 } 175 176 impl DecodeError { 177 /// Returns a stable machine-readable error code. 178 #[must_use] 179 pub const fn code(&self) -> &'static str { 180 match self { 181 Self::InputTooLarge { .. } => "input_too_large", 182 Self::InvalidJson => "invalid_json", 183 Self::InvalidEnvelope(_) => "invalid_envelope", 184 Self::InvalidWire(_) => "invalid_wire", 185 } 186 } 187 } 188 189 impl fmt::Display for DecodeError { 190 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { 191 match self { 192 Self::InputTooLarge { max, actual } => { 193 write!(formatter, "event JSON size {actual} exceeds {max} bytes") 194 } 195 Self::InvalidJson => formatter.write_str("event JSON is invalid"), 196 Self::InvalidEnvelope(error) => write!(formatter, "event envelope is invalid: {error}"), 197 Self::InvalidWire(error) => write!(formatter, "event wire is invalid: {error}"), 198 } 199 } 200 } 201 202 #[cfg(feature = "std")] 203 impl std::error::Error for DecodeError { 204 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { 205 match self { 206 Self::InvalidEnvelope(error) => Some(error), 207 Self::InvalidWire(error) => Some(error), 208 Self::InputTooLarge { .. } | Self::InvalidJson => None, 209 } 210 } 211 } 212 213 /// Decodes compact NIP-01 event JSON without hiding later validation stages. 214 /// 215 /// The returned [`RawEvent`] must still pass [`crate::verify::id`], 216 /// [`crate::verify::signature`], and [`crate::verify::contract`] before it is 217 /// treated as verified or contract-valid. 218 /// 219 /// ```no_run 220 /// # #[cfg(feature = "json")] 221 /// # { 222 /// let raw_json = r#"{"id":"00","pubkey":"00","created_at":0,"kind":1,"tags":[],"content":"","sig":"00"}"#; 223 /// let raw = radroots_event_codec::decode::event(raw_json)?; 224 /// let id_verified = radroots_event_codec::verify::id(raw)?; 225 /// # let _ = id_verified; 226 /// # } 227 /// # Ok::<(), Box<dyn std::error::Error>>(()) 228 /// ``` 229 #[cfg(feature = "json")] 230 pub fn event(raw_json: &str) -> Result<RawEvent, DecodeError> { 231 let max = MAX_EVENT_JSON_BYTES; 232 let actual = raw_json.len(); 233 if actual > max { 234 return Err(DecodeError::InputTooLarge { max, actual }); 235 } 236 237 let wire = Nip01EventWire::parse_json_unverified(raw_json).map_err(map_wire_error)?; 238 let envelope = wire 239 .into_unverified_envelope() 240 .map_err(DecodeError::InvalidEnvelope)?; 241 Ok(RawEvent::new(envelope)) 242 } 243 244 /// Decodes compact NIP-01 JSON into an ID-verified signed event. 245 #[cfg(feature = "json")] 246 pub fn signed_event(raw_json: &str) -> Result<SignedEvent, DecodeError> { 247 signed_event_with_limits(raw_json, EventWireLimits::default()) 248 } 249 250 /// Decode an ID-verified event under explicit caller-owned bounds. Legacy 251 /// defaults remain unchanged; signature and product admission stay separate. 252 #[cfg(feature = "json")] 253 pub fn signed_event_with_limits( 254 raw_json: &str, 255 limits: EventWireLimits, 256 ) -> Result<SignedEvent, DecodeError> { 257 let max = limits.max_raw_json_bytes; 258 let actual = raw_json.len(); 259 if actual > max { 260 return Err(DecodeError::InputTooLarge { max, actual }); 261 } 262 let wire = Nip01EventWire::parse_json_with_limits(raw_json, limits).map_err(map_wire_error)?; 263 SignedEvent::from_wire_verified_id_with_limits(wire, raw_json, limits).map_err(|error| { 264 match error { 265 radroots_event::draft::SignedEventError::Envelope(error) => { 266 DecodeError::InvalidEnvelope(error) 267 } 268 radroots_event::draft::SignedEventError::Wire(error) 269 | radroots_event::draft::SignedEventError::RawJson(error) => map_wire_error(error), 270 radroots_event::draft::SignedEventError::RawJsonMismatch => DecodeError::InvalidJson, 271 } 272 }) 273 } 274 275 #[cfg(feature = "json")] 276 fn map_wire_error(error: EventWireError) -> DecodeError { 277 match error { 278 EventWireError::RawJsonTooLarge { max, actual } => { 279 DecodeError::InputTooLarge { max, actual } 280 } 281 EventWireError::Json(_) 282 | EventWireError::RootNotObject 283 | EventWireError::MissingField(_) 284 | EventWireError::InvalidField(_) => DecodeError::InvalidJson, 285 EventWireError::Envelope(error) => DecodeError::InvalidEnvelope(error), 286 error => DecodeError::InvalidWire(error), 287 } 288 }