lib

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

graph.rs (10254B)


      1 use super::super::{
      2     AttachmentInput, crypto::WorkspaceCrypto, installation::Records, snapshot::RetainedGraph,
      3 };
      4 use super::{
      5     MAX_ATTEMPTS,
      6     codec::{self, Fact},
      7 };
      8 use radroots_domain::{OperationId, PublicKey};
      9 use radroots_storage::command::{
     10     BoundSigningPlan, DeliveryAttempt, DeliveryIntent, OperationError, PublicationArtifact,
     11     SignedDmRelaySource, SigningTarget,
     12 };
     13 use sqlx::{Row, SqliteConnection};
     14 use std::collections::{BTreeMap, BTreeSet};
     15 
     16 #[cfg(test)]
     17 #[path = "graph_tests.rs"]
     18 mod tests;
     19 
     20 pub(in crate::workspace) struct Graph {
     21     pub attempts: Vec<DeliveryAttempt>,
     22     facts: Vec<Fact>,
     23     parts: usize,
     24     counters: BTreeMap<(Option<PublicKey>, String), BTreeSet<u8>>,
     25     routes: BTreeMap<Option<PublicKey>, BTreeSet<String>>,
     26 }
     27 fn bad<E>(_: E) -> OperationError {
     28     OperationError::RecoveryRequired
     29 }
     30 fn keys(row: &sqlx::sqlite::SqliteRow, index: usize) -> Result<[u8; 32], OperationError> {
     31     row.try_get::<Option<Vec<u8>>, _>(index)
     32         .map_err(bad)?
     33         .ok_or(OperationError::RecoveryRequired)?
     34         .try_into()
     35         .map_err(bad)
     36 }
     37 
     38 fn allowed_routes(
     39     bound: &BoundSigningPlan,
     40     target: SigningTarget,
     41 ) -> Result<BTreeMap<Option<PublicKey>, BTreeSet<String>>, OperationError> {
     42     let recipient = target.recipient();
     43     if target == SigningTarget::PublicEvent {
     44         let plan = bound
     45             .plan()
     46             .listing()
     47             .ok_or(OperationError::UnverifiedApproval)?;
     48         return Ok(BTreeMap::from([(
     49             None,
     50             plan.selected_targets()
     51                 .iter()
     52                 .map(|v| v.as_ref().to_owned())
     53                 .collect(),
     54         )]));
     55     }
     56     let mut result = BTreeMap::new();
     57     for route in bound
     58         .chat_plan()?
     59         .routes()
     60         .iter()
     61         .filter(|route| Some(route.participant()) == recipient)
     62     {
     63         let source = SignedDmRelaySource::verify(route.raw_json())?;
     64         source.validate_capture(route)?;
     65         let selected = route
     66             .selected_relays()
     67             .iter()
     68             .map(|target| target.as_ref().to_owned())
     69             .collect::<BTreeSet<_>>();
     70         if selected.is_empty() || result.insert(Some(route.participant()), selected).is_some() {
     71             return Err(OperationError::InvalidCommand);
     72         }
     73     }
     74     Ok(result)
     75 }
     76 impl Graph {
     77     pub(in crate::workspace) async fn read(
     78         connection: &mut SqliteConnection,
     79         selected: &AttachmentInput,
     80         operation: OperationId,
     81         original: &RetainedGraph,
     82         installed: &Records,
     83         public: &super::super::listing_installation::Records,
     84         crypto: &WorkspaceCrypto,
     85     ) -> Result<Self, OperationError> {
     86         let rows=sqlx::query(super::sql(connection,"SELECT CASE WHEN length(recipient)=32 OR (length(recipient)=1 AND hex(recipient)='00') THEN recipient END,CASE WHEN length(request_key)=32 THEN request_key END FROM chat_delivery_attempts WHERE workspace=? AND operation_id=? ORDER BY recipient,request_key LIMIT 385").await?)
     87             .bind(selected.workspace_id().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).fetch_all(&mut *connection).await.map_err(bad)?;
     88         if rows.len() > MAX_ATTEMPTS {
     89             return Err(OperationError::RecoveryRequired);
     90         }
     91         let routes = BTreeMap::new();
     92         let mut result = Self {
     93             attempts: Vec::with_capacity(rows.len()),
     94             facts: Vec::with_capacity(rows.len()),
     95             parts: 0,
     96             counters: BTreeMap::new(),
     97             routes,
     98         };
     99         let mut target_count = 0usize;
    100         let mut representations = BTreeMap::new();
    101         let mut policies = BTreeMap::new();
    102         for row in rows {
    103             let key_bytes = row
    104                 .try_get::<Option<Vec<u8>>, _>(0)
    105                 .map_err(bad)?
    106                 .ok_or(OperationError::RecoveryRequired)?;
    107             let target_scope = SigningTarget::from_key(&key_bytes).map_err(bad)?;
    108             let recipient = target_scope.recipient();
    109             let key = keys(&row, 1)?;
    110             if !result.routes.contains_key(&recipient) {
    111                 result
    112                     .authorize_routes(
    113                         original
    114                             .bound_plan()
    115                             .ok_or(OperationError::RecoveryRequired)?,
    116                         target_scope,
    117                     )
    118                     .map_err(|_| OperationError::RecoveryRequired)?;
    119             }
    120             let work = match target_scope {
    121                 SigningTarget::BusinessSeal(peer) => PublicationArtifact::Private(
    122                     installed
    123                         .work
    124                         .iter()
    125                         .find(|v| v.report.recipient() == peer)
    126                         .ok_or(OperationError::RecoveryRequired)?
    127                         .report,
    128                 ),
    129                 SigningTarget::PublicEvent => PublicationArtifact::Public(
    130                     public.work().ok_or(OperationError::RecoveryRequired)?,
    131                 ),
    132             };
    133             let value = codec::read(connection, work, key, crypto)
    134                 .await?
    135                 .ok_or(OperationError::RecoveryRequired)?;
    136             if target_scope == SigningTarget::PublicEvent
    137                 && original
    138                     .obtained_artifact(target_scope)
    139                     .is_none_or(|source| {
    140                         source.raw_json() != value.report.raw_json()
    141                             || source.digest() != work.evidence().digest()
    142                     })
    143             {
    144                 return Err(OperationError::RecoveryRequired);
    145             }
    146 
    147             if policies
    148                 .insert(
    149                     recipient,
    150                     *value.report.intent().publication_policy_digest(),
    151                 )
    152                 .is_some_and(|original| {
    153                     original != *value.report.intent().publication_policy_digest()
    154                 })
    155             {
    156                 return Err(OperationError::RecoveryRequired);
    157             }
    158             if representations
    159                 .insert(
    160                     value.report.intent().event_id(),
    161                     *value.report.envelope_digest(),
    162                 )
    163                 .is_some_and(|digest| digest != *value.report.envelope_digest())
    164             {
    165                 return Err(OperationError::RecoveryRequired);
    166             }
    167             target_count = target_count
    168                 .checked_add(value.report.intent().selection().len())
    169                 .filter(|n| *n <= MAX_ATTEMPTS)
    170                 .ok_or(OperationError::RecoveryRequired)?;
    171             result
    172                 .validate_routes(target_scope, value.report.intent())
    173                 .map_err(|_| OperationError::RecoveryRequired)?;
    174             for (target, ordinal) in value
    175                 .report
    176                 .intent()
    177                 .selected_targets()
    178                 .zip(value.report.target_ordinals())
    179             {
    180                 let slots = result
    181                     .counters
    182                     .entry((recipient, target.uri().as_str().to_owned()))
    183                     .or_default();
    184                 if !slots.insert(*ordinal) {
    185                     return Err(OperationError::RecoveryRequired);
    186                 }
    187             }
    188             result.parts += value.parts.len();
    189             result.facts.push(value.fact());
    190             result.attempts.push(value.report);
    191         }
    192         for slots in result.counters.values() {
    193             if slots.iter().copied().ne(1..=slots.len() as u8) {
    194                 return Err(OperationError::RecoveryRequired);
    195             }
    196         }
    197         Ok(result)
    198     }
    199     pub(super) fn validate_routes(
    200         &self,
    201         target: SigningTarget,
    202         intent: &DeliveryIntent,
    203     ) -> Result<(), OperationError> {
    204         let routes = self
    205             .routes
    206             .get(&target.recipient())
    207             .ok_or(OperationError::UnverifiedApproval)?;
    208         if intent.targets().targets().iter().any(|target| {
    209             !routes
    210                 .iter()
    211                 .any(|raw| matches!(target.matches_nostr_relay(raw), Ok(true)))
    212         }) {
    213             return Err(OperationError::UnverifiedApproval);
    214         }
    215         Ok(())
    216     }
    217     pub(super) fn authorize_routes(
    218         &mut self,
    219         bound: &BoundSigningPlan,
    220         target: SigningTarget,
    221     ) -> Result<(), OperationError> {
    222         let routes = allowed_routes(bound, target)?;
    223         if !routes.contains_key(&target.recipient()) {
    224             return Err(OperationError::UnverifiedApproval);
    225         }
    226         self.routes.extend(routes);
    227         Ok(())
    228     }
    229     pub(super) fn ordinals(
    230         &self,
    231         target: SigningTarget,
    232         intent: &DeliveryIntent,
    233     ) -> Result<Vec<u8>, OperationError> {
    234         self.validate_routes(target, intent)?;
    235         let target_scope = target.recipient();
    236         intent
    237             .selected_targets()
    238             .map(|target| {
    239                 let count = self
    240                     .counters
    241                     .get(&(target_scope, target.uri().as_str().to_owned()))
    242                     .map_or(0, BTreeSet::len);
    243                 if count >= 12 {
    244                     return Err(OperationError::DeliveryAttemptLimit);
    245                 }
    246                 Ok(count as u8 + 1)
    247             })
    248             .collect()
    249     }
    250     pub(in crate::workspace) async fn unchanged(
    251         &self,
    252         connection: &mut SqliteConnection,
    253         selected: &AttachmentInput,
    254         operation: OperationId,
    255     ) -> Result<(), OperationError> {
    256         let counts:(i64,i64)=sqlx::query_as(super::sql(connection,"SELECT (SELECT count(*) FROM (SELECT 1 FROM chat_delivery_attempts WHERE workspace=?1 AND operation_id=?2 LIMIT 385)),(SELECT count(*) FROM (SELECT 1 FROM chat_delivery_parts WHERE workspace=?1 AND operation_id=?2 LIMIT 9217))").await?)
    257             .bind(selected.workspace_id().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).fetch_one(&mut *connection).await.map_err(bad)?;
    258         if counts != (self.facts.len() as i64, self.parts as i64) {
    259             return Err(OperationError::RecoveryRequired);
    260         }
    261         for fact in &self.facts {
    262             fact.unchanged(connection).await?;
    263         }
    264         Ok(())
    265     }
    266 }