lib

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

rewrap_capture.rs (8897B)


      1 //! Confirm original obtained rewrap bytes without provider IO inside SQL.
      2 use super::*;
      3 
      4 pub(in crate::workspace::stock::envelope) async fn capture(
      5     turn: &mut Turn<'_>,
      6     request: StockRewrapRequest,
      7     proof: AttachmentProof,
      8     candidate: PrivateEnvelopeCandidate,
      9 ) -> Result<StockEnvelopeOutcome, OperationError> {
     10     if *turn.uncertain {
     11         return Err(OperationError::RecoveryRequired);
     12     }
     13     turn.namespace.validate()?;
     14     let rewrap = request;
     15     let request = rewrap.source();
     16     let event = request
     17         .envelope_event_id()
     18         .ok_or(OperationError::InvalidCommand)?;
     19     if event != candidate.event_id() || candidate.recipient() != request.recipient() {
     20         return Err(OperationError::InvalidEvidence);
     21     }
     22     let input = request.binding().input();
     23     if !SellerAuthoritySelection::from_attachment(turn.selected).matches_attachment(input) {
     24         return Err(OperationError::Unauthorized);
     25     }
     26     let (authority, record, root, grant) =
     27         super::super::super::read(turn.connection, input, turn.crypto).await?;
     28     if !matches!(authority.catalog, 18 | 19) {
     29         return Err(OperationError::UnsupportedOperation);
     30     }
     31     record.authenticate_retained_capture(input, &proof)?;
     32     let witness = Box::pin(full_proof(turn, request, &authority)).await?;
     33     let selection = SelectionWitness::read(turn.connection, request).await?;
     34     let admission = Box::pin(rewrap_admission::lookup(turn, &rewrap))
     35         .await?
     36         .ok_or(OperationError::MissingHistory)?;
     37     if admission.frame.header.actor != request.binding().actor() {
     38         return Err(OperationError::Unauthorized);
     39     }
     40     let first = Box::pin(lookup_original(turn, request))
     41         .await?
     42         .ok_or(OperationError::MissingHistory)?;
     43     if first.source.receipt() != admission.report.original()
     44         || first.source.receipt().event_id() == event
     45     {
     46         return Err(OperationError::InvalidEvidence);
     47     }
     48     let original = Box::pin(Original::load(turn, request)).await?;
     49     if original.evidence.frame.header.actor.participant() != request.binding().actor().participant()
     50         || first.source.receipt().evidence() != original.evidence.value.receipt()
     51         || first.source.receipt().installation_transaction_id()
     52             != original.installation.frame.header.transaction
     53         || original
     54             .installation
     55             .receipt
     56             .publication_work()
     57             .iter()
     58             .any(|work| work.recipient() == candidate.author())
     59     {
     60         return Err(OperationError::InvalidEvidence);
     61     }
     62     candidate.with_wrapping_key(|key| {
     63         original.evidence.value.with_json(|seal| {
     64             super::super::super::super::delivery::containment::verify(
     65                 candidate.raw_json(),
     66                 candidate.author(),
     67                 key,
     68                 request.recipient(),
     69                 seal,
     70                 original.evidence.value.receipt().digest(),
     71             )
     72         })
     73     })?;
     74     let existing = Box::pin(lookup(turn, request, event)).await?;
     75     let captured: Option<Vec<u8>> = sqlx::query_scalar(
     76         "SELECT CASE WHEN length(event_id)=32 THEN event_id END FROM stock_rewraps WHERE actor=? AND admission_entry=?",
     77     )
     78     .bind(input.participant().as_bytes().as_slice())
     79     .bind(admission.frame.header.operation.as_bytes().as_slice())
     80     .fetch_optional(&mut *turn.connection)
     81     .await
     82     .map_err(|_| OperationError::RecoveryRequired)?;
     83     if captured
     84         .as_deref()
     85         .is_some_and(|old| old != event.as_bytes().as_slice())
     86     {
     87         return Err(OperationError::IdempotencyConflict);
     88     }
     89     let before = authority
     90         .inventory
     91         .ok_or(OperationError::RecoveryRequired)?;
     92     let (frame, updated, receipt) = if let Some(old) = &existing {
     93         if old.source.with_json(|raw| raw != candidate.raw_json())
     94             || old.source.receipt().evidence() != first.source.receipt().evidence()
     95             || old.source.receipt().rewrap_admission_transaction_id()
     96                 != Some(admission.report.transaction_id())
     97             || old.source.receipt().installation_transaction_id()
     98                 != first.source.receipt().installation_transaction_id()
     99         {
    100             return Err(OperationError::IdempotencyConflict);
    101         }
    102         (None, None, old.source.receipt())
    103     } else {
    104         let revision = Sequence::new(
    105             before
    106                 .revision
    107                 .get()
    108                 .checked_add(1)
    109                 .ok_or(WorkspaceError::Capacity)?,
    110         )
    111         .map_err(|_| WorkspaceError::Capacity)?;
    112         let body = encode(&admission, request, candidate.raw_json());
    113         let mut header = ledger::Header {
    114             version: 5,
    115             family: ledger::Family::RewrappedEnvelope,
    116             namespace: SellerAuthoritySelection::from_attachment(turn.selected),
    117             actor: request.binding().actor(),
    118             operation: OperationId::from_bytes(super::super::super::super::random()?),
    119             digest: request.command_digest(),
    120             transaction: TransactionId::from_bytes(super::super::super::super::random()?),
    121             revision,
    122             previous: before.head,
    123             head: CheckpointDigest::from_bytes([0; 32]),
    124             pool: None,
    125             order: first.frame.header.order,
    126             related_operation: Some(request.operation_id()),
    127             subject_grant: None,
    128             bytes: 0,
    129             parts: 0,
    130             body_digest: [0; 32],
    131         };
    132         header.head = head(&header, &body);
    133         let receipt = StockEnvelopeReceipt::from_committed_store(
    134             request,
    135             CommitAttempt::new(
    136                 input.workspace_id(),
    137                 request.operation_id(),
    138                 request.command_digest(),
    139                 Some(header.transaction),
    140             ),
    141             first.source.receipt().evidence(),
    142             first.source.receipt().installation_transaction_id(),
    143             event,
    144             *candidate.digest(),
    145             InventoryCheckpointRef::from_host_metadata(
    146                 input.authority(),
    147                 revision,
    148                 Some(header.head),
    149             )?,
    150         )?;
    151         let receipt = receipt.with_rewrap_admission(&admission.report)?;
    152         let frame = ledger::prepare(turn.crypto, turn.selected, header, &body).await?;
    153         let mut next = authority.clone();
    154         next.inventory = Some(InventoryCheckpoint {
    155             revision,
    156             head: Some(frame.header.head),
    157             ..before
    158         });
    159         let updated = turn
    160             .crypto
    161             .seal_stock_root(turn.selected, next.catalog, &next.encode()?)
    162             .await?;
    163         (Some(frame), Some(updated), receipt)
    164     };
    165     let mut tx = turn
    166         .connection
    167         .begin_with("BEGIN IMMEDIATE")
    168         .await
    169         .map_err(|_| OperationError::StorageFailure)?;
    170     let changed: Result<(), OperationError> = async {
    171         turn.namespace.validate()?;
    172         super::super::super::unchanged(&mut tx, input, authority.catalog, &root, &grant).await?;
    173         record.authenticate_retained_capture(input, &proof)?;
    174         witness.confirm(&mut tx).await?;
    175         selection.confirm(&mut tx, request).await?;
    176         first.confirm(&mut tx).await?;
    177         admission.confirm(&mut tx).await?;
    178         if let Some(old) = &existing {
    179             old.confirm(&mut tx).await?;
    180         }
    181         if let Some(frame) = &frame {
    182             frame.insert_record(&mut tx).await?;
    183             Projection::Rewrap {
    184                 operation: request.operation_id(),
    185                 recipient: request.recipient(),
    186                 admission: admission.frame.header.operation,
    187                 event,
    188             }
    189             .insert(&mut tx, input.participant(), frame.header.operation)
    190             .await?;
    191             let changed = sqlx::query(
    192                 "UPDATE stock_authority SET protected=? WHERE singleton=1 AND protected=?",
    193             )
    194             .bind(updated.as_ref().ok_or(OperationError::RecoveryRequired)?)
    195             .bind(&root)
    196             .execute(&mut *tx)
    197             .await
    198             .map_err(|_| OperationError::StorageFailure)?;
    199             if changed.rows_affected() != 1 {
    200                 return Err(OperationError::RecoveryRequired);
    201             }
    202         }
    203         turn.namespace.validate()?;
    204         Ok(())
    205     }
    206     .await;
    207     if let Err(error) = changed {
    208         if tx.rollback().await.is_err() {
    209             *turn.uncertain = true;
    210             return Ok(StockEnvelopeOutcome::Unknown(receipt.attempt()));
    211         }
    212         return Err(error);
    213     }
    214     let done = if frame.is_some() {
    215         tx.commit().await
    216     } else {
    217         tx.rollback().await
    218     };
    219     if done.is_err() {
    220         *turn.uncertain = true;
    221         return Ok(StockEnvelopeOutcome::Unknown(receipt.attempt()));
    222     }
    223     Ok(StockEnvelopeOutcome::Committed(Box::new(receipt)))
    224 }