lib

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

replay_admission.rs (15478B)


      1 //! A confirmed current-catalog replay admission precedes every returned permit.
      2 use super::super::inventory::Turn;
      3 use super::*;
      4 use radroots_domain::CheckpointDigest;
      5 use radroots_storage::workspace::seller_stock::StockAuthorizationRef;
      6 use zeroize::Zeroizing;
      7 
      8 const MAGIC: &[u8; 8] = b"RDSTRP1\0";
      9 const BYTES: usize = 184;
     10 
     11 /// Authenticated first admission of possible exact replay, never a dispatch or
     12 /// nonissuance certificate. Later current authorization does not erase this fact.
     13 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
     14 pub struct StockReplayAdmissionReceipt {
     15     attempt: CommitAttempt,
     16     claim: SigningAttemptId,
     17     recipient: PublicKey,
     18     observed_at: UnixSeconds,
     19     authorization: StockAuthorizationRef,
     20     checkpoint: InventoryCheckpointRef,
     21 }
     22 impl StockReplayAdmissionReceipt {
     23     /// Original operation and confirmed first admission transaction.
     24     pub const fn attempt(&self) -> CommitAttempt {
     25         self.attempt
     26     }
     27     /// Exact original durable signing claim.
     28     pub const fn signing_attempt_id(&self) -> SigningAttemptId {
     29         self.claim
     30     }
     31     /// Original recipient, independently of other recipient observations.
     32     pub const fn recipient(&self) -> PublicKey {
     33         self.recipient
     34     }
     35     /// First checked authorization observation, captured before protection IO.
     36     /// Permission and the original window are rechecked before actual commit.
     37     pub const fn observed_at(&self) -> UnixSeconds {
     38         self.observed_at
     39     }
     40     /// Authenticated grant-set observation captured by the first admission.
     41     pub const fn authorization(&self) -> StockAuthorizationRef {
     42         self.authorization
     43     }
     44     /// Protected first admission checkpoint; metadata supplies no permission.
     45     pub const fn checkpoint(&self) -> InventoryCheckpointRef {
     46         self.checkpoint
     47     }
     48 }
     49 fn body(
     50     original: &claim::codec::Retained,
     51     at: UnixSeconds,
     52     auth: StockAuthorizationRef,
     53 ) -> Zeroizing<Vec<u8>> {
     54     let mut bytes = Zeroizing::new(Vec::with_capacity(BYTES));
     55     bytes.extend_from_slice(MAGIC);
     56     bytes.extend_from_slice(original.frame.header.operation.as_bytes());
     57     bytes.extend_from_slice(original.frame.header.transaction.as_bytes());
     58     bytes.extend_from_slice(original.frame.header.head.as_bytes());
     59     bytes.extend_from_slice(original.report.binding().digest());
     60     bytes.extend_from_slice(&at.get().to_be_bytes());
     61     bytes.extend_from_slice(&auth.generation().get().to_be_bytes());
     62     bytes.extend_from_slice(auth.digest().as_bytes());
     63     bytes
     64 }
     65 fn head(header: &ledger::Header, bytes: &[u8]) -> CheckpointDigest {
     66     let mut hash = Sha256::new();
     67     hash.update(b"radroots.seller_stock.replay_admission_chain.v1\0");
     68     hash.update(header.namespace.workspace_id().as_bytes());
     69     hash.update(header.namespace.authority().executor_id().as_bytes());
     70     hash.update(
     71         header
     72             .namespace
     73             .authority()
     74             .generation()
     75             .get()
     76             .to_be_bytes(),
     77     );
     78     hash.update(header.namespace.route_digest().as_bytes());
     79     hash.update(header.actor.participant().as_bytes());
     80     hash.update(
     81         header
     82             .actor
     83             .grant_id()
     84             .map(|v| *v.as_bytes())
     85             .unwrap_or([0; 32]),
     86     );
     87     hash.update(header.operation.as_bytes());
     88     hash.update(header.digest.as_bytes());
     89     hash.update(header.transaction.as_bytes());
     90     hash.update(header.revision.get().to_be_bytes());
     91     hash.update([u8::from(header.previous.is_some())]);
     92     hash.update(header.previous.map(|v| *v.as_bytes()).unwrap_or([0; 32]));
     93     hash.update(Sha256::digest(bytes));
     94     CheckpointDigest::from_bytes(hash.finalize().into())
     95 }
     96 fn receipt(
     97     input: &AttachmentInput,
     98     header: &ledger::Header,
     99     original: &claim::codec::Retained,
    100     at: UnixSeconds,
    101     auth: StockAuthorizationRef,
    102 ) -> Result<StockReplayAdmissionReceipt, OperationError> {
    103     Ok(StockReplayAdmissionReceipt {
    104         attempt: CommitAttempt::new(
    105             input.workspace_id(),
    106             original.report.attempt().operation_id(),
    107             header.digest,
    108             Some(header.transaction),
    109         ),
    110         claim: original.report.attempt_id(),
    111         recipient: original.report.recipient(),
    112         observed_at: at,
    113         authorization: auth,
    114         checkpoint: InventoryCheckpointRef::from_host_metadata(
    115             input.authority(),
    116             header.revision,
    117             Some(header.head),
    118         )?
    119         .with_authorization(auth),
    120     })
    121 }
    122 pub(in crate::workspace::stock) struct Retained {
    123     frame: ledger::Retained,
    124     value: StockReplayAdmissionReceipt,
    125     projection: Projection,
    126 }
    127 impl Retained {
    128     pub(in crate::workspace::stock) fn receipt(&self) -> StockReplayAdmissionReceipt {
    129         self.value
    130     }
    131     pub(in crate::workspace::stock) async fn confirm(
    132         &self,
    133         connection: &mut SqliteConnection,
    134     ) -> Result<(), OperationError> {
    135         ledger::confirm_header(connection, &self.frame.header, &self.frame.protected).await?;
    136         ledger::confirm_parts(
    137             connection,
    138             self.frame.header.actor,
    139             self.frame.header.operation,
    140             self.frame.parts_witness,
    141             self.frame.header.parts,
    142         )
    143         .await?;
    144         self.projection
    145             .confirm(
    146                 connection,
    147                 self.frame.header.actor.participant(),
    148                 self.frame.header.operation,
    149             )
    150             .await?;
    151         let count: i64 = sqlx::query_scalar(
    152             "SELECT count(*) FROM stock_movements WHERE actor=? AND operation_id=?",
    153         )
    154         .bind(self.frame.header.actor.participant().as_bytes().as_slice())
    155         .bind(self.frame.header.operation.as_bytes().as_slice())
    156         .fetch_one(connection)
    157         .await
    158         .map_err(|_| OperationError::RecoveryRequired)?;
    159         if count != 0 {
    160             return Err(OperationError::RecoveryRequired);
    161         }
    162         Ok(())
    163     }
    164     pub(in crate::workspace::stock) fn into_history(self) -> ledger::HistoryEntry {
    165         ledger::HistoryEntry {
    166             deficit: None,
    167             delivery: None,
    168             envelope: None,
    169             aborted: None,
    170             preparation: None,
    171             local_record: None,
    172             installation: None,
    173             header: self.frame.header,
    174             protected: self.frame.protected,
    175             parts_witness: self.frame.parts_witness,
    176             pools: vec![],
    177             mapping: None,
    178             movements: vec![],
    179             signing: Some(self.projection),
    180         }
    181     }
    182 }
    183 pub(in crate::workspace::stock) async fn read_entry(
    184     connection: &mut SqliteConnection,
    185     input: &AttachmentInput,
    186     crypto: &WorkspaceCrypto,
    187     entry: OperationId,
    188 ) -> Result<Option<Retained>, OperationError> {
    189     let Some(frame) = ledger::read(connection, input, crypto, entry).await? else {
    190         return Ok(None);
    191     };
    192     let raw = frame.body.as_slice();
    193     if frame.header.family != ledger::Family::ReplayAdmission
    194         || raw.len() != BYTES
    195         || &raw[..8] != MAGIC
    196     {
    197         return Err(OperationError::RecoveryRequired);
    198     }
    199     let array = |start, end| {
    200         raw[start..end]
    201             .try_into()
    202             .map_err(|_| OperationError::RecoveryRequired)
    203     };
    204     let original = Box::pin(claim::read_entry(
    205         connection,
    206         input,
    207         crypto,
    208         OperationId::from_bytes(array(8, 40)?),
    209     ))
    210     .await?
    211     .ok_or(OperationError::RecoveryRequired)?;
    212     let at = UnixSeconds::new(u64::from_be_bytes(
    213         raw[136..144]
    214             .try_into()
    215             .map_err(|_| OperationError::RecoveryRequired)?,
    216     ))
    217     .map_err(|_| OperationError::RecoveryRequired)?;
    218     let authorization = StockAuthorizationRef::from_host_metadata(
    219         Sequence::new(u64::from_be_bytes(
    220             raw[144..152]
    221                 .try_into()
    222                 .map_err(|_| OperationError::RecoveryRequired)?,
    223         ))
    224         .map_err(|_| OperationError::RecoveryRequired)?,
    225         CheckpointDigest::from_bytes(array(152, 184)?),
    226     )?;
    227     if original.frame.header.transaction != TransactionId::from_bytes(array(40, 72)?)
    228         || original.frame.header.head != CheckpointDigest::from_bytes(array(72, 104)?)
    229         || original.report.binding().digest() != &array(104, 136)?
    230         || frame.header.actor.participant() != original.frame.header.actor.participant()
    231         || frame.header.related_operation != original.frame.header.related_operation
    232         || frame.header.order != original.frame.header.order
    233         || frame.header.digest != original.frame.header.digest
    234         || frame.header.revision <= original.frame.header.revision
    235         || original.report.bound_plan().plan().replay()
    236             != radroots_protocol::intent::SigningReplay::LocalReplaySafe
    237         || at < original.report.claimed_at()
    238         || at < original.report.bound_plan().bound_at()
    239         || at
    240             >= original
    241                 .report
    242                 .bound_plan()
    243                 .preparation()
    244                 .first_issue_deadline()
    245         || head(&frame.header, raw) != frame.header.head
    246     {
    247         return Err(OperationError::RecoveryRequired);
    248     }
    249     let projection = Projection {
    250         operation: original.report.attempt().operation_id(),
    251         recipient: original.report.recipient(),
    252         kind: ProjectionKind::ReplayAdmission,
    253     };
    254     let value = receipt(input, &frame.header, &original, at, authorization)?;
    255     let retained = Retained {
    256         frame,
    257         value,
    258         projection,
    259     };
    260     retained.confirm(connection).await?;
    261     Ok(Some(retained))
    262 }
    263 pub(in crate::workspace::stock) async fn lookup(
    264     connection: &mut SqliteConnection,
    265     input: &AttachmentInput,
    266     crypto: &WorkspaceCrypto,
    267     operation: OperationId,
    268     recipient: PublicKey,
    269 ) -> Result<Option<Retained>, OperationError> {
    270     let entry:Option<Vec<u8>>=sqlx::query_scalar("SELECT CASE WHEN length(entry_id)=32 THEN entry_id END FROM stock_replay_admissions WHERE actor=? AND operation_id=? AND recipient=?")
    271         .bind(input.participant().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(recipient.as_bytes().as_slice()).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?;
    272     let Some(entry) = entry else { return Ok(None) };
    273     let retained = Box::pin(read_entry(
    274         connection,
    275         input,
    276         crypto,
    277         OperationId::from_bytes(
    278             entry
    279                 .try_into()
    280                 .map_err(|_| OperationError::RecoveryRequired)?,
    281         ),
    282     ))
    283     .await?
    284     .ok_or(OperationError::RecoveryRequired)?;
    285     if retained.value.attempt.operation_id() != operation || retained.value.recipient != recipient {
    286         return Err(OperationError::RecoveryRequired);
    287     }
    288     Ok(Some(retained))
    289 }
    290 pub(super) struct Pending {
    291     old: Option<Retained>,
    292     frame: Option<ledger::Prepared>,
    293     root: Option<Vec<u8>>,
    294     value: StockReplayAdmissionReceipt,
    295 }
    296 impl Pending {
    297     pub(super) fn receipt(&self) -> StockReplayAdmissionReceipt {
    298         self.value
    299     }
    300     /// Called only after current authorization and all original witnesses have
    301     /// been rechecked in the same transaction, with no provider IO inside it.
    302     pub(super) async fn apply(
    303         &self,
    304         connection: &mut SqliteConnection,
    305         input: &AttachmentInput,
    306         auth: &signing_plan::Authorized,
    307     ) -> Result<(), OperationError> {
    308         if let Some(old) = &self.old {
    309             old.confirm(connection).await?;
    310         }
    311         if let Some(frame) = &self.frame {
    312             frame.insert_record(connection).await?;
    313             sqlx::query("INSERT INTO stock_replay_admissions(actor,operation_id,recipient,entry_id) VALUES(?,?,?,?)")
    314                 .bind(input.participant().as_bytes().as_slice()).bind(self.value.attempt.operation_id().as_bytes().as_slice()).bind(self.value.recipient.as_bytes().as_slice()).bind(frame.header.operation.as_bytes().as_slice())
    315                 .execute(&mut *connection).await.map_err(|_|OperationError::StorageFailure)?;
    316             let changed = sqlx::query(
    317                 "UPDATE stock_authority SET protected=? WHERE singleton=1 AND protected=?",
    318             )
    319             .bind(self.root.as_ref().ok_or(OperationError::RecoveryRequired)?)
    320             .bind(&auth.access.root)
    321             .execute(connection)
    322             .await
    323             .map_err(|_| OperationError::StorageFailure)?;
    324             if changed.rows_affected() != 1 {
    325                 return Err(OperationError::RecoveryRequired);
    326             }
    327         }
    328         Ok(())
    329     }
    330     pub(super) fn writes(&self) -> bool {
    331         self.frame.is_some()
    332     }
    333 }
    334 pub(super) async fn prepare(
    335     turn: &mut Turn<'_>,
    336     auth: &signing_plan::Authorized,
    337     original: &claim::codec::Retained,
    338     at: UnixSeconds,
    339 ) -> Result<Pending, OperationError> {
    340     let old = Box::pin(lookup(
    341         turn.connection,
    342         turn.selected,
    343         turn.crypto,
    344         original.report.attempt().operation_id(),
    345         original.report.recipient(),
    346     ))
    347     .await?;
    348     if let Some(old) = old {
    349         if at < old.value.observed_at {
    350             return Err(WorkspaceError::Unavailable.into());
    351         }
    352         if old.value.claim != original.report.attempt_id() {
    353             return Err(OperationError::RecoveryRequired);
    354         }
    355         let value = old.value;
    356         return Ok(Pending {
    357             old: Some(old),
    358             frame: None,
    359             root: None,
    360             value,
    361         });
    362     }
    363     let before = auth
    364         .access
    365         .authority
    366         .inventory
    367         .ok_or(OperationError::RecoveryRequired)?;
    368     let authorization = auth
    369         .access
    370         .authority
    371         .authorization
    372         .ok_or(OperationError::RecoveryRequired)?;
    373     let revision = Sequence::new(
    374         before
    375             .revision
    376             .get()
    377             .checked_add(1)
    378             .ok_or(WorkspaceError::Capacity)?,
    379     )
    380     .map_err(|_| WorkspaceError::Capacity)?;
    381     let bytes = body(original, at, authorization);
    382     let mut header = ledger::Header {
    383         version: 5,
    384         family: ledger::Family::ReplayAdmission,
    385         namespace: SellerAuthoritySelection::from_attachment(turn.selected),
    386         actor: auth.access.current.actor(),
    387         operation: OperationId::from_bytes(super::super::super::random()?),
    388         digest: original.report.attempt().command_digest(),
    389         transaction: TransactionId::from_bytes(super::super::super::random()?),
    390         revision,
    391         previous: before.head,
    392         head: CheckpointDigest::from_bytes([0; 32]),
    393         pool: None,
    394         order: original.frame.header.order,
    395         related_operation: Some(original.report.attempt().operation_id()),
    396         subject_grant: None,
    397         bytes: 0,
    398         parts: 0,
    399         body_digest: [0; 32],
    400     };
    401     header.head = head(&header, &bytes);
    402     let value = receipt(turn.selected, &header, original, at, authorization)?;
    403     let frame = ledger::prepare(turn.crypto, turn.selected, header, &bytes).await?;
    404     let mut next = auth.access.authority.clone();
    405     next.inventory = Some(super::super::InventoryCheckpoint {
    406         revision,
    407         head: Some(frame.header.head),
    408         ..before
    409     });
    410     let root = turn
    411         .crypto
    412         .seal_stock_root(turn.selected, next.catalog, &next.encode()?)
    413         .await?;
    414     Ok(Pending {
    415         old: None,
    416         frame: Some(frame),
    417         root: Some(root),
    418         value,
    419     })
    420 }