lib

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

envelope.rs (15597B)


      1 //! Obtained original outers on the stock owner. Capture grants no transport right.
      2 use super::*;
      3 use inventory::{Turn, checkpoint};
      4 use radroots_domain::{CheckpointDigest, EnvelopeEventId, OperationId, PublicKey};
      5 use radroots_storage::{
      6     command::{CommitAttempt, OperationError, PrivateEnvelopeCandidate},
      7     inventory::{
      8         InventoryCheckpointRef, StockEnvelopeOutcome, StockEnvelopeReceipt, StockEnvelopeRequest,
      9         StockEnvelopeSource,
     10     },
     11 };
     12 use sha2::{Digest, Sha256};
     13 use sqlx::Row;
     14 use zeroize::Zeroizing;
     15 mod codec;
     16 mod projection;
     17 mod rewrap;
     18 mod rewrap_admission;
     19 use codec::Original;
     20 pub(in crate::workspace::stock) use codec::Retained;
     21 pub(super) use codec::read_entry;
     22 pub(super) use projection::{
     23     Projection, raw_admission_projection, raw_projection, raw_rewrap_projection,
     24 };
     25 pub(in crate::workspace) use rewrap_admission::prepare as prepare_rewrap;
     26 pub(in crate::workspace::stock) async fn admission_history(
     27     connection: &mut SqliteConnection,
     28     input: &AttachmentInput,
     29     crypto: &WorkspaceCrypto,
     30     binding: &WorkspaceBinding,
     31     entry: OperationId,
     32 ) -> Result<ledger::HistoryEntry, OperationError> {
     33     Ok(Box::pin(rewrap_admission::read_entry(
     34         connection, input, crypto, binding, entry,
     35     ))
     36     .await?
     37     .into_history())
     38 }
     39 pub(in crate::workspace) use rewrap::{attempt as rewrap_attempt, page};
     40 pub(in crate::workspace) use rewrap_admission::reconcile as reconcile_rewrap_admission;
     41 pub(in crate::workspace) enum CaptureRequest {
     42     Original(Box<StockEnvelopeRequest>),
     43     Rewrap(Box<radroots_storage::inventory::StockRewrapRequest>),
     44 }
     45 impl CaptureRequest {
     46     pub(in crate::workspace) fn source(&self) -> &StockEnvelopeRequest {
     47         match self {
     48             Self::Original(request) => request,
     49             Self::Rewrap(request) => request.source(),
     50         }
     51     }
     52 }
     53 pub(in crate::workspace) async fn capture_obtained(
     54     turn: &mut Turn<'_>,
     55     request: CaptureRequest,
     56     proof: AttachmentProof,
     57     candidate: PrivateEnvelopeCandidate,
     58 ) -> Result<StockEnvelopeOutcome, OperationError> {
     59     match request {
     60         CaptureRequest::Original(request) => {
     61             Box::pin(capture(turn, *request, proof, candidate)).await
     62         }
     63         CaptureRequest::Rewrap(request) => {
     64             Box::pin(rewrap::capture(turn, *request, proof, candidate)).await
     65         }
     66     }
     67 }
     68 
     69 async fn selected_entry(
     70     connection: &mut SqliteConnection,
     71     actor: PublicKey,
     72     operation: OperationId,
     73     recipient: PublicKey,
     74 ) -> Result<Option<OperationId>, OperationError> {
     75     let row: Option<Vec<u8>> = sqlx::query_scalar(
     76         "SELECT CASE WHEN length(entry_id)=32 THEN entry_id END FROM stock_envelopes WHERE actor=? AND operation_id=? AND recipient=?",
     77     )
     78     .bind(actor.as_bytes().as_slice())
     79     .bind(operation.as_bytes().as_slice())
     80     .bind(recipient.as_bytes().as_slice())
     81     .fetch_optional(connection)
     82     .await
     83     .map_err(|_| OperationError::RecoveryRequired)?;
     84     row.map(|bytes| {
     85         bytes
     86             .try_into()
     87             .map(OperationId::from_bytes)
     88             .map_err(|_| OperationError::RecoveryRequired)
     89     })
     90     .transpose()
     91 }
     92 async fn lookup_original(
     93     turn: &mut Turn<'_>,
     94     request: &StockEnvelopeRequest,
     95 ) -> Result<Option<Retained>, OperationError> {
     96     let Some(entry) = selected_entry(
     97         turn.connection,
     98         turn.selected.participant(),
     99         request.operation_id(),
    100         request.recipient(),
    101     )
    102     .await?
    103     else {
    104         return Ok(None);
    105     };
    106     let retained = Box::pin(read_entry(
    107         turn.connection,
    108         turn.selected,
    109         turn.crypto,
    110         request.binding(),
    111         entry,
    112     ))
    113     .await?
    114     .ok_or(OperationError::RecoveryRequired)?;
    115     let receipt = retained.source.receipt();
    116     if receipt.attempt().operation_id() != request.operation_id()
    117         || receipt.attempt().command_digest() != request.command_digest()
    118         || receipt.recipient() != request.recipient()
    119     {
    120         return Err(OperationError::RecoveryRequired);
    121     }
    122     Ok(Some(retained))
    123 }
    124 pub(in crate::workspace::stock) async fn lookup(
    125     turn: &mut Turn<'_>,
    126     request: &StockEnvelopeRequest,
    127 ) -> Result<Option<Retained>, OperationError> {
    128     let original = Box::pin(lookup_original(turn, request)).await?;
    129     let Some(event) = request.envelope_event_id() else {
    130         return Ok(original);
    131     };
    132     if original
    133         .as_ref()
    134         .is_some_and(|value| value.source.receipt().event_id() == event)
    135     {
    136         return Ok(original);
    137     }
    138     Box::pin(rewrap::lookup(turn, request, event)).await
    139 }
    140 pub(in crate::workspace::stock) async fn full_proof(
    141     turn: &mut Turn<'_>,
    142     request: &StockEnvelopeRequest,
    143     authority: &Authority,
    144 ) -> Result<checkpoint::MinimumProof, OperationError> {
    145     let requested = Box::pin(checkpoint::authenticate_minimum(
    146         turn.connection,
    147         turn.selected,
    148         turn.crypto,
    149         request.binding(),
    150         authority,
    151         request.minimum_checkpoint(),
    152     ))
    153     .await?;
    154     if request.minimum_checkpoint().revision().get() == 0 {
    155         return Ok(requested);
    156     }
    157     let zero = InventoryCheckpointRef::from_host_metadata(
    158         turn.selected.authority(),
    159         Sequence::new(0).map_err(|_| WorkspaceError::InvalidInput)?,
    160         None,
    161     )?;
    162     Box::pin(checkpoint::authenticate_minimum(
    163         turn.connection,
    164         turn.selected,
    165         turn.crypto,
    166         request.binding(),
    167         authority,
    168         zero,
    169     ))
    170     .await
    171 }
    172 
    173 pub(in crate::workspace) async fn capture(
    174     turn: &mut Turn<'_>,
    175     request: StockEnvelopeRequest,
    176     proof: AttachmentProof,
    177     candidate: PrivateEnvelopeCandidate,
    178 ) -> Result<StockEnvelopeOutcome, OperationError> {
    179     if request.envelope_event_id().is_some() {
    180         return Err(OperationError::InvalidCommand);
    181     }
    182     if *turn.uncertain {
    183         return Err(OperationError::RecoveryRequired);
    184     }
    185     turn.namespace.validate()?;
    186     let input = request.binding().input();
    187     if !SellerAuthoritySelection::from_attachment(turn.selected).matches_attachment(input) {
    188         return Err(OperationError::Unauthorized);
    189     }
    190     let (authority, record, root, grant) = super::read(turn.connection, input, turn.crypto).await?;
    191     if !matches!(authority.catalog, 16..=20) {
    192         return Err(OperationError::UnsupportedOperation);
    193     }
    194     record.authenticate_retained_capture(input, &proof)?;
    195     let witness = Box::pin(full_proof(turn, &request, &authority)).await?;
    196     let original = Box::pin(Original::load(turn, &request)).await?;
    197     if original.evidence.frame.header.actor != request.binding().actor()
    198         || candidate.recipient() != request.recipient()
    199         || original
    200             .installation
    201             .receipt
    202             .publication_work()
    203             .iter()
    204             .any(|work| work.recipient() == candidate.author())
    205     {
    206         return Err(OperationError::InvalidEvidence);
    207     }
    208     candidate.with_wrapping_key(|key| {
    209         original.evidence.value.with_json(|seal| {
    210             super::super::delivery::containment::verify(
    211                 candidate.raw_json(),
    212                 candidate.author(),
    213                 key,
    214                 request.recipient(),
    215                 seal,
    216                 original.evidence.value.receipt().digest(),
    217             )
    218         })
    219     })?;
    220     // The complete protected chain proves natural index absence as well as
    221     // presence. A missing projection is recovery evidence, never recapture.
    222     let existing = Box::pin(lookup(turn, &request)).await?;
    223     let before = authority
    224         .inventory
    225         .ok_or(OperationError::RecoveryRequired)?;
    226     let (frame, updated, receipt) = if let Some(old) = &existing {
    227         if old.source.with_json(|raw| raw != candidate.raw_json())
    228             || old.source.receipt().evidence() != original.evidence.value.receipt()
    229             || old.source.receipt().installation_transaction_id()
    230                 != original
    231                     .installation
    232                     .receipt
    233                     .attempt()
    234                     .transaction_id()
    235                     .ok_or(OperationError::RecoveryRequired)?
    236         {
    237             return Err(OperationError::IdempotencyConflict);
    238         }
    239         (None, None, old.source.receipt())
    240     } else {
    241         let revision = Sequence::new(
    242             before
    243                 .revision
    244                 .get()
    245                 .checked_add(1)
    246                 .ok_or(WorkspaceError::Capacity)?,
    247         )
    248         .map_err(|_| WorkspaceError::Capacity)?;
    249         let body = codec::encode(&original, &request, &candidate);
    250         let mut header = ledger::Header {
    251             version: 5,
    252             family: ledger::Family::Envelope,
    253             namespace: SellerAuthoritySelection::from_attachment(turn.selected),
    254             actor: original.evidence.frame.header.actor,
    255             operation: OperationId::from_bytes(super::super::random()?),
    256             digest: request.command_digest(),
    257             transaction: TransactionId::from_bytes(super::super::random()?),
    258             revision,
    259             previous: before.head,
    260             head: CheckpointDigest::from_bytes([0; 32]),
    261             pool: None,
    262             order: original.installation.frame.header.order,
    263             related_operation: Some(request.operation_id()),
    264             subject_grant: None,
    265             bytes: 0,
    266             parts: 0,
    267             body_digest: [0; 32],
    268         };
    269         header.head = codec::head(&header, &body);
    270         let receipt = StockEnvelopeReceipt::from_committed_store(
    271             &request,
    272             CommitAttempt::new(
    273                 input.workspace_id(),
    274                 request.operation_id(),
    275                 request.command_digest(),
    276                 Some(header.transaction),
    277             ),
    278             original.evidence.value.receipt(),
    279             original.installation.frame.header.transaction,
    280             candidate.event_id(),
    281             *candidate.digest(),
    282             InventoryCheckpointRef::from_host_metadata(
    283                 input.authority(),
    284                 revision,
    285                 Some(header.head),
    286             )?,
    287         )?;
    288         let frame = ledger::prepare(turn.crypto, turn.selected, header, &body).await?;
    289         let mut next = authority.clone();
    290         next.inventory = Some(InventoryCheckpoint {
    291             revision,
    292             head: Some(frame.header.head),
    293             ..before
    294         });
    295         let updated = turn
    296             .crypto
    297             .seal_stock_root(turn.selected, next.catalog, &next.encode()?)
    298             .await?;
    299         (Some(frame), Some(updated), receipt)
    300     };
    301     let mut tx = turn
    302         .connection
    303         .begin_with("BEGIN IMMEDIATE")
    304         .await
    305         .map_err(|_| OperationError::StorageFailure)?;
    306     let changed: Result<(), OperationError> = async {
    307         turn.namespace.validate()?;
    308         super::unchanged(&mut tx, input, authority.catalog, &root, &grant).await?;
    309         record.authenticate_retained_capture(input, &proof)?;
    310         witness.confirm(&mut tx).await?;
    311         if let Some(old) = &existing {
    312             old.confirm(&mut tx).await?;
    313         }
    314         if let Some(frame) = &frame {
    315             frame.insert_record(&mut tx).await?;
    316             Projection::Original {
    317                 operation: request.operation_id(),
    318                 recipient: request.recipient(),
    319             }
    320             .insert(&mut tx, input.participant(), frame.header.operation)
    321             .await?;
    322             let result = sqlx::query(
    323                 "UPDATE stock_authority SET protected=? WHERE singleton=1 AND protected=?",
    324             )
    325             .bind(updated.as_ref().ok_or(OperationError::RecoveryRequired)?)
    326             .bind(&root)
    327             .execute(&mut *tx)
    328             .await
    329             .map_err(|_| OperationError::StorageFailure)?;
    330             if result.rows_affected() != 1 {
    331                 return Err(OperationError::RecoveryRequired);
    332             }
    333         }
    334         turn.namespace.validate()?;
    335         Ok(())
    336     }
    337     .await;
    338     if let Err(error) = changed {
    339         if tx.rollback().await.is_err() {
    340             *turn.uncertain = true;
    341             return Ok(StockEnvelopeOutcome::Unknown(receipt.attempt()));
    342         }
    343         return Err(error);
    344     }
    345     let done = if frame.is_some() {
    346         tx.commit().await
    347     } else {
    348         tx.rollback().await
    349     };
    350     if done.is_err() {
    351         *turn.uncertain = true;
    352         return Ok(StockEnvelopeOutcome::Unknown(receipt.attempt()));
    353     }
    354     Ok(StockEnvelopeOutcome::Committed(Box::new(receipt)))
    355 }
    356 
    357 pub(in crate::workspace) async fn read(
    358     turn: &mut Turn<'_>,
    359     request: StockEnvelopeRequest,
    360     proof: AttachmentProof,
    361 ) -> Result<Option<StockEnvelopeSource>, OperationError> {
    362     if *turn.uncertain {
    363         return Err(OperationError::RecoveryRequired);
    364     }
    365     turn.namespace.validate()?;
    366     let input = request.binding().input();
    367     let catalog: i64 = sqlx::query_scalar("PRAGMA user_version")
    368         .fetch_one(&mut *turn.connection)
    369         .await
    370         .map_err(|_| OperationError::RecoveryRequired)?;
    371     if !matches!(catalog, 16..=20) {
    372         return Err(OperationError::UnsupportedOperation);
    373     }
    374     let auth = Box::pin(super::signing_plan::load(
    375         turn,
    376         request.binding(),
    377         request.minimum_checkpoint(),
    378         request.operation_id(),
    379         request.command_digest(),
    380         &proof,
    381     ))
    382     .await?;
    383     if !matches!(auth.access.authority.catalog, 16..=20) {
    384         return Err(OperationError::UnsupportedOperation);
    385     }
    386     let witness = Box::pin(full_proof(turn, &request, &auth.access.authority)).await?;
    387     let retained = Box::pin(lookup(turn, &request)).await?;
    388     let mut tx = turn
    389         .connection
    390         .begin_with("BEGIN IMMEDIATE")
    391         .await
    392         .map_err(|_| OperationError::StorageFailure)?;
    393     let checked: Result<(), OperationError> = async {
    394         turn.namespace.validate()?;
    395         auth.confirm(&mut tx, turn.namespace, turn.clock, &proof, false)
    396             .await?;
    397         witness.confirm(&mut tx).await?;
    398         if let Some(retained) = &retained {
    399             retained.confirm(&mut tx).await?;
    400         } else {
    401             let count: i64 = if let Some(event) = request.envelope_event_id() {
    402                 sqlx::query_scalar("SELECT count(*) FROM stock_rewraps WHERE actor=? AND operation_id=? AND recipient=? AND event_id=?")
    403                     .bind(input.participant().as_bytes().as_slice())
    404                     .bind(request.operation_id().as_bytes().as_slice()).bind(request.recipient().as_bytes().as_slice())
    405                     .bind(event.as_bytes().as_slice()).fetch_one(&mut *tx).await.map_err(|_| OperationError::RecoveryRequired)?
    406             } else {
    407                 sqlx::query_scalar("SELECT count(*) FROM stock_envelopes WHERE actor=? AND operation_id=? AND recipient=?")
    408                     .bind(input.participant().as_bytes().as_slice())
    409                     .bind(request.operation_id().as_bytes().as_slice()).bind(request.recipient().as_bytes().as_slice())
    410                     .fetch_one(&mut *tx).await.map_err(|_| OperationError::RecoveryRequired)?
    411             };
    412             if count != 0 { return Err(OperationError::RecoveryRequired); }
    413         }
    414         turn.namespace.validate()?;
    415         Ok(())
    416     }
    417     .await;
    418     if let Err(error) = checked {
    419         if tx.rollback().await.is_err() {
    420             *turn.uncertain = true;
    421         }
    422         return Err(error);
    423     }
    424     if tx.rollback().await.is_err() {
    425         *turn.uncertain = true;
    426         return Err(OperationError::RecoveryRequired);
    427     }
    428     Ok(retained.map(|value| value.source))
    429 }