lib

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

transaction.rs (21964B)


      1 use super::super::inventory::Turn;
      2 use super::*;
      3 use checkpoint::{Proof, Target};
      4 use radroots_storage::command::protected::same_binding;
      5 use record::{Header, RetainedHeader};
      6 
      7 struct Access {
      8     authority: Authority,
      9     record: StockRecord,
     10     root: Vec<u8>,
     11     grant: Vec<u8>,
     12     current: WorkspaceBinding,
     13     minimum: Proof,
     14 }
     15 async fn access(
     16     turn: &mut Turn<'_>,
     17     binding: &WorkspaceBinding,
     18     minimum: StockSourceCheckpointRef,
     19     proof: &AttachmentProof,
     20 ) -> Result<Access, OperationError> {
     21     if *turn.uncertain {
     22         return Err(OperationError::RecoveryRequired);
     23     }
     24     turn.namespace.validate()?;
     25     if !SellerAuthoritySelection::from_attachment(turn.selected).matches_attachment(binding.input())
     26     {
     27         return Err(OperationError::Unauthorized);
     28     }
     29     let (authority, record, root, grant) =
     30         super::super::read(turn.connection, binding.input(), turn.crypto).await?;
     31     if !(6..=20).contains(&authority.catalog) {
     32         return Err(OperationError::UnsupportedOperation);
     33     }
     34     let current = record.authenticate(binding.input(), proof, turn.clock.now()?)?;
     35     same_binding(binding, &current)?;
     36     if current.observed_at() < binding.observed_at() {
     37         return Err(WorkspaceError::Unavailable.into());
     38     }
     39     if current.scope() != WorkspaceScope::SellerStockOwner || !record.administrator() {
     40         return Err(OperationError::Unauthorized);
     41     }
     42     if authority.authorization != minimum.authorization() {
     43         return Err(WorkspaceError::StaleCheckpoint.into());
     44     }
     45     let witness = checkpoint::authenticate(
     46         turn.connection,
     47         turn.selected,
     48         turn.crypto,
     49         authority.sources.ok_or(OperationError::RecoveryRequired)?,
     50         Target::Minimum(minimum),
     51     )
     52     .await?;
     53     Ok(Access {
     54         authority,
     55         record,
     56         root,
     57         grant,
     58         current,
     59         minimum: witness,
     60     })
     61 }
     62 impl Access {
     63     async fn confirm(
     64         &self,
     65         connection: &mut SqliteConnection,
     66         namespace: &Namespace,
     67         clock: &dyn WorkspaceClock,
     68         proof: &AttachmentProof,
     69     ) -> Result<WorkspaceBinding, OperationError> {
     70         namespace.validate()?;
     71         super::super::unchanged(
     72             connection,
     73             self.current.input(),
     74             self.authority.catalog,
     75             &self.root,
     76             &self.grant,
     77         )
     78         .await?;
     79         grants::check_state(
     80             connection,
     81             self.authority
     82                 .authorization
     83                 .ok_or(OperationError::RecoveryRequired)?,
     84         )
     85         .await?;
     86         super::super::check_source_counts(
     87             connection,
     88             self.authority
     89                 .sources
     90                 .ok_or(OperationError::RecoveryRequired)?,
     91         )
     92         .await?;
     93         self.minimum.confirm(connection).await?;
     94         let current = self
     95             .record
     96             .authenticate(self.current.input(), proof, clock.now()?)?;
     97         same_binding(&self.current, &current)?;
     98         if current.observed_at() < self.current.observed_at() {
     99             return Err(WorkspaceError::Unavailable.into());
    100         }
    101         if !self.record.administrator() {
    102             return Err(OperationError::Unauthorized);
    103         }
    104         Ok(current)
    105     }
    106 }
    107 pub(in crate::workspace) async fn history(
    108     turn: &mut Turn<'_>,
    109     binding: WorkspaceBinding,
    110     inventory_minimum: radroots_storage::inventory::InventoryCheckpointRef,
    111     minimum: StockSourceCheckpointRef,
    112     listing_minimum: radroots_storage::workspace::seller_stock::StockListingCheckpointRef,
    113     scope: radroots_domain::causal::CausalScope,
    114     proof: AttachmentProof,
    115 ) -> Result<StockHistorySnapshot, OperationError> {
    116     let access = access(turn, &binding, minimum, &proof).await?;
    117     if !matches!(access.authority.catalog, 8..=20) {
    118         return Err(OperationError::UnsupportedOperation);
    119     }
    120     let prepared = Box::pin(super::history::prepare(
    121         turn.connection,
    122         turn.selected,
    123         turn.crypto,
    124         super::history::InventoryRead {
    125             binding: &access.current,
    126             authority: &access.authority,
    127             minimum: inventory_minimum,
    128         },
    129         scope,
    130         listing_minimum,
    131     ))
    132     .await?;
    133     let mut tx = turn
    134         .connection
    135         .begin_with("BEGIN IMMEDIATE")
    136         .await
    137         .map_err(|_| OperationError::StorageFailure)?;
    138     let checked: Result<_, OperationError> = async {
    139         // The complete cryptographic/row witness may span a large local
    140         // history. Check usable current permission/time after that work.
    141         prepared.confirm(&mut tx).await?;
    142         let current = access
    143             .confirm(&mut tx, turn.namespace, turn.clock, &proof)
    144             .await?;
    145         Ok(current.observed_at())
    146     }
    147     .await;
    148     if tx.rollback().await.is_err() {
    149         *turn.uncertain = true;
    150         return Err(OperationError::RecoveryRequired);
    151     }
    152     let observed_at = checked?;
    153     let private = access
    154         .authority
    155         .sources
    156         .ok_or(OperationError::RecoveryRequired)?;
    157     let public = access
    158         .authority
    159         .public_sources
    160         .ok_or(OperationError::RecoveryRequired)?;
    161     Ok(StockHistorySnapshot {
    162         inventory: prepared.inventory,
    163         scope,records:prepared.records.len(),analysis:prepared.analysis,checkpoint:prepared.checkpoint,observed_at,
    164         sources:StockSourceCheckpointRef::from_host_metadata(turn.selected.authority(),private.revision,private.head)?.with_optional_authorization(access.authority.authorization),
    165         listings:radroots_storage::workspace::seller_stock::StockListingCheckpointRef::from_host_metadata(turn.selected.authority(),public.revision,public.head)?.with_optional_authorization(access.authority.authorization),
    166     })
    167 }
    168 pub(in crate::workspace) async fn inspect_request(
    169     turn: &mut Turn<'_>,
    170     binding: WorkspaceBinding,
    171     inventory_minimum: radroots_storage::inventory::InventoryCheckpointRef,
    172     minimum: StockSourceCheckpointRef,
    173     listing_minimum: radroots_storage::workspace::seller_stock::StockListingCheckpointRef,
    174     selected: RecordId,
    175     proof: AttachmentProof,
    176 ) -> Result<StockRequestSnapshot, OperationError> {
    177     let access = access(turn, &binding, minimum, &proof).await?;
    178     if !matches!(access.authority.catalog, 8..=20) {
    179         return Err(OperationError::UnsupportedOperation);
    180     }
    181     let prepared = Box::pin(super::request::prepare(
    182         turn.connection,
    183         turn.selected,
    184         turn.crypto,
    185         super::history::InventoryRead {
    186             binding: &access.current,
    187             authority: &access.authority,
    188             minimum: inventory_minimum,
    189         },
    190         selected,
    191         listing_minimum,
    192         access.current.observed_at(),
    193     ))
    194     .await;
    195     let mut tx = turn
    196         .connection
    197         .begin_with("BEGIN IMMEDIATE")
    198         .await
    199         .map_err(|_| OperationError::StorageFailure)?;
    200     let checked: Result<_, OperationError> = async {
    201         let witnessed = match &prepared {
    202             Ok(value) => value.confirm(&mut tx).await,
    203             Err(_) => Ok(()),
    204         };
    205         // Do not disclose even a detailed source denial under expired/revoked
    206         // access. All provider work and row witnesses precede this final check.
    207         let current = access
    208             .confirm(&mut tx, turn.namespace, turn.clock, &proof)
    209             .await?;
    210         witnessed?;
    211         if let Ok(value) = &prepared {
    212             value.validate_at(current.observed_at())?;
    213         }
    214         Ok(current.observed_at())
    215     }
    216     .await;
    217     if tx.rollback().await.is_err() {
    218         *turn.uncertain = true;
    219         return Err(OperationError::RecoveryRequired);
    220     }
    221     let observed_at = checked?;
    222     let prepared = prepared?;
    223     let private = access
    224         .authority
    225         .sources
    226         .ok_or(OperationError::RecoveryRequired)?;
    227     let public = access
    228         .authority
    229         .public_sources
    230         .ok_or(OperationError::RecoveryRequired)?;
    231     Ok(StockRequestSnapshot {
    232         inventory: prepared.history.inventory,
    233         scope:prepared.scope,request:prepared.authorization,terms:Box::new(prepared.terms()?.clone()),digest:prepared.digest,
    234         expires:prepared.expires,quote:prepared.quote,checkpoint:prepared.history.checkpoint.clone().ok_or(OperationError::RecoveryRequired)?,observed_at,
    235         sources:StockSourceCheckpointRef::from_host_metadata(turn.selected.authority(),private.revision,private.head)?.with_optional_authorization(access.authority.authorization),
    236         listings:radroots_storage::workspace::seller_stock::StockListingCheckpointRef::from_host_metadata(turn.selected.authority(),public.revision,public.head)?.with_optional_authorization(access.authority.authorization),
    237     })
    238 }
    239 struct Observation {
    240     ancestry: Proof,
    241     header: Option<RetainedHeader>,
    242     canonical: Option<(RecordId, Option<Vec<u8>>)>,
    243     parts: Option<[u8; 32]>,
    244     record_ancestry: Option<Proof>,
    245 }
    246 impl Observation {
    247     async fn confirm(
    248         &self,
    249         connection: &mut SqliteConnection,
    250         envelope: EnvelopeEventId,
    251     ) -> Result<(), OperationError> {
    252         self.ancestry.confirm(connection).await?;
    253         if let Some(proof) = &self.record_ancestry {
    254             proof.confirm(connection).await?;
    255         }
    256         let count: i64 = if let Some(header) = &self.header {
    257             sqlx::query_scalar(
    258                 "SELECT count(*) FROM stock_source_evidence WHERE envelope_id=? AND protected=?",
    259             )
    260             .bind(envelope.as_bytes().as_slice())
    261             .bind(&header.protected)
    262             .fetch_one(&mut *connection)
    263             .await
    264             .map_err(|_| OperationError::RecoveryRequired)?
    265         } else {
    266             sqlx::query_scalar("SELECT count(*) FROM stock_source_evidence WHERE envelope_id=?")
    267                 .bind(envelope.as_bytes().as_slice())
    268                 .fetch_one(&mut *connection)
    269                 .await
    270                 .map_err(|_| OperationError::RecoveryRequired)?
    271         };
    272         if count != i64::from(self.header.is_some()) {
    273             return Err(OperationError::RecoveryRequired);
    274         }
    275         if let Some((id, protected)) = &self.canonical {
    276             let count: i64 = if let Some(protected) = protected {
    277                 sqlx::query_scalar(
    278                     "SELECT count(*) FROM stock_source_records WHERE record_id=? AND protected=?",
    279                 )
    280                 .bind(id.as_bytes().as_slice())
    281                 .bind(protected)
    282                 .fetch_one(&mut *connection)
    283                 .await
    284                 .map_err(|_| OperationError::RecoveryRequired)?
    285             } else {
    286                 sqlx::query_scalar("SELECT count(*) FROM stock_source_records WHERE record_id=?")
    287                     .bind(id.as_bytes().as_slice())
    288                     .fetch_one(&mut *connection)
    289                     .await
    290                     .map_err(|_| OperationError::RecoveryRequired)?
    291             };
    292             if count != i64::from(protected.is_some()) {
    293                 return Err(OperationError::RecoveryRequired);
    294             }
    295         }
    296         if let (Some(header), Some(expected)) = (&self.header, self.parts) {
    297             record::confirm_parts(connection, &header.header, expected).await?;
    298         }
    299         Ok(())
    300     }
    301 }
    302 async fn observed(
    303     turn: &mut Turn<'_>,
    304     authority: &Authority,
    305     envelope: EnvelopeEventId,
    306 ) -> Result<Observation, OperationError> {
    307     let retained = record::read(turn.connection, turn.selected, turn.crypto, envelope).await?;
    308     let expected = retained.as_ref().map(|value| {
    309         (
    310             value.header.revision,
    311             value.header.head,
    312             Sha256::digest(&value.protected).into(),
    313         )
    314     });
    315     let ancestry = checkpoint::authenticate(
    316         turn.connection,
    317         turn.selected,
    318         turn.crypto,
    319         authority.sources.ok_or(OperationError::RecoveryRequired)?,
    320         Target::Envelope(envelope, expected),
    321     )
    322     .await?;
    323     Ok(Observation {
    324         ancestry,
    325         header: retained,
    326         canonical: None,
    327         parts: None,
    328         record_ancestry: None,
    329     })
    330 }
    331 async fn load(
    332     turn: &mut Turn<'_>,
    333     observation: &mut Observation,
    334 ) -> Result<StockSourceSnapshot, OperationError> {
    335     let retained = observation
    336         .header
    337         .as_ref()
    338         .ok_or(OperationError::RecoveryRequired)?;
    339     let (pieces, witness) = record::pieces(
    340         turn.connection,
    341         turn.selected,
    342         turn.crypto,
    343         &retained.header,
    344     )
    345     .await?;
    346     observation.parts = Some(witness);
    347     let canonical = if let Some(id) = retained.header.manifest.record {
    348         let (clear, protected) = record::canonical(turn.connection, turn.selected, turn.crypto, id)
    349             .await?
    350             .ok_or(OperationError::RecoveryRequired)?;
    351         let digest: [u8; 32] = Sha256::digest(clear.as_slice()).into();
    352         if Some(digest) != retained.header.manifest.canonical_digest {
    353             return Err(OperationError::RecoveryRequired);
    354         }
    355         observation.canonical = Some((id, Some(protected)));
    356         Some(clear)
    357     } else {
    358         None
    359     };
    360     Ok(StockSourceSnapshot {
    361         receipt: retained.header.receipt(turn.selected)?,
    362         pieces,
    363         canonical,
    364     })
    365 }
    366 async fn confirm_read(
    367     turn: &mut Turn<'_>,
    368     access: &Access,
    369     proof: &AttachmentProof,
    370     envelope: EnvelopeEventId,
    371     observed: &Observation,
    372 ) -> Result<(), OperationError> {
    373     let mut tx = turn
    374         .connection
    375         .begin_with("BEGIN IMMEDIATE")
    376         .await
    377         .map_err(|_| OperationError::StorageFailure)?;
    378     let checked: Result<(), OperationError> = async {
    379         access
    380             .confirm(&mut tx, turn.namespace, turn.clock, proof)
    381             .await?;
    382         observed.confirm(&mut tx, envelope).await?;
    383         turn.namespace.validate()?;
    384         Ok(())
    385     }
    386     .await;
    387     if tx.rollback().await.is_err() {
    388         *turn.uncertain = true;
    389         return Err(OperationError::RecoveryRequired);
    390     }
    391     checked
    392 }
    393 pub(in crate::workspace) async fn query(
    394     turn: &mut Turn<'_>,
    395     binding: WorkspaceBinding,
    396     minimum: StockSourceCheckpointRef,
    397     envelope: EnvelopeEventId,
    398     proof: AttachmentProof,
    399 ) -> Result<Option<StockSourceSnapshot>, OperationError> {
    400     let access = access(turn, &binding, minimum, &proof).await?;
    401     let mut observation = observed(turn, &access.authority, envelope).await?;
    402     let result = if observation.header.is_some() {
    403         Some(load(turn, &mut observation).await?)
    404     } else {
    405         None
    406     };
    407     confirm_read(turn, &access, &proof, envelope, &observation).await?;
    408     Ok(result)
    409 }
    410 pub(in crate::workspace) async fn retain(
    411     turn: &mut Turn<'_>,
    412     binding: WorkspaceBinding,
    413     minimum: StockSourceCheckpointRef,
    414     capture: StockSourceCapture,
    415     proof: AttachmentProof,
    416 ) -> Result<StockSourceOutcome, OperationError> {
    417     let access = access(turn, &binding, minimum, &proof).await?;
    418     if capture.namespace != SellerAuthoritySelection::from_attachment(turn.selected) {
    419         return Err(OperationError::Unauthorized);
    420     }
    421     let mut observation = observed(turn, &access.authority, capture.envelope).await?;
    422     if let Some(prior) = &observation.header {
    423         if prior.header.manifest != capture.manifest {
    424             return Err(OperationError::IdempotencyConflict);
    425         }
    426         let snapshot = load(turn, &mut observation).await?;
    427         confirm_read(turn, &access, &proof, capture.envelope, &observation).await?;
    428         return Ok(StockSourceOutcome::Committed(snapshot.receipt));
    429     }
    430     let before = access
    431         .authority
    432         .sources
    433         .ok_or(OperationError::RecoveryRequired)?;
    434     let mut protected_record = None;
    435     let mut new_record = false;
    436     if let Some((id, canonical)) = &capture.canonical {
    437         let prior = record::canonical(turn.connection, turn.selected, turn.crypto, *id).await?;
    438         let digest = prior
    439             .as_ref()
    440             .map(|value| Sha256::digest(value.0.as_slice()).into());
    441         observation.record_ancestry = Some(
    442             checkpoint::authenticate(
    443                 turn.connection,
    444                 turn.selected,
    445                 turn.crypto,
    446                 before,
    447                 Target::Record(*id, digest),
    448             )
    449             .await?,
    450         );
    451         if let Some((clear, _)) = &prior
    452             && clear.as_slice() != canonical.as_slice()
    453         {
    454             return Err(OperationError::InvalidEvidence);
    455         }
    456         new_record = prior.is_none();
    457         if new_record {
    458             protected_record = Some((
    459                 *id,
    460                 turn.crypto
    461                     .seal_stock_record(turn.selected, "source_record", id.as_bytes(), canonical)
    462                     .await?,
    463             ));
    464         }
    465         observation.canonical = Some((*id, prior.map(|value| value.1)));
    466     }
    467     let revision = Sequence::new(
    468         before
    469             .revision
    470             .get()
    471             .checked_add(1)
    472             .ok_or(WorkspaceError::Capacity)?,
    473     )
    474     .map_err(|_| WorkspaceError::Capacity)?;
    475     let mut header = Header {
    476         version: 1,
    477         manifest: capture.manifest,
    478         transaction: capture.transaction,
    479         revision,
    480         previous: before.head,
    481         head: CheckpointDigest::from_bytes([0; 32]),
    482         grant: access.current.input().grant_id(),
    483         principal: access.current.principal_id().into(),
    484         authorization: access
    485             .authority
    486             .authorization
    487             .ok_or(OperationError::RecoveryRequired)?,
    488     };
    489     header.head = record::head(turn.selected, &header)?;
    490     let mut parts = Vec::new();
    491     for (role, clear) in capture.pieces.iter().enumerate() {
    492         for (part, clear) in clear.chunks(16 * 1024).enumerate() {
    493             let protected = turn
    494                 .crypto
    495                 .seal_stock_record(
    496                     turn.selected,
    497                     "source_part",
    498                     &record::part_id(capture.envelope, role as u8, part as u8),
    499                     clear,
    500                 )
    501                 .await?;
    502             parts.push((role as u8, part as u8, protected));
    503         }
    504     }
    505     let protected_header = turn
    506         .crypto
    507         .seal_stock_record(
    508             turn.selected,
    509             "source_evidence",
    510             capture.envelope.as_bytes(),
    511             &record::encode(&header)?,
    512         )
    513         .await?;
    514     let mut next = access.authority.clone();
    515     next.sources = Some(SourceCheckpoint {
    516         revision,
    517         head: Some(header.head),
    518         records: Sequence::new(
    519             before
    520                 .records
    521                 .get()
    522                 .checked_add(u64::from(new_record))
    523                 .ok_or(WorkspaceError::Capacity)?,
    524         )
    525         .map_err(|_| WorkspaceError::Capacity)?,
    526         parts: Sequence::new(
    527             before
    528                 .parts
    529                 .get()
    530                 .checked_add(parts.len() as u64)
    531                 .ok_or(WorkspaceError::Capacity)?,
    532         )
    533         .map_err(|_| WorkspaceError::Capacity)?,
    534     });
    535     let root = turn
    536         .crypto
    537         .seal_stock_root(turn.selected, next.catalog, &next.encode()?)
    538         .await?;
    539     let receipt = header.receipt(turn.selected)?;
    540     turn.namespace.validate()?;
    541     let mut tx = turn
    542         .connection
    543         .begin_with("BEGIN IMMEDIATE")
    544         .await
    545         .map_err(|_| OperationError::StorageFailure)?;
    546     let changed: Result<(), OperationError> = async {
    547         access.confirm(&mut tx, turn.namespace, turn.clock, &proof).await?;
    548         observation.confirm(&mut tx, capture.envelope).await?;
    549         if let Some((id, protected)) = protected_record {
    550             sqlx::query("INSERT INTO stock_source_records(record_id,protected) VALUES(?,?)")
    551                 .bind(id.as_bytes().as_slice())
    552                 .bind(protected)
    553                 .execute(&mut *tx)
    554                 .await
    555                 .map_err(|_| OperationError::StorageFailure)?;
    556         }
    557         sqlx::query("INSERT INTO stock_source_evidence(envelope_id,record_id,transaction_id,revision,chain_head,protected) VALUES(?,?,?,?,?,?)")
    558             .bind(capture.envelope.as_bytes().as_slice())
    559             .bind(header.manifest.record.map(|id| id.as_bytes().to_vec()))
    560             .bind(capture.transaction.as_bytes().as_slice())
    561             .bind(revision.get() as i64)
    562             .bind(header.head.as_bytes().as_slice())
    563             .bind(protected_header)
    564             .execute(&mut *tx)
    565             .await
    566             .map_err(|_| OperationError::StorageFailure)?;
    567         for (role, part, protected) in parts {
    568             sqlx::query("INSERT INTO stock_source_parts(envelope_id,role,part,protected) VALUES(?,?,?,?)")
    569                 .bind(capture.envelope.as_bytes().as_slice())
    570                 .bind(i64::from(role))
    571                 .bind(i64::from(part))
    572                 .bind(protected)
    573                 .execute(&mut *tx)
    574                 .await
    575                 .map_err(|_| OperationError::StorageFailure)?;
    576         }
    577         let changed = sqlx::query("UPDATE stock_authority SET protected=? WHERE singleton=1 AND protected=?")
    578             .bind(root)
    579             .bind(&access.root)
    580             .execute(&mut *tx)
    581             .await
    582             .map_err(|_| OperationError::StorageFailure)?;
    583         if changed.rows_affected() != 1 {
    584             return Err(OperationError::RecoveryRequired);
    585         }
    586         turn.namespace.validate()?;
    587         Ok(())
    588     }.await;
    589     let unknown = || StockSourceOutcome::Unknown {
    590         transaction: capture.transaction,
    591         envelope: capture.envelope,
    592     };
    593     if let Err(error) = changed {
    594         if tx.rollback().await.is_err() {
    595             *turn.uncertain = true;
    596             return Ok(unknown());
    597         }
    598         return Err(error);
    599     }
    600     if tx.commit().await.is_err() {
    601         *turn.uncertain = true;
    602         return Ok(unknown());
    603     }
    604     Ok(StockSourceOutcome::Committed(receipt))
    605 }