lib

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

checkpoint.rs (6741B)


      1 use super::*;
      2 use radroots_domain::{CheckpointDigest, Sequence};
      3 use radroots_storage::{
      4     command::OperationError, workspace::seller_stock::StockListingCheckpointRef,
      5 };
      6 use sha2::{Digest, Sha256};
      7 use sqlx::Row;
      8 
      9 #[derive(Clone, Copy, Eq, PartialEq)]
     10 pub(super) struct Identity {
     11     pub revision: Sequence,
     12     pub head: CheckpointDigest,
     13     pub protected: [u8; 32],
     14 }
     15 pub(super) enum Target {
     16     Minimum(StockListingCheckpointRef),
     17     Event(EnvelopeEventId, Option<Identity>),
     18     Coordinate(ListingCoordinate, Option<record::Head>),
     19 }
     20 pub(super) struct Proof {
     21     lower: u64,
     22     upper: u64,
     23     digest: [u8; 32],
     24 }
     25 fn hash() -> Sha256 {
     26     let mut h = Sha256::new();
     27     h.update(b"radroots.seller_stock.public_source_ancestry_snapshot.v1\0");
     28     h
     29 }
     30 fn hash_retained(hash: &mut Sha256, value: &record::RetainedHeader) -> Result<(), OperationError> {
     31     let header = &value.header;
     32     let listing = header.manifest.listing;
     33     hash.update(header.revision.get().to_be_bytes());
     34     hash.update(listing.event_id().as_bytes());
     35     hash.update(listing.coordinate().author().as_bytes());
     36     hash.update(listing.coordinate().d().as_bytes());
     37     hash.update(record::time(&header.manifest.created_at)?.to_be_bytes());
     38     hash.update(header.transaction.as_bytes());
     39     hash.update(
     40         header
     41             .head
     42             .ok_or(OperationError::RecoveryRequired)?
     43             .as_bytes(),
     44     );
     45     hash.update((value.protected.len() as u64).to_be_bytes());
     46     hash.update(&value.protected);
     47     Ok(())
     48 }
     49 impl record::RetainedHeader {
     50     pub(super) fn identity(&self) -> Result<Identity, OperationError> {
     51         Ok(Identity {
     52             revision: self.header.revision,
     53             head: self.header.head.ok_or(OperationError::RecoveryRequired)?,
     54             protected: Sha256::digest(&self.protected).into(),
     55         })
     56     }
     57 }
     58 impl Proof {
     59     /// Exact bounded-row witnesses are checked in the actual transaction,
     60     /// after every provider callback and before reporting authenticated state.
     61     pub async fn confirm(&self, connection: &mut SqliteConnection) -> Result<(), OperationError> {
     62         let mut hash = hash();
     63         for revision in (self.lower..=self.upper).rev() {
     64             let row=sqlx::query("SELECT event_id,listing_author,listing_d,created_at,transaction_id,chain_head,CASE WHEN length(protected) BETWEEN 1 AND 262144 THEN protected END FROM stock_public_events WHERE revision=?")
     65                 .bind(revision as i64).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?;
     66             hash.update(revision.to_be_bytes());
     67             for (column, length) in [(0, 32), (1, 32), (2, 16), (3, 8), (4, 32), (5, 32)] {
     68                 let value: Vec<u8> = row
     69                     .try_get(column)
     70                     .map_err(|_| OperationError::RecoveryRequired)?;
     71                 if value.len() != length {
     72                     return Err(OperationError::RecoveryRequired);
     73                 }
     74                 hash.update(value);
     75             }
     76             let protected: Vec<u8> = row
     77                 .try_get::<Option<Vec<u8>>, _>(6)
     78                 .map_err(|_| OperationError::RecoveryRequired)?
     79                 .ok_or(OperationError::RecoveryRequired)?;
     80             hash.update((protected.len() as u64).to_be_bytes());
     81             hash.update(protected);
     82         }
     83         if <[u8; 32]>::from(hash.finalize()) != self.digest {
     84             return Err(OperationError::RecoveryRequired);
     85         }
     86         Ok(())
     87     }
     88 }
     89 pub(super) async fn authenticate(
     90     connection: &mut SqliteConnection,
     91     input: &AttachmentInput,
     92     crypto: &WorkspaceCrypto,
     93     authority: &Authority,
     94     target: Target,
     95 ) -> Result<Proof, OperationError> {
     96     let current = authority
     97         .public_sources
     98         .ok_or(OperationError::UnsupportedOperation)?;
     99     if let Target::Minimum(minimum) = &target {
    100         if minimum.authority() != input.authority() {
    101             return Err(WorkspaceError::StaleAuthority.into());
    102         }
    103         if minimum.revision() > current.revision {
    104             return Err(WorkspaceError::StaleCheckpoint.into());
    105         }
    106     }
    107     let upper = current.revision.get();
    108     let mut previous = current.head;
    109     let mut hash = hash();
    110     for revision in (1..=upper).rev() {
    111         let id: Vec<u8> = sqlx::query_scalar(
    112             "SELECT event_id FROM stock_public_events WHERE revision=? AND length(event_id)=32",
    113         )
    114         .bind(revision as i64)
    115         .fetch_optional(&mut *connection)
    116         .await
    117         .map_err(|_| OperationError::RecoveryRequired)?
    118         .ok_or(OperationError::RecoveryRequired)?;
    119         let event = EnvelopeEventId::from_bytes(
    120             id.try_into()
    121                 .map_err(|_| OperationError::RecoveryRequired)?,
    122         );
    123         let original = record::read(connection, input, crypto, authority.input.grant_id(), event)
    124             .await?
    125             .ok_or(OperationError::RecoveryRequired)?;
    126         let header = &original.header;
    127         if header.revision.get() != revision || header.head != previous {
    128             return Err(OperationError::RecoveryRequired);
    129         }
    130         hash_retained(&mut hash, &original)?;
    131         let matched = match &target {
    132             Target::Minimum(minimum) if minimum.revision().get() == revision => {
    133                 if minimum.head() != header.head {
    134                     return Err(WorkspaceError::StaleCheckpoint.into());
    135                 }
    136                 true
    137             }
    138             Target::Event(wanted, expected) if *wanted == event => {
    139                 if *expected != Some(original.identity()?) {
    140                     return Err(OperationError::RecoveryRequired);
    141                 }
    142                 true
    143             }
    144             Target::Coordinate(coordinate, expected)
    145                 if *coordinate == header.manifest.listing.coordinate() =>
    146             {
    147                 if expected.as_ref() != Some(&header.after) {
    148                     return Err(OperationError::RecoveryRequired);
    149                 }
    150                 true
    151             }
    152             _ => false,
    153         };
    154         if matched {
    155             return Ok(Proof {
    156                 lower: revision,
    157                 upper,
    158                 digest: hash.finalize().into(),
    159             });
    160         }
    161         previous = header.previous;
    162     }
    163     if previous.is_some() {
    164         return Err(OperationError::RecoveryRequired);
    165     }
    166     match target {
    167         Target::Minimum(value) if value.revision().get() == 0 => {}
    168         Target::Event(_, None) | Target::Coordinate(_, None) => {}
    169         _ => return Err(OperationError::RecoveryRequired),
    170     }
    171     Ok(Proof {
    172         lower: 1,
    173         upper,
    174         digest: hash.finalize().into(),
    175     })
    176 }