lib

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

source.rs (12062B)


      1 //! Protected original-source retention on the existing stock connection owner.
      2 //! Recognized profiles remain claims until causal and business admission.
      3 use super::*;
      4 use radroots_domain::{CheckpointDigest, EnvelopeEventId, RecordId, RumorEventId};
      5 use radroots_nostr::{commerce::RecordOpening, private_ingress::AuthenticatedCarrier};
      6 use radroots_storage::{
      7     command::OperationError, workspace::seller_stock::StockSourceCheckpointRef,
      8 };
      9 use sha2::{Digest, Sha256};
     10 use zeroize::Zeroizing;
     11 pub(in crate::workspace::stock) mod checkpoint;
     12 pub(in crate::workspace::stock) mod history;
     13 pub(in crate::workspace::stock) mod request;
     14 pub use history::StockHistorySnapshot;
     15 pub use request::StockRequestSnapshot;
     16 mod record;
     17 mod transaction;
     18 pub(in crate::workspace) use transaction::history as query_history;
     19 pub(in crate::workspace) use transaction::inspect_request;
     20 pub(in crate::workspace) use transaction::{query, retain};
     21 
     22 /// Authenticated carrier/profile disposition, without causal actionability.
     23 #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
     24 #[serde(rename_all = "snake_case")]
     25 pub enum StockSourceProfile {
     26     Known,
     27     Unsupported,
     28     Rejected,
     29 }
     30 /// Original immutable source prepared before store IO. Only the Nostr layer's
     31 /// authenticated opening types supply its evidence; metadata cannot mint it.
     32 pub struct StockSourceCapture {
     33     namespace: SellerAuthoritySelection,
     34     transaction: TransactionId,
     35     envelope: EnvelopeEventId,
     36     seal: EnvelopeEventId,
     37     rumor: RumorEventId,
     38     profile: StockSourceProfile,
     39     canonical: Option<(RecordId, Zeroizing<Vec<u8>>)>,
     40     pieces: [Zeroizing<Vec<u8>>; 3],
     41     manifest: Manifest,
     42 }
     43 #[derive(Clone, Copy, Eq, PartialEq, Serialize)]
     44 struct Piece {
     45     bytes: u32,
     46     digest: [u8; 32],
     47     parts: u8,
     48 }
     49 impl<'de> Deserialize<'de> for Piece {
     50     fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
     51         #[derive(Deserialize)]
     52         #[serde(deny_unknown_fields)]
     53         struct Wire {
     54             bytes: u32,
     55             digest: [u8; 32],
     56             parts: u8,
     57         }
     58         let wire: Wire = super::object(deserializer)?;
     59         Ok(Self {
     60             bytes: wire.bytes,
     61             digest: wire.digest,
     62             parts: wire.parts,
     63         })
     64     }
     65 }
     66 #[derive(Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
     67 #[serde(deny_unknown_fields)]
     68 struct Manifest {
     69     envelope: EnvelopeEventId,
     70     seal: EnvelopeEventId,
     71     rumor: RumorEventId,
     72     profile: StockSourceProfile,
     73     #[serde(deserialize_with = "super::required_nullable")]
     74     record: Option<RecordId>,
     75     #[serde(deserialize_with = "super::required_nullable")]
     76     canonical_digest: Option<[u8; 32]>,
     77     pieces: [Piece; 3],
     78 }
     79 impl StockSourceCapture {
     80     pub fn prepare(
     81         namespace: SellerAuthoritySelection,
     82         opening: &RecordOpening,
     83     ) -> Result<Self, WorkspaceError> {
     84         let (carrier, profile, canonical) = match opening {
     85             RecordOpening::Known(value) => {
     86                 let encoded =
     87                     radroots_protocol::commerce::EncodedRecord::capture(value.record().content())
     88                         .map_err(|_| WorkspaceError::InvalidInput)?;
     89                 (
     90                     value.carrier(),
     91                     StockSourceProfile::Known,
     92                     Some((
     93                         encoded.record_id(),
     94                         Zeroizing::new(encoded.protected_wire().to_vec()),
     95                     )),
     96                 )
     97             }
     98             RecordOpening::Unsupported(value) => {
     99                 (value.carrier(), StockSourceProfile::Unsupported, None)
    100             }
    101             RecordOpening::Rejected(value) => (value.carrier(), StockSourceProfile::Rejected, None),
    102         };
    103         if carrier.recipient() != namespace.participant() {
    104             return Err(WorkspaceError::WrongNamespace);
    105         }
    106         let pieces = source_pieces(carrier)?;
    107         let envelope = EnvelopeEventId::from_bytes(*carrier.envelope_id().as_bytes());
    108         let seal = EnvelopeEventId::from_bytes(*carrier.seal_id().as_bytes());
    109         let rumor = carrier.rumor().event_id();
    110         let descriptors = pieces.each_ref().map(|bytes| Piece {
    111             bytes: bytes.len() as u32,
    112             digest: Sha256::digest(bytes.as_slice()).into(),
    113             parts: bytes.len().div_ceil(16 * 1024) as u8,
    114         });
    115         let manifest = Manifest {
    116             envelope,
    117             seal,
    118             rumor,
    119             profile,
    120             record: canonical.as_ref().map(|value| value.0),
    121             canonical_digest: canonical
    122                 .as_ref()
    123                 .map(|value| Sha256::digest(value.1.as_slice()).into()),
    124             pieces: descriptors,
    125         };
    126         Ok(Self {
    127             namespace,
    128             transaction: TransactionId::from_bytes(super::super::random()?),
    129             envelope,
    130             seal,
    131             rumor,
    132             profile,
    133             canonical,
    134             pieces,
    135             manifest,
    136         })
    137     }
    138     pub const fn transaction_id(&self) -> TransactionId {
    139         self.transaction
    140     }
    141     pub const fn envelope_id(&self) -> EnvelopeEventId {
    142         self.envelope
    143     }
    144     pub const fn profile(&self) -> StockSourceProfile {
    145         self.profile
    146     }
    147     pub fn record_id(&self) -> Option<RecordId> {
    148         self.canonical.as_ref().map(|value| value.0)
    149     }
    150     pub(super) fn retained_copy(&self) -> Self {
    151         Self {
    152             namespace: self.namespace.clone(),
    153             transaction: self.transaction,
    154             envelope: self.envelope,
    155             seal: self.seal,
    156             rumor: self.rumor,
    157             profile: self.profile,
    158             canonical: self
    159                 .canonical
    160                 .as_ref()
    161                 .map(|(id, bytes)| (*id, Zeroizing::new(bytes.to_vec()))),
    162             pieces: self
    163                 .pieces
    164                 .each_ref()
    165                 .map(|value| Zeroizing::new(value.to_vec())),
    166             manifest: self.manifest,
    167         }
    168     }
    169 }
    170 fn source_pieces(
    171     carrier: &AuthenticatedCarrier,
    172 ) -> Result<[Zeroizing<Vec<u8>>; 3], WorkspaceError> {
    173     let texts = [
    174         carrier.protected_outer(),
    175         carrier.protected_seal(),
    176         carrier.protected_rumor(),
    177     ];
    178     if texts
    179         .iter()
    180         .any(|text| text.is_empty() || text.len() > 64 * 1024)
    181     {
    182         return Err(WorkspaceError::InvalidInput);
    183     }
    184     Ok(texts.map(|text| Zeroizing::new(text.as_bytes().to_vec())))
    185 }
    186 impl std::fmt::Debug for StockSourceCapture {
    187     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    188         f.write_str("StockSourceCapture(<redacted>)")
    189     }
    190 }
    191 /// Confirmed original storage identity. Profile recognition is not an order
    192 /// decision, source-completeness result or physical fact.
    193 #[derive(Clone, Debug, Eq, PartialEq)]
    194 pub struct StockSourceReceipt {
    195     transaction: TransactionId,
    196     envelope: EnvelopeEventId,
    197     record: Option<RecordId>,
    198     profile: StockSourceProfile,
    199     checkpoint: StockSourceCheckpointRef,
    200 }
    201 impl StockSourceReceipt {
    202     pub const fn transaction_id(&self) -> TransactionId {
    203         self.transaction
    204     }
    205     pub const fn envelope_id(&self) -> EnvelopeEventId {
    206         self.envelope
    207     }
    208     pub const fn record_id(&self) -> Option<RecordId> {
    209         self.record
    210     }
    211     pub const fn profile(&self) -> StockSourceProfile {
    212         self.profile
    213     }
    214     pub const fn checkpoint(&self) -> StockSourceCheckpointRef {
    215         self.checkpoint
    216     }
    217 }
    218 #[derive(Clone, Debug, Eq, PartialEq)]
    219 pub enum StockSourceOutcome {
    220     Committed(StockSourceReceipt),
    221     Unknown {
    222         transaction: TransactionId,
    223         envelope: EnvelopeEventId,
    224     },
    225 }
    226 /// Explicit private original bytes, returned only under current source access.
    227 /// This never reconstructs an authenticated-opening token or business status.
    228 pub struct StockSourceSnapshot {
    229     receipt: StockSourceReceipt,
    230     pieces: [Zeroizing<Vec<u8>>; 3],
    231     canonical: Option<Zeroizing<Vec<u8>>>,
    232 }
    233 impl StockSourceSnapshot {
    234     pub const fn receipt(&self) -> &StockSourceReceipt {
    235         &self.receipt
    236     }
    237     pub fn protected_outer(&self) -> &[u8] {
    238         &self.pieces[0]
    239     }
    240     pub fn protected_seal(&self) -> &[u8] {
    241         &self.pieces[1]
    242     }
    243     pub fn protected_rumor(&self) -> &[u8] {
    244         &self.pieces[2]
    245     }
    246     pub fn protected_canonical_record(&self) -> Option<&[u8]> {
    247         self.canonical.as_ref().map(|value| value.as_slice())
    248     }
    249 }
    250 impl std::fmt::Debug for StockSourceSnapshot {
    251     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    252         f.write_str("StockSourceSnapshot(<redacted>)")
    253     }
    254 }
    255 impl NativeWorkspace {
    256     /// Inspects original initial request, quote, source snapshots and deadlines
    257     /// under current administrative read access. This acquires no execution
    258     /// permission, pending order fence, signature or physical stock hold.
    259     pub async fn stock_order_request(
    260         &self,
    261         binding: WorkspaceBinding,
    262         inventory_minimum: radroots_storage::inventory::InventoryCheckpointRef,
    263         minimum: StockSourceCheckpointRef,
    264         listing_minimum: radroots_storage::workspace::seller_stock::StockListingCheckpointRef,
    265         request: RecordId,
    266         proof: &AttachmentProof,
    267     ) -> Result<StockRequestSnapshot, OperationError> {
    268         let proof = proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?;
    269         self.worker
    270             .stock_order_request(
    271                 binding,
    272                 inventory_minimum,
    273                 minimum,
    274                 listing_minimum,
    275                 request,
    276                 proof,
    277             )
    278             .await
    279     }
    280     /// Reads complete retained local causal coverage for one bilateral scope.
    281     /// Current administrator access is required. This neither authorizes a new
    282     /// request nor reports an installed agreement, global history or stock hold.
    283     /// Uninterpreted commerce from either party conservatively blocks that pair
    284     /// because its future header cannot yet be scoped. Ordinary chat remains a
    285     /// separate source and never becomes a structured record by interpretation.
    286     pub async fn stock_order_history(
    287         &self,
    288         binding: WorkspaceBinding,
    289         inventory_minimum: radroots_storage::inventory::InventoryCheckpointRef,
    290         minimum: StockSourceCheckpointRef,
    291         listing_minimum: radroots_storage::workspace::seller_stock::StockListingCheckpointRef,
    292         scope: radroots_domain::causal::CausalScope,
    293         proof: &AttachmentProof,
    294     ) -> Result<StockHistorySnapshot, OperationError> {
    295         let proof = proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?;
    296         self.worker
    297             .stock_order_history(
    298                 binding,
    299                 inventory_minimum,
    300                 minimum,
    301                 listing_minimum,
    302                 scope,
    303                 proof,
    304             )
    305             .await
    306     }
    307     /// Retains original authenticated evidence on the selected owner worker.
    308     /// Borrowed capture/proof remain available after error or observer loss.
    309     pub async fn retain_stock_source(
    310         &self,
    311         binding: WorkspaceBinding,
    312         minimum: StockSourceCheckpointRef,
    313         capture: &StockSourceCapture,
    314         proof: &AttachmentProof,
    315     ) -> Result<StockSourceOutcome, OperationError> {
    316         let proof = proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?;
    317         self.worker
    318             .retain_stock_source(binding, minimum, capture.retained_copy(), proof)
    319             .await
    320     }
    321     pub async fn stock_source(
    322         &self,
    323         binding: WorkspaceBinding,
    324         minimum: StockSourceCheckpointRef,
    325         envelope: EnvelopeEventId,
    326         proof: &AttachmentProof,
    327     ) -> Result<Option<StockSourceSnapshot>, OperationError> {
    328         let proof = proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?;
    329         self.worker
    330             .stock_source(binding, minimum, envelope, proof)
    331             .await
    332     }
    333 }