lib

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

public_source.rs (9829B)


      1 //! Original authenticated public listing observations. Local observation is not
      2 //! a global head, supported profile, current business permission or stock hold.
      3 use super::*;
      4 use radroots_domain::{
      5     EnvelopeEventId,
      6     listing::{ListingCoordinate, ListingId, ListingRevision},
      7 };
      8 use radroots_event::envelope::event_head::EventHeadCoordinate;
      9 use radroots_nostr::public_ingress::ObservedHead;
     10 use zeroize::Zeroizing;
     11 pub(in crate::workspace::stock) mod admission;
     12 mod checkpoint;
     13 pub(in crate::workspace::stock) mod history;
     14 mod record;
     15 #[cfg(test)]
     16 mod tests;
     17 mod transaction;
     18 pub(in crate::workspace) use transaction::{Lookup, query, retain};
     19 
     20 /// Captured before store IO, using only authenticated Nostr observation
     21 /// evidence. Namespace comparison here is data validation, not store access.
     22 pub struct StockListingCapture {
     23     namespace: SellerAuthoritySelection,
     24     transaction: TransactionId,
     25     listing: ListingRevision,
     26     created_at: u64,
     27     raw: Zeroizing<Vec<u8>>,
     28 }
     29 impl StockListingCapture {
     30     pub fn prepare(
     31         namespace: SellerAuthoritySelection,
     32         observed: &ObservedHead,
     33     ) -> Result<Self, WorkspaceError> {
     34         let selected = observed.selected().ok_or(WorkspaceError::InvalidInput)?;
     35         let EventHeadCoordinate::Addressable {
     36             kind,
     37             pubkey,
     38             d_tag,
     39         } = &selected.coordinate
     40         else {
     41             return Err(WorkspaceError::InvalidInput);
     42         };
     43         if *kind != radroots_protocol::listing::LISTING_KIND {
     44             return Err(WorkspaceError::InvalidInput);
     45         }
     46         let discriminator: ListingId = d_tag.parse().map_err(|_| WorkspaceError::InvalidInput)?;
     47         let coordinate = ListingCoordinate::new(*pubkey, discriminator);
     48         if coordinate.author() != namespace.participant() {
     49             return Err(WorkspaceError::WrongNamespace);
     50         }
     51         let raw = observed
     52             .raw_json()
     53             .ok_or(WorkspaceError::InvalidInput)?
     54             .as_bytes();
     55         if raw.is_empty() || raw.len() > 64 * 1024 {
     56             return Err(WorkspaceError::Capacity);
     57         }
     58         Ok(Self {
     59             namespace,
     60             transaction: TransactionId::from_bytes(super::super::random()?),
     61             listing: ListingRevision::new(
     62                 coordinate,
     63                 EnvelopeEventId::from_bytes(*selected.event_id.as_bytes()),
     64             ),
     65             // NIP01 permits the full unsigned timestamp range. Preserve an
     66             // authentic far-future head; clock readiness is evaluated separately.
     67             created_at: selected.created_at,
     68             raw: Zeroizing::new(raw.to_vec()),
     69         })
     70     }
     71     pub const fn transaction_id(&self) -> TransactionId {
     72         self.transaction
     73     }
     74     pub const fn listing_revision(&self) -> ListingRevision {
     75         self.listing
     76     }
     77     pub(super) fn retained_copy(&self) -> Self {
     78         Self {
     79             namespace: self.namespace.clone(),
     80             transaction: self.transaction,
     81             listing: self.listing,
     82             created_at: self.created_at,
     83             raw: Zeroizing::new(self.raw.to_vec()),
     84         }
     85     }
     86 }
     87 impl std::fmt::Debug for StockListingCapture {
     88     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     89         f.write_str("StockListingCapture(<authenticated observation>)")
     90     }
     91 }
     92 
     93 /// Original persisted observation. Selection is described at its original
     94 /// retention, not promised for a later lookup or globally across relays.
     95 #[derive(Clone, Debug, Eq, PartialEq)]
     96 pub struct StockListingReceipt {
     97     transaction: TransactionId,
     98     listing: ListingRevision,
     99     selected_at_retention: bool,
    100     checkpoint: radroots_storage::workspace::seller_stock::StockListingCheckpointRef,
    101 }
    102 impl StockListingReceipt {
    103     pub const fn transaction_id(&self) -> TransactionId {
    104         self.transaction
    105     }
    106     pub const fn listing_revision(&self) -> ListingRevision {
    107         self.listing
    108     }
    109     pub const fn selected_at_retention(&self) -> bool {
    110         self.selected_at_retention
    111     }
    112     pub const fn checkpoint(
    113         &self,
    114     ) -> radroots_storage::workspace::seller_stock::StockListingCheckpointRef {
    115         self.checkpoint
    116     }
    117 }
    118 #[derive(Clone, Debug, Eq, PartialEq)]
    119 pub enum StockListingOutcome {
    120     Committed(Box<StockListingReceipt>),
    121     Unknown {
    122         transaction: TransactionId,
    123         listing: ListingRevision,
    124     },
    125 }
    126 /// Original public evidence plus the independently acknowledged scope in which
    127 /// its current-observed flag was checked. Neither grants business permission.
    128 pub struct StockListingSnapshot {
    129     receipt: StockListingReceipt,
    130     selection_checkpoint: radroots_storage::workspace::seller_stock::StockListingCheckpointRef,
    131     observed_at: radroots_domain::UnixSeconds,
    132     current: bool,
    133     raw: Zeroizing<String>,
    134 }
    135 impl StockListingSnapshot {
    136     pub const fn receipt(&self) -> &StockListingReceipt {
    137         &self.receipt
    138     }
    139     pub const fn selection_checkpoint(
    140         &self,
    141     ) -> radroots_storage::workspace::seller_stock::StockListingCheckpointRef {
    142         self.selection_checkpoint
    143     }
    144     pub const fn observed_at(&self) -> radroots_domain::UnixSeconds {
    145         self.observed_at
    146     }
    147     pub const fn is_current_observed(&self) -> bool {
    148         self.current
    149     }
    150     pub fn raw_json(&self) -> &str {
    151         &self.raw
    152     }
    153     /// Pure profile/time classification at the captured read observation. A
    154     /// historical or unsupported result cannot be substituted as a live offer.
    155     pub fn interpret_at_observation(
    156         &self,
    157     ) -> Result<
    158         radroots_nostr::public_ingress::Interpretation,
    159         radroots_storage::command::OperationError,
    160     > {
    161         use radroots_storage::command::OperationError;
    162         let coordinate = self.receipt.listing.coordinate();
    163         let mut observed = ObservedHead::listing(coordinate.author(), &coordinate.d().to_string())
    164             .map_err(|_| OperationError::RecoveryRequired)?;
    165         observed
    166             .observe(&self.raw)
    167             .map_err(|_| OperationError::RecoveryRequired)?;
    168         observed
    169             .interpret(
    170                 radroots_protocol::advertisement::UnixSeconds::new(self.observed_at.get())
    171                     .map_err(|_| WorkspaceError::Unavailable)?,
    172             )
    173             .ok_or(OperationError::RecoveryRequired)
    174     }
    175 }
    176 impl std::fmt::Debug for StockListingSnapshot {
    177     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    178         f.write_str("StockListingSnapshot(<original observation>)")
    179     }
    180 }
    181 
    182 impl NativeWorkspace {
    183     /// Retains original signed listing evidence under current administrative
    184     /// access. The borrowed capture keeps its original recovery identity if an
    185     /// observer is lost; this does not publish or admit a business command.
    186     pub async fn retain_stock_listing(
    187         &self,
    188         binding: WorkspaceBinding,
    189         minimum: radroots_storage::workspace::seller_stock::StockListingCheckpointRef,
    190         capture: &StockListingCapture,
    191         proof: &AttachmentProof,
    192     ) -> Result<StockListingOutcome, radroots_storage::command::OperationError> {
    193         let proof = proof.with_secret(|secret| AttachmentProof::from_protected_input(secret))?;
    194         self.worker
    195             .retain_stock_listing(binding, minimum, capture.retained_copy(), proof)
    196             .await
    197     }
    198     /// Reads one exact retained revision, including historical observations.
    199     pub async fn stock_listing_source(
    200         &self,
    201         binding: WorkspaceBinding,
    202         minimum: radroots_storage::workspace::seller_stock::StockListingCheckpointRef,
    203         revision: ListingRevision,
    204         proof: &AttachmentProof,
    205     ) -> Result<Option<StockListingSnapshot>, radroots_storage::command::OperationError> {
    206         let proof = proof.with_secret(|secret| AttachmentProof::from_protected_input(secret))?;
    207         self.worker
    208             .stock_listing(binding, minimum, Lookup::Revision(revision), proof)
    209             .await
    210     }
    211     /// Reads the protected current observed head without older-profile fallback
    212     /// or a claim of global relay completeness or business actionability.
    213     pub async fn stock_listing_head(
    214         &self,
    215         binding: WorkspaceBinding,
    216         minimum: radroots_storage::workspace::seller_stock::StockListingCheckpointRef,
    217         coordinate: ListingCoordinate,
    218         proof: &AttachmentProof,
    219     ) -> Result<Option<StockListingSnapshot>, radroots_storage::command::OperationError> {
    220         let proof = proof.with_secret(|secret| AttachmentProof::from_protected_input(secret))?;
    221         self.worker
    222             .stock_listing(binding, minimum, Lookup::Coordinate(coordinate), proof)
    223             .await
    224     }
    225 }
    226 
    227 pub(super) async fn counts(
    228     connection: &mut SqliteConnection,
    229     current: PublicSourceCheckpoint,
    230 ) -> Result<(), WorkspaceError> {
    231     use sqlx::Row;
    232     current.validate()?;
    233     let row=sqlx::query("SELECT count(*),coalesce(max(revision),0),coalesce(sum(CASE WHEN revision=? AND chain_head=? THEN 1 ELSE 0 END),0),(SELECT count(*) FROM stock_public_heads),(SELECT count(*) FROM stock_public_parts) FROM stock_public_events")
    234         .bind(current.revision.get() as i64).bind(current.head.map(|head|head.as_bytes().to_vec()))
    235         .fetch_one(connection).await.map_err(|_|WorkspaceError::RecoveryRequired)?;
    236     for (column, expected) in [
    237         (0, current.events.get() as i64),
    238         (1, current.revision.get() as i64),
    239         (2, i64::from(current.head.is_some())),
    240         (3, current.heads.get() as i64),
    241         (4, current.parts.get() as i64),
    242     ] {
    243         if row
    244             .try_get::<i64, _>(column)
    245             .map_err(|_| WorkspaceError::RecoveryRequired)?
    246             != expected
    247         {
    248             return Err(WorkspaceError::RecoveryRequired);
    249         }
    250     }
    251     Ok(())
    252 }