lib

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

source_original.rs (4060B)


      1 //! Original source evidence, correlated without treating a normalized key as
      2 //! admission. Only original bytes leave this bounded queue.
      3 use core::mem;
      4 use nostr_sdk::prelude::Event;
      5 use serde_json::value::RawValue;
      6 use sha2::{Digest as _, Sha256};
      7 use std::{collections::VecDeque, fmt};
      8 
      9 pub(crate) const MAX_PENDING_EVENTS: usize = 256;
     10 pub(crate) const MAX_PENDING_BYTES: usize = 4 * 1024 * 1024;
     11 pub(crate) const MAX_ORIGINAL_EVENT_BYTES: usize =
     12     radroots_protocol::profile::SIGNED_EVENT_MAX_BYTES;
     13 
     14 struct Original {
     15     owner: u64,
     16     scope: u64,
     17     correlation: [u8; 32],
     18     raw: Box<str>,
     19 }
     20 
     21 pub(crate) struct OriginalQueue {
     22     entries: VecDeque<Original>,
     23     payload_bytes: usize,
     24 }
     25 impl Default for OriginalQueue {
     26     fn default() -> Self {
     27         Self {
     28             entries: VecDeque::with_capacity(MAX_PENDING_EVENTS),
     29             payload_bytes: 0,
     30         }
     31     }
     32 }
     33 impl fmt::Debug for OriginalQueue {
     34     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     35         f.debug_struct("OriginalQueue")
     36             .field("events", &self.entries.len())
     37             .field("retained_bytes", &self.retained_bytes())
     38             .finish()
     39     }
     40 }
     41 impl OriginalQueue {
     42     pub(crate) fn retained_bytes(&self) -> usize {
     43         mem::size_of::<Self>()
     44             + self.entries.capacity() * mem::size_of::<Original>()
     45             + self.payload_bytes
     46     }
     47     pub(crate) fn insert(
     48         &mut self,
     49         owner: u64,
     50         scope: u64,
     51         correlation: [u8; 32],
     52         raw: &str,
     53     ) -> bool {
     54         if self.entries.len() == MAX_PENDING_EVENTS
     55             || raw.len() > MAX_ORIGINAL_EVENT_BYTES
     56             || raw.len() > MAX_PENDING_BYTES.saturating_sub(self.retained_bytes())
     57         {
     58             return false;
     59         }
     60         self.entries.push_back(Original {
     61             owner,
     62             scope,
     63             correlation,
     64             raw: Box::from(raw),
     65         });
     66         self.payload_bytes += raw.len();
     67         true
     68     }
     69     pub(crate) fn take(&mut self, scope: u64, correlation: [u8; 32]) -> Option<String> {
     70         let index = self
     71             .entries
     72             .iter()
     73             .position(|entry| entry.scope == scope && entry.correlation == correlation)?;
     74         let value = self.entries.remove(index)?;
     75         self.payload_bytes -= value.raw.len();
     76         Some(value.raw.into_string())
     77     }
     78     fn retain(&mut self, mut keep: impl FnMut(&Original) -> bool) {
     79         let mut removed = 0;
     80         self.entries.retain(|value| {
     81             if keep(value) {
     82                 true
     83             } else {
     84                 removed += value.raw.len();
     85                 false
     86             }
     87         });
     88         self.payload_bytes -= removed;
     89     }
     90     pub(crate) fn remove_scope(&mut self, scope: u64) {
     91         self.retain(|entry| entry.scope != scope);
     92     }
     93     pub(crate) fn remove_owner(&mut self, owner: u64) {
     94         self.retain(|entry| entry.owner != owner);
     95     }
     96 }
     97 
     98 /// The key is only correlation with the same already-pinned upstream decoder.
     99 /// It grants no identity/signature/profile authority and is never substituted
    100 /// for original bytes. Different raw spellings remain separate queued entries.
    101 pub(crate) fn correlation(event: &Event) -> [u8; 32] {
    102     Sha256::digest(event.as_json().as_bytes()).into()
    103 }
    104 
    105 pub(crate) fn frame(raw: &str) -> Option<(String, &RawValue)> {
    106     if raw.len() > crate::session_socket::MAX_WIRE_MESSAGE_BYTES {
    107         return None;
    108     }
    109     let [kind, subscription, event]: [&RawValue; 3] = serde_json::from_str(raw).ok()?;
    110     if kind.get().len() > 32 || subscription.get().len() > 6 * 256 + 2 {
    111         return None;
    112     }
    113     let kind: String = serde_json::from_str(kind.get()).ok()?;
    114     if kind != "EVENT" || event.get().len() > MAX_ORIGINAL_EVENT_BYTES {
    115         return None;
    116     }
    117     let subscription: String = serde_json::from_str(subscription.get()).ok()?;
    118     if subscription.is_empty() || subscription.len() > 256 {
    119         return None;
    120     }
    121     Some((subscription, event))
    122 }
    123 
    124 #[cfg(test)]
    125 #[path = "source_original_queue_tests.rs"]
    126 mod tests;