lib

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

listing.rs (8098B)


      1 //! Retained initial-coordinate decisions. Updates have separate expected-head
      2 //! commands; another initial publish never overwrites this creation decision.
      3 use super::{
      4     AttachmentInput,
      5     crypto::{ListingScope, WorkspaceCrypto},
      6 };
      7 use radroots_domain::{
      8     CommandDigest, OperationId, PublicKey, TransactionId, WorkspaceId, listing::ListingId,
      9 };
     10 use radroots_storage::command::{AdmissionRequest, OperationError, PreparedOperation};
     11 use serde::{Deserialize, Serialize};
     12 use sqlx::{Row, SqliteConnection};
     13 use zeroize::Zeroizing;
     14 
     15 pub(super) const CREATIONS: &str = "CREATE TABLE listing_creations (workspace BLOB NOT NULL, operation_id BLOB NOT NULL, author BLOB NOT NULL CHECK(length(author)=32), listing_id BLOB NOT NULL CHECK(length(listing_id)=16), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), PRIMARY KEY(workspace,operation_id), FOREIGN KEY(workspace,operation_id) REFERENCES operations(workspace,operation_id)) STRICT, WITHOUT ROWID";
     16 pub(super) const COORDINATE_INDEX: &str = "CREATE UNIQUE INDEX listing_coordinate_identity ON listing_creations(workspace,author,listing_id)";
     17 #[derive(Serialize, Deserialize, Eq, PartialEq)]
     18 #[serde(deny_unknown_fields)]
     19 struct DecisionRecord {
     20     version: u8,
     21     workspace: WorkspaceId,
     22     operation: OperationId,
     23     command: CommandDigest,
     24     author: PublicKey,
     25     listing: ListingId,
     26     transaction: TransactionId,
     27 }
     28 impl DecisionRecord {
     29     fn new(request: &AdmissionRequest, transaction: TransactionId) -> Result<Self, OperationError> {
     30         let command = request
     31             .command()
     32             .listing()
     33             .ok_or(OperationError::UnsupportedOperation)?;
     34         let context = request.command().context();
     35         Ok(Self {
     36             version: 1,
     37             workspace: context.workspace_id(),
     38             operation: context.operation_id(),
     39             command: request.command().digest(),
     40             author: context.actor().participant(),
     41             listing: command.input().id(),
     42             transaction,
     43         })
     44     }
     45     fn scope(&self) -> ListingScope {
     46         ListingScope::Decision {
     47             workspace: self.workspace,
     48             operation: self.operation,
     49         }
     50     }
     51 }
     52 pub(super) struct Creation {
     53     record: DecisionRecord,
     54     protected: Vec<u8>,
     55 }
     56 impl Creation {
     57     pub(super) async fn protect(
     58         request: &AdmissionRequest,
     59         transaction: TransactionId,
     60         crypto: &WorkspaceCrypto,
     61     ) -> Result<Option<Self>, OperationError> {
     62         if request.command().listing().is_none() {
     63             return Ok(None);
     64         }
     65         let record = DecisionRecord::new(request, transaction)?;
     66         let raw = Zeroizing::new(
     67             serde_json::to_vec(&record).map_err(|_| OperationError::InvalidCommand)?,
     68         );
     69         let protected = crypto.seal_listing(record.scope(), &raw).await?;
     70         Ok(Some(Self { record, protected }))
     71     }
     72     pub(super) async fn read(
     73         connection: &mut SqliteConnection,
     74         prepared: &PreparedOperation,
     75         crypto: &WorkspaceCrypto,
     76     ) -> Result<Option<Self>, OperationError> {
     77         if !current(connection).await? {
     78             return Ok(None);
     79         }
     80         let request = prepared.request();
     81         let context = request.command().context();
     82         let row=sqlx::query("SELECT CASE WHEN length(author)=32 THEN author END,CASE WHEN length(listing_id)=16 THEN listing_id END,CASE WHEN length(transaction_id)=32 THEN transaction_id END,CASE WHEN length(protected)>0 AND length(protected)<=262144 THEN protected END FROM listing_creations WHERE workspace=? AND operation_id=?")
     83             .bind(context.workspace_id().as_bytes().as_slice()).bind(context.operation_id().as_bytes().as_slice()).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?;
     84         let Some(row) = row else {
     85             return if request.command().listing().is_some() {
     86                 Err(OperationError::RecoveryRequired)
     87             } else {
     88                 Ok(None)
     89             };
     90         };
     91         let bytes = |i| -> Result<Vec<u8>, OperationError> {
     92             row.try_get::<Option<Vec<u8>>, _>(i)
     93                 .map_err(|_| OperationError::RecoveryRequired)?
     94                 .ok_or(OperationError::RecoveryRequired)
     95         };
     96         let expected = DecisionRecord::new(request, prepared.transaction_id())
     97             .map_err(|_| OperationError::RecoveryRequired)?;
     98         let protected = bytes(3)?;
     99         let raw = crypto.open_listing(expected.scope(), &protected).await?;
    100         let record: DecisionRecord = raw
    101             .expose_secret(|raw| serde_json::from_slice(raw))
    102             .map_err(|_| OperationError::RecoveryRequired)?;
    103         if record != expected
    104             || bytes(0)? != record.author.as_bytes()
    105             || bytes(1)? != record.listing.as_bytes()
    106             || bytes(2)? != record.transaction.as_bytes()
    107         {
    108             return Err(OperationError::RecoveryRequired);
    109         }
    110         Ok(Some(Self { record, protected }))
    111     }
    112     pub(super) async fn insert(
    113         &self,
    114         connection: &mut SqliteConnection,
    115     ) -> Result<(), OperationError> {
    116         let r = &self.record;
    117         // This check is inside the same BEGIN IMMEDIATE as T0 insertion. A
    118         // competing operation cannot reach its first signing claim.
    119         let exists:bool=sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM listing_creations WHERE workspace=? AND author=? AND listing_id=?)")
    120             .bind(r.workspace.as_bytes().as_slice()).bind(r.author.as_bytes().as_slice()).bind(r.listing.as_bytes().as_slice()).fetch_one(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?;
    121         if exists {
    122             return Err(OperationError::StaleState);
    123         }
    124         sqlx::query("INSERT INTO listing_creations(workspace,operation_id,author,listing_id,transaction_id,protected) VALUES(?,?,?,?,?,?)")
    125             .bind(r.workspace.as_bytes().as_slice()).bind(r.operation.as_bytes().as_slice()).bind(r.author.as_bytes().as_slice()).bind(r.listing.as_bytes().as_slice()).bind(r.transaction.as_bytes().as_slice()).bind(&self.protected).execute(connection).await.map_err(|_|OperationError::StorageFailure)?;
    126         Ok(())
    127     }
    128     pub(super) async fn unchanged(
    129         &self,
    130         connection: &mut SqliteConnection,
    131     ) -> Result<(), OperationError> {
    132         let r = &self.record;
    133         let count:i64=sqlx::query_scalar("SELECT count(*) FROM listing_creations WHERE workspace=? AND operation_id=? AND author=? AND listing_id=? AND transaction_id=? AND protected=?")
    134             .bind(r.workspace.as_bytes().as_slice()).bind(r.operation.as_bytes().as_slice()).bind(r.author.as_bytes().as_slice()).bind(r.listing.as_bytes().as_slice()).bind(r.transaction.as_bytes().as_slice()).bind(&self.protected).fetch_one(connection).await.map_err(|_|OperationError::RecoveryRequired)?;
    135         if count != 1 {
    136             return Err(OperationError::RecoveryRequired);
    137         }
    138         Ok(())
    139     }
    140 }
    141 pub(super) async fn current(connection: &mut SqliteConnection) -> Result<bool, OperationError> {
    142     let version: i64 = sqlx::query_scalar("PRAGMA user_version")
    143         .fetch_one(connection)
    144         .await
    145         .map_err(|_| OperationError::RecoveryRequired)?;
    146     match version {
    147         7..=9 => Ok(false),
    148         10 | 11 => Ok(true),
    149         _ => Err(OperationError::RecoveryRequired),
    150     }
    151 }
    152 pub(super) async fn absent(
    153     connection: &mut SqliteConnection,
    154     selected: &AttachmentInput,
    155     operation: OperationId,
    156 ) -> Result<(), OperationError> {
    157     if !current(connection).await? {
    158         return Ok(());
    159     }
    160     let found: bool = sqlx::query_scalar(
    161         "SELECT EXISTS(SELECT 1 FROM listing_creations WHERE workspace=? AND operation_id=?)",
    162     )
    163     .bind(selected.workspace_id().as_bytes().as_slice())
    164     .bind(operation.as_bytes().as_slice())
    165     .fetch_one(connection)
    166     .await
    167     .map_err(|_| OperationError::RecoveryRequired)?;
    168     if found {
    169         return Err(OperationError::RecoveryRequired);
    170     }
    171     Ok(())
    172 }