lib

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

rewrap_admission.rs (18156B)


      1 //! Confirmed one-invocation wrapping admission, separate from obtained bytes.
      2 use super::*;
      3 use radroots_domain::UnixSeconds;
      4 use radroots_storage::inventory::{StockRewrapAdmission, StockRewrapOutcome, StockRewrapRequest};
      5 const MAGIC: &[u8; 8] = b"RDSTRP1\0";
      6 const BYTES: usize = 248;
      7 pub(super) struct Admitted {
      8     pub frame: ledger::Retained,
      9     pub report: StockRewrapAdmission,
     10     pub original_entry: OperationId,
     11     projection: Projection,
     12 }
     13 fn head(header: &ledger::Header, body: &[u8]) -> CheckpointDigest {
     14     let mut hash = Sha256::new();
     15     hash.update(b"radroots.seller_stock.rewrap_admission_chain.v1\0");
     16     hash.update([13]);
     17     hash.update(codec::head(header, body).as_bytes());
     18     CheckpointDigest::from_bytes(hash.finalize().into())
     19 }
     20 fn reference(body: &mut Vec<u8>, header: &ledger::Header) {
     21     body.extend_from_slice(header.operation.as_bytes());
     22     body.extend_from_slice(header.transaction.as_bytes());
     23     body.extend_from_slice(header.head.as_bytes());
     24 }
     25 fn encode(
     26     id: OperationId,
     27     original: &Retained,
     28     consent: &super::super::consent::Retained,
     29     at: UnixSeconds,
     30     expires: UnixSeconds,
     31 ) -> Zeroizing<Vec<u8>> {
     32     let mut body = Zeroizing::new(Vec::with_capacity(BYTES));
     33     body.extend_from_slice(MAGIC);
     34     body.extend_from_slice(id.as_bytes());
     35     reference(&mut body, &original.frame.header);
     36     reference(&mut body, &consent.frame.header);
     37     body.extend_from_slice(&at.get().to_be_bytes());
     38     body.extend_from_slice(&expires.get().to_be_bytes());
     39     body
     40 }
     41 pub(super) async fn lookup(
     42     turn: &mut Turn<'_>,
     43     request: &StockRewrapRequest,
     44 ) -> Result<Option<Admitted>, OperationError> {
     45     let source = request.source();
     46     let entry: Option<Vec<u8>> = sqlx::query_scalar("SELECT CASE WHEN length(entry_id)=32 THEN entry_id END FROM stock_rewrap_admissions WHERE actor=? AND operation_id=? AND recipient=? AND request_id=?")
     47         .bind(turn.selected.participant().as_bytes().as_slice()).bind(source.operation_id().as_bytes().as_slice())
     48         .bind(source.recipient().as_bytes().as_slice()).bind(request.rewrap_id().as_bytes().as_slice())
     49         .fetch_optional(&mut *turn.connection).await.map_err(|_| OperationError::RecoveryRequired)?;
     50     let Some(entry) = entry else { return Ok(None) };
     51     let retained = Box::pin(read_entry(
     52         turn.connection,
     53         turn.selected,
     54         turn.crypto,
     55         source.binding(),
     56         OperationId::from_bytes(
     57             entry
     58                 .try_into()
     59                 .map_err(|_| OperationError::RecoveryRequired)?,
     60         ),
     61     ))
     62     .await?;
     63     let original = retained.report.original();
     64     if retained.report.rewrap_id() != request.rewrap_id()
     65         || original.attempt().operation_id() != source.operation_id()
     66         || original.attempt().command_digest() != source.command_digest()
     67         || original.recipient() != source.recipient()
     68     {
     69         return Err(OperationError::RecoveryRequired);
     70     }
     71     Ok(Some(retained))
     72 }
     73 pub(super) async fn read_entry(
     74     connection: &mut SqliteConnection,
     75     input: &AttachmentInput,
     76     crypto: &WorkspaceCrypto,
     77     binding: &WorkspaceBinding,
     78     entry: OperationId,
     79 ) -> Result<Admitted, OperationError> {
     80     let catalog: i64 = sqlx::query_scalar("PRAGMA user_version")
     81         .fetch_one(&mut *connection)
     82         .await
     83         .map_err(|_| OperationError::RecoveryRequired)?;
     84     let frame = Box::pin(ledger::read(connection, input, crypto, entry))
     85         .await?
     86         .ok_or(OperationError::RecoveryRequired)?;
     87     let (authority, _, _, _) = super::super::read(connection, input, crypto).await?;
     88     let body = frame.body.as_slice();
     89     if !matches!(catalog, 18 | 19)
     90         || frame.header.family != ledger::Family::RewrapAdmission
     91         || body.len() != BYTES
     92         || &body[..8] != MAGIC
     93     {
     94         return Err(OperationError::RecoveryRequired);
     95     }
     96     let array = |start, end| -> Result<[u8; 32], OperationError> {
     97         body[start..end]
     98             .try_into()
     99             .map_err(|_| OperationError::RecoveryRequired)
    100     };
    101     let id = OperationId::from_bytes(array(8, 40)?);
    102     let original = Box::pin(codec::read_original_entry(
    103         connection,
    104         input,
    105         crypto,
    106         binding,
    107         OperationId::from_bytes(array(40, 72)?),
    108     ))
    109     .await?;
    110     let consent = Box::pin(super::super::consent::read(
    111         connection,
    112         input,
    113         crypto,
    114         authority.input.grant_id(),
    115         OperationId::from_bytes(array(136, 168)?),
    116     ))
    117     .await?
    118     .ok_or(OperationError::RecoveryRequired)?;
    119     let at = UnixSeconds::new(u64::from_be_bytes(
    120         body[232..240]
    121             .try_into()
    122             .map_err(|_| OperationError::RecoveryRequired)?,
    123     ))
    124     .map_err(|_| OperationError::RecoveryRequired)?;
    125     let expires = UnixSeconds::new(u64::from_be_bytes(
    126         body[240..248]
    127             .try_into()
    128             .map_err(|_| OperationError::RecoveryRequired)?,
    129     ))
    130     .map_err(|_| OperationError::RecoveryRequired)?;
    131     let h = &frame.header;
    132     let first = &original.frame.header;
    133     if first.transaction != TransactionId::from_bytes(array(72, 104)?)
    134         || first.head != CheckpointDigest::from_bytes(array(104, 136)?)
    135         || consent.frame.header.transaction != TransactionId::from_bytes(array(168, 200)?)
    136         || consent.frame.header.head != CheckpointDigest::from_bytes(array(200, 232)?)
    137         || h.actor.participant() != first.actor.participant()
    138         || h.actor.grant_id() != Some(consent.subject)
    139         || h.digest != first.digest
    140         || h.related_operation != first.related_operation
    141         || h.order != first.order
    142         || h.revision <= first.revision
    143         || h.revision <= consent.frame.header.revision
    144         || consent.command.context().operation_id()
    145             != first
    146                 .related_operation
    147                 .ok_or(OperationError::RecoveryRequired)?
    148         || consent.command.digest() != h.digest
    149         || at < consent.observed_at
    150         || expires > consent.expires
    151         || at >= expires
    152         || expires.get() - at.get() > 30
    153         || head(h, body) != h.head
    154     {
    155         return Err(OperationError::RecoveryRequired);
    156     }
    157     let source = original.source.receipt();
    158     let request = StockRewrapRequest::new(
    159         StockEnvelopeRequest::new(
    160             binding.clone(),
    161             source.checkpoint(),
    162             source.attempt().operation_id(),
    163             source.attempt().command_digest(),
    164             source.recipient(),
    165             None,
    166         )?,
    167         id,
    168     );
    169     let report = StockRewrapAdmission::from_store_report(
    170         &request,
    171         source,
    172         h.transaction,
    173         at,
    174         expires,
    175         InventoryCheckpointRef::from_host_metadata(input.authority(), h.revision, Some(h.head))?,
    176     )?;
    177     let retained = Admitted {
    178         original_entry: first.operation,
    179         projection: Projection::Admission {
    180             operation: source.attempt().operation_id(),
    181             recipient: source.recipient(),
    182             request: id,
    183         },
    184         frame,
    185         report,
    186     };
    187     retained.confirm(connection).await?;
    188     Ok(retained)
    189 }
    190 impl Admitted {
    191     pub(super) async fn confirm(
    192         &self,
    193         connection: &mut SqliteConnection,
    194     ) -> Result<(), OperationError> {
    195         ledger::confirm_header(connection, &self.frame.header, &self.frame.protected).await?;
    196         ledger::confirm_parts(
    197             connection,
    198             self.frame.header.actor,
    199             self.frame.header.operation,
    200             self.frame.parts_witness,
    201             self.frame.header.parts,
    202         )
    203         .await?;
    204         self.projection
    205             .confirm(
    206                 connection,
    207                 self.frame.header.actor.participant(),
    208                 self.frame.header.operation,
    209             )
    210             .await?;
    211         let count: i64 = sqlx::query_scalar(
    212             "SELECT count(*) FROM stock_movements WHERE actor=? AND operation_id=?",
    213         )
    214         .bind(self.frame.header.actor.participant().as_bytes().as_slice())
    215         .bind(self.frame.header.operation.as_bytes().as_slice())
    216         .fetch_one(connection)
    217         .await
    218         .map_err(|_| OperationError::RecoveryRequired)?;
    219         if count != 0 {
    220             return Err(OperationError::RecoveryRequired);
    221         }
    222         Ok(())
    223     }
    224     pub(super) fn into_history(self) -> ledger::HistoryEntry {
    225         ledger::HistoryEntry {
    226             deficit: None,
    227             envelope: Some(self.projection),
    228             delivery: None,
    229             aborted: None,
    230             preparation: None,
    231             header: self.frame.header,
    232             protected: self.frame.protected,
    233             parts_witness: self.frame.parts_witness,
    234             pools: vec![],
    235             mapping: None,
    236             movements: vec![],
    237             signing: None,
    238             installation: None,
    239             local_record: None,
    240         }
    241     }
    242 }
    243 pub(in crate::workspace) async fn prepare(
    244     turn: &mut Turn<'_>,
    245     request: StockRewrapRequest,
    246     proof: AttachmentProof,
    247 ) -> Result<StockRewrapOutcome, OperationError> {
    248     if *turn.uncertain {
    249         return Err(OperationError::RecoveryRequired);
    250     }
    251     let source = request.source();
    252     if source.envelope_event_id().is_some() {
    253         return Err(OperationError::InvalidCommand);
    254     }
    255     let catalog: i64 = sqlx::query_scalar("PRAGMA user_version")
    256         .fetch_one(&mut *turn.connection)
    257         .await
    258         .map_err(|_| OperationError::RecoveryRequired)?;
    259     if !matches!(catalog, 18 | 19) {
    260         return Err(OperationError::UnsupportedOperation);
    261     }
    262     let auth = Box::pin(super::super::signing_plan::load(
    263         turn,
    264         source.binding(),
    265         source.minimum_checkpoint(),
    266         source.operation_id(),
    267         source.command_digest(),
    268         &proof,
    269     ))
    270     .await?;
    271     if !matches!(auth.access.authority.catalog, 18 | 19)
    272         || !auth
    273             .original
    274             .receipt
    275             .rumor()
    276             .recipients()
    277             .contains(&source.recipient())
    278     {
    279         return Err(OperationError::InvalidEvidence);
    280     }
    281     let witness = Box::pin(full_proof(turn, source, &auth.access.authority)).await?;
    282     let selection =
    283         super::rewrap::selection::SelectionWitness::read(turn.connection, source).await?;
    284     let original = Box::pin(lookup_original(turn, source))
    285         .await?
    286         .ok_or(OperationError::MissingHistory)?;
    287     let existing = Box::pin(lookup(turn, &request)).await?;
    288     let before = auth
    289         .access
    290         .authority
    291         .inventory
    292         .ok_or(OperationError::RecoveryRequired)?;
    293     let (frame, root, report) = if let Some(existing) = &existing {
    294         if existing.report.original() != original.source.receipt() {
    295             return Err(OperationError::RecoveryRequired);
    296         }
    297         (None, None, existing.report)
    298     } else {
    299         if selection.count >= 192 {
    300             return Err(OperationError::DeliveryAttemptLimit);
    301         }
    302         let at = auth.access.current.observed_at();
    303         let expires = UnixSeconds::new(
    304             at.get()
    305                 .checked_add(30)
    306                 .ok_or(OperationError::DeadlineExceeded)?,
    307         )
    308         .map_err(|_| OperationError::DeadlineExceeded)?
    309         .min(auth.access.current.expires_at())
    310         .min(auth.consent.expires);
    311         if expires <= at {
    312             return Err(OperationError::DeadlineExceeded);
    313         }
    314         let revision = Sequence::new(
    315             before
    316                 .revision
    317                 .get()
    318                 .checked_add(1)
    319                 .ok_or(WorkspaceError::Capacity)?,
    320         )
    321         .map_err(|_| WorkspaceError::Capacity)?;
    322         let body = encode(request.rewrap_id(), &original, &auth.consent, at, expires);
    323         let mut header = ledger::Header {
    324             version: 5,
    325             family: ledger::Family::RewrapAdmission,
    326             namespace: SellerAuthoritySelection::from_attachment(turn.selected),
    327             actor: auth.access.current.actor(),
    328             operation: OperationId::from_bytes(super::super::super::random()?),
    329             digest: source.command_digest(),
    330             transaction: TransactionId::from_bytes(super::super::super::random()?),
    331             revision,
    332             previous: before.head,
    333             head: CheckpointDigest::from_bytes([0; 32]),
    334             pool: None,
    335             order: original.frame.header.order,
    336             related_operation: Some(source.operation_id()),
    337             subject_grant: None,
    338             bytes: 0,
    339             parts: 0,
    340             body_digest: [0; 32],
    341         };
    342         header.head = head(&header, &body);
    343         let report = StockRewrapAdmission::from_store_report(
    344             &request,
    345             original.source.receipt(),
    346             header.transaction,
    347             at,
    348             expires,
    349             InventoryCheckpointRef::from_host_metadata(
    350                 turn.selected.authority(),
    351                 revision,
    352                 Some(header.head),
    353             )?,
    354         )?;
    355         let frame = ledger::prepare(turn.crypto, turn.selected, header, &body).await?;
    356         let mut next = auth.access.authority.clone();
    357         next.inventory = Some(InventoryCheckpoint {
    358             revision,
    359             head: Some(frame.header.head),
    360             ..before
    361         });
    362         let root = turn
    363             .crypto
    364             .seal_stock_root(turn.selected, next.catalog, &next.encode()?)
    365             .await?;
    366         (Some(frame), Some(root), report)
    367     };
    368     let unknown = || {
    369         StockRewrapOutcome::Unknown(CommitAttempt::new(
    370             turn.selected.workspace_id(),
    371             source.operation_id(),
    372             source.command_digest(),
    373             Some(report.transaction_id()),
    374         ))
    375     };
    376     let mut tx = turn
    377         .connection
    378         .begin_with("BEGIN IMMEDIATE")
    379         .await
    380         .map_err(|_| OperationError::StorageFailure)?;
    381     let checked: Result<(), OperationError> = async {
    382         let current = auth
    383             .confirm(&mut tx, turn.namespace, turn.clock, &proof, false)
    384             .await?;
    385         if frame.is_some() && current.observed_at() >= report.expires_at() {
    386             return Err(OperationError::DeadlineExceeded);
    387         }
    388         inventory::check_head(&mut tx, before).await?;
    389         witness.confirm(&mut tx).await?;
    390         selection.confirm(&mut tx, source).await?;
    391         original.confirm(&mut tx).await?;
    392         if let Some(existing) = &existing {
    393             existing.confirm(&mut tx).await?;
    394         }
    395         if let Some(frame) = &frame {
    396             frame.insert_record(&mut tx).await?;
    397             Projection::Admission {
    398                 operation: source.operation_id(),
    399                 recipient: source.recipient(),
    400                 request: request.rewrap_id(),
    401             }
    402             .insert(&mut tx, turn.selected.participant(), frame.header.operation)
    403             .await?;
    404             let changed = sqlx::query(
    405                 "UPDATE stock_authority SET protected=? WHERE singleton=1 AND protected=?",
    406             )
    407             .bind(root.as_ref().ok_or(OperationError::RecoveryRequired)?)
    408             .bind(&auth.access.root)
    409             .execute(&mut *tx)
    410             .await
    411             .map_err(|_| OperationError::StorageFailure)?;
    412             if changed.rows_affected() != 1 {
    413                 return Err(OperationError::RecoveryRequired);
    414             }
    415         }
    416         turn.namespace.validate()?;
    417         Ok(())
    418     }
    419     .await;
    420     if let Err(error) = checked {
    421         if tx.rollback().await.is_err() {
    422             *turn.uncertain = true;
    423             return Ok(unknown());
    424         }
    425         return Err(error);
    426     }
    427     let done = if frame.is_some() {
    428         tx.commit().await
    429     } else {
    430         tx.rollback().await
    431     };
    432     if done.is_err() {
    433         *turn.uncertain = true;
    434         return Ok(unknown());
    435     }
    436     Ok(if frame.is_some() {
    437         StockRewrapOutcome::Claimed(Box::new(report))
    438     } else {
    439         StockRewrapOutcome::Retained(Box::new(report))
    440     })
    441 }
    442 
    443 /// Repair the original writer fence without returning history or a new permit.
    444 pub(in crate::workspace) async fn reconcile(
    445     turn: &mut Turn<'_>,
    446     request: StockRewrapRequest,
    447     proof: AttachmentProof,
    448 ) -> Result<(), OperationError> {
    449     if *turn.uncertain {
    450         return Err(OperationError::RecoveryRequired);
    451     }
    452     let source = request.source();
    453     if source.envelope_event_id().is_some() {
    454         return Err(OperationError::InvalidCommand);
    455     }
    456     let input = source.binding().input();
    457     if !SellerAuthoritySelection::from_attachment(turn.selected).matches_attachment(input) {
    458         return Err(OperationError::Unauthorized);
    459     }
    460     let (authority, record, root, grant) =
    461         super::super::read(turn.connection, input, turn.crypto).await?;
    462     if !matches!(authority.catalog, 18 | 19) {
    463         return Err(OperationError::UnsupportedOperation);
    464     }
    465     record.authenticate_retained_capture(input, &proof)?;
    466     let witness = Box::pin(full_proof(turn, source, &authority)).await?;
    467     let selection =
    468         super::rewrap::selection::SelectionWitness::read(turn.connection, source).await?;
    469     let existing = Box::pin(lookup(turn, &request)).await?;
    470     if existing
    471         .as_ref()
    472         .is_some_and(|value| value.frame.header.actor != source.binding().actor())
    473     {
    474         return Err(OperationError::Unauthorized);
    475     }
    476     let mut tx = turn
    477         .connection
    478         .begin_with("BEGIN IMMEDIATE")
    479         .await
    480         .map_err(|_| OperationError::StorageFailure)?;
    481     let checked: Result<(), OperationError> = async {
    482         turn.namespace.validate()?;
    483         super::super::unchanged(&mut tx, input, authority.catalog, &root, &grant).await?;
    484         record.authenticate_retained_capture(input, &proof)?;
    485         witness.confirm(&mut tx).await?;
    486         selection.confirm(&mut tx, source).await?;
    487         if let Some(existing) = &existing {
    488             existing.confirm(&mut tx).await?;
    489         }
    490         turn.namespace.validate()?;
    491         Ok(())
    492     }
    493     .await;
    494     if tx.rollback().await.is_err() {
    495         *turn.uncertain = true;
    496         return Err(OperationError::RecoveryRequired);
    497     }
    498     checked
    499 }