lib

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

changes.rs (9060B)


      1 //! Original-allocation residual transitions; the SQL projection has identities
      2 //! only. Quantities stay in the authenticated installation journal body.
      3 use super::*;
      4 use radroots_domain::{
      5     AgreementLineId, PublicKey,
      6     stock::{ObligationBacking, StockTicks},
      7 };
      8 
      9 #[derive(Clone, Eq, PartialEq, Serialize, Deserialize)]
     10 #[serde(deny_unknown_fields)]
     11 pub(in crate::workspace::stock) struct Release {
     12     pub acceptance: OperationId,
     13     pub installation: OperationId,
     14     pub line: AgreementLineId,
     15     pub pool: PoolId,
     16     pub before: ObligationBacking,
     17     pub after: ObligationBacking,
     18     pub backed: StockTicks,
     19     pub deficit: StockTicks,
     20 }
     21 impl Release {
     22     pub fn validate(&self) -> Result<StockTicks, OperationError> {
     23         let quantity = self
     24             .backed
     25             .checked_add(self.deficit)
     26             .map_err(|_| OperationError::RecoveryRequired)?;
     27         if self.before.release_residual(self.backed, self.deficit).ok() != Some(self.after) {
     28             return Err(OperationError::RecoveryRequired);
     29         }
     30         Ok(quantity)
     31     }
     32     fn key(&self) -> ChangeIdentity {
     33         ChangeIdentity {
     34             acceptance: self.acceptance,
     35             line: self.line,
     36             pool: self.pool,
     37             installation: self.installation,
     38         }
     39     }
     40 }
     41 #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
     42 struct ChangeIdentity {
     43     acceptance: OperationId,
     44     line: AgreementLineId,
     45     pool: PoolId,
     46     installation: OperationId,
     47 }
     48 fn index_digest(values: &mut [ChangeIdentity]) -> Result<[u8; 32], OperationError> {
     49     if values.len() > 64 {
     50         return Err(OperationError::RecoveryRequired);
     51     }
     52     values.sort();
     53     if values.windows(2).any(|pair| {
     54         pair[0].acceptance == pair[1].acceptance
     55             && pair[0].line == pair[1].line
     56             && pair[0].pool == pair[1].pool
     57     }) {
     58         return Err(OperationError::RecoveryRequired);
     59     }
     60     let mut hash = Sha256::new();
     61     hash.update(b"radroots.seller_stock.obligation_changes_projection.v1\0");
     62     hash.update((values.len() as u64).to_be_bytes());
     63     for value in values {
     64         hash.update(value.acceptance.as_bytes());
     65         hash.update(value.line.as_bytes());
     66         hash.update(value.pool.as_bytes());
     67         hash.update(value.installation.as_bytes());
     68     }
     69     Ok(hash.finalize().into())
     70 }
     71 pub(super) fn digest(changes: &[Release]) -> Result<[u8; 32], OperationError> {
     72     for change in changes {
     73         change.validate()?;
     74     }
     75     index_digest(&mut changes.iter().map(Release::key).collect::<Vec<_>>())
     76 }
     77 pub(super) async fn raw_digest(
     78     connection: &mut SqliteConnection,
     79     actor: PublicKey,
     80     entry: OperationId,
     81 ) -> Result<[u8; 32], OperationError> {
     82     let rows=sqlx::query("SELECT acceptance_id,line_id,pool_id,installation_id FROM stock_obligation_changes WHERE actor=? AND operation_id=? ORDER BY acceptance_id,line_id,pool_id LIMIT 65")
     83         .bind(actor.as_bytes().as_slice()).bind(entry.as_bytes().as_slice()).fetch_all(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?;
     84     let mut values = Vec::with_capacity(rows.len());
     85     for row in rows {
     86         let field = |index| -> Result<[u8; 32], OperationError> {
     87             row.try_get::<Vec<u8>, _>(index)
     88                 .map_err(|_| OperationError::RecoveryRequired)?
     89                 .try_into()
     90                 .map_err(|_| OperationError::RecoveryRequired)
     91         };
     92         values.push(ChangeIdentity {
     93             acceptance: OperationId::from_bytes(field(0)?),
     94             line: AgreementLineId::from_bytes(field(1)?),
     95             pool: PoolId::from_bytes(field(2)?),
     96             installation: OperationId::from_bytes(field(3)?),
     97         });
     98     }
     99     index_digest(&mut values)
    100 }
    101 pub(super) async fn insert(
    102     connection: &mut SqliteConnection,
    103     actor: PublicKey,
    104     entry: OperationId,
    105     changes: &[Release],
    106 ) -> Result<(), OperationError> {
    107     digest(changes)?;
    108     for change in changes {
    109         sqlx::query("INSERT INTO stock_obligation_changes(actor,operation_id,acceptance_id,installation_id,line_id,pool_id) VALUES(?,?,?,?,?,?)")
    110             .bind(actor.as_bytes().as_slice()).bind(entry.as_bytes().as_slice()).bind(change.acceptance.as_bytes().as_slice())
    111             .bind(change.installation.as_bytes().as_slice()).bind(change.line.as_bytes().as_slice()).bind(change.pool.as_bytes().as_slice())
    112             .execute(&mut *connection).await.map_err(|_|OperationError::StorageFailure)?;
    113     }
    114     Ok(())
    115 }
    116 
    117 /// Replays each protected loss/release in original revision order. Summing
    118 /// historical losses alone would resurrect released obligations or deficits.
    119 pub(super) async fn current(
    120     connection: &mut SqliteConnection,
    121     input: &AttachmentInput,
    122     crypto: &WorkspaceCrypto,
    123     original: &super::allocations::InstalledAllocation,
    124     before_revision: u64,
    125 ) -> Result<ObligationBacking, OperationError> {
    126     let mut state = ObligationBacking::new(
    127         original.allocation.ticks(),
    128         original.allocation.ticks(),
    129         StockTicks::ZERO,
    130     )
    131     .map_err(|_| OperationError::RecoveryRequired)?;
    132     let mut cursor = 0_u64;
    133     loop {
    134         let row=sqlx::query("WITH c AS (SELECT actor,operation_id,acceptance_id,installation_id,line_id,pool_id,0 AS kind FROM stock_deficits UNION ALL SELECT actor,operation_id,acceptance_id,installation_id,line_id,pool_id,1 AS kind FROM stock_obligation_changes) SELECT o.revision,o.operation_id,c.kind FROM c JOIN stock_operations o ON o.actor=c.actor AND o.operation_id=c.operation_id WHERE c.actor=? AND c.acceptance_id=? AND c.installation_id=? AND c.line_id=? AND c.pool_id=? AND o.revision>? AND o.revision<? ORDER BY o.revision LIMIT 1")
    135             .bind(input.participant().as_bytes().as_slice()).bind(original.acceptance.as_bytes().as_slice()).bind(original.installation.as_bytes().as_slice())
    136             .bind(original.allocation.line_id().as_bytes().as_slice()).bind(original.allocation.pool_id().as_bytes().as_slice())
    137             .bind(cursor as i64).bind(before_revision as i64).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?;
    138         let Some(row) = row else {
    139             return Ok(state);
    140         };
    141         let revision: i64 = row
    142             .try_get(0)
    143             .map_err(|_| OperationError::RecoveryRequired)?;
    144         let operation = OperationId::from_bytes(
    145             row.try_get::<Vec<u8>, _>(1)
    146                 .map_err(|_| OperationError::RecoveryRequired)?
    147                 .try_into()
    148                 .map_err(|_| OperationError::RecoveryRequired)?,
    149         );
    150         let kind: i64 = row
    151             .try_get(2)
    152             .map_err(|_| OperationError::RecoveryRequired)?;
    153         if revision <= 0 {
    154             return Err(OperationError::RecoveryRequired);
    155         }
    156         cursor = revision as u64;
    157         let frame = super::super::ledger::read(connection, input, crypto, operation)
    158             .await?
    159             .ok_or(OperationError::RecoveryRequired)?;
    160         if frame.header.revision.get() != cursor
    161             || frame.header.actor.participant() != input.participant()
    162         {
    163             return Err(OperationError::RecoveryRequired);
    164         }
    165         if kind == 0 {
    166             let (request, data) = decode_operation(&frame.body, 20)?;
    167             if frame.header.family != super::super::ledger::Family::Inventory
    168                 || request.command().digest() != frame.header.digest
    169                 || data.revision != frame.header.revision
    170                 || data.head != frame.header.head
    171                 || data.pool.id() != original.allocation.pool_id()
    172             {
    173                 return Err(OperationError::RecoveryRequired);
    174             }
    175             let mut matches = data.losses.iter().filter(|loss| {
    176                 loss.acceptance == original.acceptance
    177                     && loss.installation == original.installation
    178                     && loss.line == original.allocation.line_id()
    179             });
    180             let change = matches.next().ok_or(OperationError::RecoveryRequired)?;
    181             if matches.next().is_some() || change.before != state {
    182                 return Err(OperationError::RecoveryRequired);
    183             }
    184             change.quantity()?;
    185             state = change.after;
    186         } else if kind == 1 {
    187             let changes = super::installation::read_changes(&frame)?;
    188             let mut matches = changes.iter().filter(|change| {
    189                 change.acceptance == original.acceptance
    190                     && change.installation == original.installation
    191                     && change.line == original.allocation.line_id()
    192                     && change.pool == original.allocation.pool_id()
    193             });
    194             let change = matches.next().ok_or(OperationError::RecoveryRequired)?;
    195             if matches.next().is_some() || change.before != state {
    196                 return Err(OperationError::RecoveryRequired);
    197             }
    198             change.validate()?;
    199             state = change.after;
    200         } else {
    201             return Err(OperationError::RecoveryRequired);
    202         }
    203     }
    204 }