public_ingress.rs (7770B)
1 //! Authenticated observed heads. Observation is neither a global current head, 2 //! a verified running capability nor permission to request or accept an order. 3 use crate::event_verify::{SignedReadError, signed_json_with_limits}; 4 use alloc::boxed::Box; 5 use core::fmt; 6 use radroots_event::envelope::{ 7 EventEnvelope, 8 event_head::{ 9 self, CurrentEventHead, EventHeadCandidateResult, EventHeadCoordinate, EventHeadDecision, 10 }, 11 }; 12 use radroots_protocol::{ 13 advertisement::{self, Advertisement}, 14 command::CommandError, 15 listing::{self, DecodedListing}, 16 nip01::EventFields, 17 profile, 18 }; 19 20 /// Fixed input-free public admission failures. 21 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 22 pub enum Error { 23 InvalidInput, 24 LimitExceeded, 25 Unauthenticated, 26 ScopeMismatch, 27 } 28 impl fmt::Display for Error { 29 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 30 f.write_str(match self { 31 Self::InvalidInput => "invalid public input", 32 Self::LimitExceeded => "public input limit exceeded", 33 Self::Unauthenticated => "unauthenticated public event", 34 Self::ScopeMismatch => "public scope mismatch", 35 }) 36 } 37 } 38 impl core::error::Error for Error {} 39 impl From<SignedReadError> for Error { 40 fn from(value: SignedReadError) -> Self { 41 match value { 42 SignedReadError::InvalidInput => Self::InvalidInput, 43 SignedReadError::LimitExceeded => Self::LimitExceeded, 44 SignedReadError::Unauthenticated => Self::Unauthenticated, 45 } 46 } 47 } 48 49 /// Selected authenticated evidence; no public constructor can forge provenance. 50 pub struct ObservedHead { 51 scope: EventHeadCoordinate, 52 current: Option<Selected>, 53 } 54 struct Selected { 55 head: CurrentEventHead, 56 event: EventEnvelope, 57 raw: Box<str>, 58 } 59 impl fmt::Debug for ObservedHead { 60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 61 f.write_str("ObservedHead(<original authenticated evidence>)") 62 } 63 } 64 /// Post-selection interpretation. Every non-known outcome retains the same 65 /// authentic head; callers cannot use an older event as an actionable fallback. 66 #[derive(Debug)] 67 pub enum Interpretation { 68 Listing(Box<DecodedListing>), 69 Capabilities(Advertisement), 70 Unsupported, 71 Invalid, 72 Expired, 73 ClockAhead, 74 } 75 impl ObservedHead { 76 /// Captures one canonical public listing scope before copying its bounded d. 77 pub fn listing(author: radroots_identity::PublicKey, d: &str) -> Result<Self, Error> { 78 if d.len() != 32 { 79 return Err(Error::InvalidInput); 80 } 81 Self::new(EventHeadCoordinate::Addressable { 82 kind: listing::LISTING_KIND, 83 pubkey: author, 84 d_tag: d.into(), 85 }) 86 } 87 /// Captures the assigned per-author replaceable capability scope. 88 pub fn capabilities(author: radroots_identity::PublicKey) -> Self { 89 Self { 90 scope: EventHeadCoordinate::Replaceable { 91 kind: u32::from(profile::CAPABILITIES_KIND), 92 pubkey: author, 93 }, 94 current: None, 95 } 96 } 97 /// Captures one explicit supported numeric coordinate. This allocates no 98 /// network client, performs no IO and makes no observation claim. 99 pub fn new(scope: EventHeadCoordinate) -> Result<Self, Error> { 100 let valid = match &scope { 101 EventHeadCoordinate::Replaceable { kind, .. } => { 102 *kind == u32::from(profile::CAPABILITIES_KIND) 103 } 104 EventHeadCoordinate::Addressable { kind, d_tag, .. } => { 105 *kind == listing::LISTING_KIND 106 && d_tag.len() == 32 107 && d_tag 108 .bytes() 109 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) 110 } 111 }; 112 if !valid { 113 return Err(Error::InvalidInput); 114 } 115 Ok(Self { 116 scope, 117 current: None, 118 }) 119 } 120 /// Authenticate original bounded bytes before raw NIP01 ranking. Invalid 121 /// signatures or foreign scopes never mutate the retained head. Only one 122 /// original event and parsed representation are retained per scope. 123 pub fn observe(&mut self, raw: &str) -> Result<EventHeadDecision, Error> { 124 let event = signed_json_with_limits( 125 raw, 126 radroots_event::wire::EventWireLimits { 127 max_raw_json_bytes: profile::SIGNED_EVENT_MAX_BYTES, 128 max_content_bytes: profile::SIGNED_EVENT_MAX_BYTES, 129 max_tag_element_bytes: profile::SIGNED_EVENT_MAX_BYTES, 130 max_total_tag_bytes: profile::SIGNED_EVENT_MAX_BYTES, 131 ..Default::default() 132 }, 133 )?; 134 let EventHeadCandidateResult::Candidate(candidate) = 135 event_head::event_head_candidate_for_nip01_event(&event) 136 else { 137 return Err(Error::ScopeMismatch); 138 }; 139 if candidate.coordinate != self.scope { 140 return Err(Error::ScopeMismatch); 141 } 142 let decision = 143 event_head::select_event_head(candidate, self.current.as_ref().map(|v| &v.head)); 144 if let EventHeadDecision::Applied(head) = &decision { 145 self.current = Some(Selected { 146 head: head.clone(), 147 event, 148 raw: Box::from(raw), 149 }); 150 } 151 Ok(decision) 152 } 153 /// Borrows the original authenticated selected object, including unsupported 154 /// or invalid-profile evidence. Absence is not fabricated empty history. 155 pub fn raw_json(&self) -> Option<&str> { 156 self.current.as_ref().map(|v| v.raw.as_ref()) 157 } 158 pub fn selected(&self) -> Option<&CurrentEventHead> { 159 self.current.as_ref().map(|v| &v.head) 160 } 161 /// Evaluate only the selected head with caller-injected observation time. 162 /// Any future author timestamp is flagged; no hidden skew, ambient clock, 163 /// automatic purge or older-head fallback is introduced. 164 pub fn interpret(&self, observed_at: advertisement::UnixSeconds) -> Option<Interpretation> { 165 let Some(value) = &self.current else { 166 return None; 167 }; 168 let observed_at = observed_at.get(); 169 if value.event.created_at_u64() > observed_at { 170 return Some(Interpretation::ClockAhead); 171 } 172 let event = &value.event; 173 let result = match &self.scope { 174 EventHeadCoordinate::Addressable { .. } => { 175 let tags = event.tags_as_vec(); 176 let fields = EventFields { 177 author: *event.author(), 178 created_at: event.created_at_u64(), 179 kind: event.kind_u32(), 180 tags: &tags, 181 content: event.content(), 182 }; 183 listing::decode_observed(&fields, *event.id().as_bytes()) 184 .map(|v| Interpretation::Listing(Box::new(v))) 185 } 186 EventHeadCoordinate::Replaceable { .. } => { 187 if !event.tag_slices().is_empty() { 188 return Some(Interpretation::Invalid); 189 } 190 advertisement::decode(event.content().as_bytes(), event.created_at_u64()).map(|v| { 191 if observed_at >= v.valid_until().get() { 192 Interpretation::Expired 193 } else { 194 Interpretation::Capabilities(v) 195 } 196 }) 197 } 198 }; 199 Some(match result { 200 Ok(v) => v, 201 Err(CommandError::UnsupportedProfile) => Interpretation::Unsupported, 202 Err(_) => Interpretation::Invalid, 203 }) 204 } 205 }