lib

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

unissued.rs (21471B)


      1 //! Retain an owned original invocation's refusal; this never releases stock.
      2 use super::super::inventory::{Turn, checkpoint};
      3 use super::*;
      4 use radroots_domain::CheckpointDigest;
      5 use radroots_signing::provider::ProviderError;
      6 use zeroize::Zeroizing;
      7 
      8 const MAGIC: &[u8; 8] = b"RDSTKN1\0";
      9 const BYTES: usize = 105;
     10 
     11 /// An authenticated retained fact about one original invocation, not a permit.
     12 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
     13 pub struct StockUnissuedReceipt {
     14     attempt: CommitAttempt,
     15     claim: SigningAttemptId,
     16     recipient: PublicKey,
     17     reason: ProviderError,
     18     checkpoint: InventoryCheckpointRef,
     19 }
     20 impl StockUnissuedReceipt {
     21     pub const fn attempt(&self) -> CommitAttempt {
     22         self.attempt
     23     }
     24     pub const fn signing_attempt_id(&self) -> SigningAttemptId {
     25         self.claim
     26     }
     27     pub const fn recipient(&self) -> PublicKey {
     28         self.recipient
     29     }
     30     pub const fn reason(&self) -> ProviderError {
     31         self.reason
     32     }
     33     pub const fn checkpoint(&self) -> InventoryCheckpointRef {
     34         self.checkpoint
     35     }
     36 }
     37 /// Confirmed append versus actual transaction uncertainty, never business success.
     38 #[derive(Clone, Debug, Eq, PartialEq)]
     39 pub enum StockUnissuedOutcome {
     40     Committed(Box<StockUnissuedReceipt>),
     41     Unknown(CommitAttempt),
     42 }
     43 
     44 /// Private worker transport, constructed only from the owned original proof.
     45 pub(in crate::workspace) struct Request {
     46     pub(in crate::workspace) binding: WorkspaceBinding,
     47     claim: SigningAttemptId,
     48     operation: OperationId,
     49     digest: CommandDigest,
     50     recipient: PublicKey,
     51     intent: [u8; 32],
     52     reason: u8,
     53 }
     54 impl Request {
     55     fn from_observation(
     56         binding: WorkspaceBinding,
     57         value: &StockUnissuedInvocation,
     58     ) -> Result<Self, OperationError> {
     59         let original = value.attempt();
     60         if binding.input().workspace_id() != original.attempt().workspace_id()
     61             || binding.actor().participant() != original.bound_plan().preparation().rumor().author()
     62         {
     63             return Err(OperationError::InvalidEvidence);
     64         }
     65         Ok(Self {
     66             binding,
     67             claim: original.attempt_id(),
     68             operation: original.attempt().operation_id(),
     69             digest: original.attempt().command_digest(),
     70             recipient: original.recipient(),
     71             intent: *original.binding().digest(),
     72             reason: encode_reason(value.reason())?,
     73         })
     74     }
     75     pub(in crate::workspace) fn attempt(&self) -> CommitAttempt {
     76         CommitAttempt::new(
     77             self.binding.input().workspace_id(),
     78             self.operation,
     79             self.digest,
     80             None,
     81         )
     82     }
     83 }
     84 fn encode_reason(reason: ProviderError) -> Result<u8, OperationError> {
     85     Ok(match reason.as_str() {
     86         "invalid_input" => 1,
     87         "limit_exceeded" => 2,
     88         "unsupported_version" => 3,
     89         "capability_unavailable" => 4,
     90         "identity_changed" => 5,
     91         "authentication_failed" => 6,
     92         "cancelled" => 7,
     93         "deadline_exceeded" => 8,
     94         "provider_failure" => 9,
     95         _ => return Err(OperationError::UnsupportedOperation),
     96     })
     97 }
     98 fn decode_reason(reason: u8) -> Result<ProviderError, OperationError> {
     99     Ok(match reason {
    100         1 => ProviderError::InvalidInput,
    101         2 => ProviderError::LimitExceeded,
    102         3 => ProviderError::UnsupportedVersion,
    103         4 => ProviderError::CapabilityUnavailable,
    104         5 => ProviderError::IdentityChanged,
    105         6 => ProviderError::AuthenticationFailed,
    106         7 => ProviderError::Cancelled,
    107         8 => ProviderError::DeadlineExceeded,
    108         9 => ProviderError::ProviderFailure,
    109         _ => return Err(OperationError::RecoveryRequired),
    110     })
    111 }
    112 fn body(original: &claim::codec::Retained, reason: u8) -> Zeroizing<Vec<u8>> {
    113     let mut bytes = Zeroizing::new(Vec::with_capacity(BYTES));
    114     bytes.extend_from_slice(MAGIC);
    115     bytes.extend_from_slice(original.frame.header.operation.as_bytes());
    116     bytes.extend_from_slice(original.frame.header.transaction.as_bytes());
    117     bytes.extend_from_slice(original.frame.header.head.as_bytes());
    118     bytes.push(reason);
    119     bytes
    120 }
    121 fn head(header: &ledger::Header, body: &[u8]) -> CheckpointDigest {
    122     let mut hash = Sha256::new();
    123     hash.update(b"radroots.seller_stock.original_unissued_chain.v1\0");
    124     hash.update(header.namespace.workspace_id().as_bytes());
    125     hash.update(header.namespace.authority().executor_id().as_bytes());
    126     hash.update(
    127         header
    128             .namespace
    129             .authority()
    130             .generation()
    131             .get()
    132             .to_be_bytes(),
    133     );
    134     hash.update(header.namespace.route_digest().as_bytes());
    135     hash.update(header.actor.participant().as_bytes());
    136     hash.update(
    137         header
    138             .actor
    139             .grant_id()
    140             .map(|v| *v.as_bytes())
    141             .unwrap_or([0; 32]),
    142     );
    143     hash.update(header.operation.as_bytes());
    144     hash.update(header.digest.as_bytes());
    145     hash.update(header.transaction.as_bytes());
    146     hash.update(header.revision.get().to_be_bytes());
    147     hash.update([u8::from(header.previous.is_some())]);
    148     hash.update(header.previous.map(|v| *v.as_bytes()).unwrap_or([0; 32]));
    149     hash.update(Sha256::digest(body));
    150     CheckpointDigest::from_bytes(hash.finalize().into())
    151 }
    152 fn receipt(
    153     input: &AttachmentInput,
    154     header: &ledger::Header,
    155     original: &claim::codec::Retained,
    156     reason: u8,
    157 ) -> Result<StockUnissuedReceipt, OperationError> {
    158     Ok(StockUnissuedReceipt {
    159         attempt: CommitAttempt::new(
    160             input.workspace_id(),
    161             original.report.attempt().operation_id(),
    162             header.digest,
    163             Some(header.transaction),
    164         ),
    165         claim: original.report.attempt_id(),
    166         recipient: original.report.recipient(),
    167         reason: decode_reason(reason)?,
    168         checkpoint: InventoryCheckpointRef::from_host_metadata(
    169             input.authority(),
    170             header.revision,
    171             Some(header.head),
    172         )?,
    173     })
    174 }
    175 pub(in crate::workspace::stock) struct Retained {
    176     frame: ledger::Retained,
    177     value: Box<StockUnissuedReceipt>,
    178     projection: Projection,
    179 }
    180 impl Retained {
    181     pub(in crate::workspace::stock) fn identity(&self) -> checkpoint::EntryIdentity {
    182         checkpoint::EntryIdentity {
    183             operation: self.frame.header.operation,
    184             revision: self.frame.header.revision,
    185             head: self.frame.header.head,
    186             protected_digest: Sha256::digest(&self.frame.protected).into(),
    187         }
    188     }
    189     pub(in crate::workspace::stock) fn receipt(&self) -> StockUnissuedReceipt {
    190         *self.value
    191     }
    192     pub(in crate::workspace::stock) async fn confirm(
    193         &self,
    194         connection: &mut SqliteConnection,
    195     ) -> Result<(), OperationError> {
    196         ledger::confirm_header(connection, &self.frame.header, &self.frame.protected).await?;
    197         ledger::confirm_parts(
    198             connection,
    199             self.frame.header.actor,
    200             self.frame.header.operation,
    201             self.frame.parts_witness,
    202             self.frame.header.parts,
    203         )
    204         .await?;
    205         self.projection
    206             .confirm(
    207                 connection,
    208                 self.frame.header.actor.participant(),
    209                 self.frame.header.operation,
    210             )
    211             .await?;
    212         let count: i64 = sqlx::query_scalar(
    213             "SELECT count(*) FROM stock_movements WHERE actor=? AND operation_id=?",
    214         )
    215         .bind(self.frame.header.actor.participant().as_bytes().as_slice())
    216         .bind(self.frame.header.operation.as_bytes().as_slice())
    217         .fetch_one(connection)
    218         .await
    219         .map_err(|_| OperationError::RecoveryRequired)?;
    220         if count != 0 {
    221             return Err(OperationError::RecoveryRequired);
    222         }
    223         Ok(())
    224     }
    225     pub(in crate::workspace::stock) fn into_history(self) -> ledger::HistoryEntry {
    226         ledger::HistoryEntry {
    227             deficit: None,
    228             delivery: None,
    229             envelope: None,
    230             aborted: None,
    231             preparation: None,
    232             installation: None,
    233             header: self.frame.header,
    234             protected: self.frame.protected,
    235             parts_witness: self.frame.parts_witness,
    236             pools: vec![],
    237             mapping: None,
    238             movements: vec![],
    239             signing: Some(self.projection),
    240             local_record: None,
    241         }
    242     }
    243 }
    244 pub(in crate::workspace::stock) async fn read_entry(
    245     connection: &mut SqliteConnection,
    246     input: &AttachmentInput,
    247     crypto: &WorkspaceCrypto,
    248     entry: OperationId,
    249 ) -> Result<Option<Retained>, OperationError> {
    250     let Some(frame) = ledger::read(connection, input, crypto, entry).await? else {
    251         return Ok(None);
    252     };
    253     let raw = frame.body.as_slice();
    254     if frame.header.family != ledger::Family::OriginalUnissued
    255         || raw.len() != BYTES
    256         || &raw[..8] != MAGIC
    257     {
    258         return Err(OperationError::RecoveryRequired);
    259     }
    260     let array = |start, end| {
    261         raw[start..end]
    262             .try_into()
    263             .map_err(|_| OperationError::RecoveryRequired)
    264     };
    265     let original = Box::pin(claim::read_entry(
    266         connection,
    267         input,
    268         crypto,
    269         OperationId::from_bytes(array(8, 40)?),
    270     ))
    271     .await?
    272     .ok_or(OperationError::RecoveryRequired)?;
    273     if original.frame.header.transaction != TransactionId::from_bytes(array(40, 72)?)
    274         || original.frame.header.head != CheckpointDigest::from_bytes(array(72, 104)?)
    275         || frame.header.actor != original.frame.header.actor
    276         || frame.header.related_operation != original.frame.header.related_operation
    277         || frame.header.order != original.frame.header.order
    278         || frame.header.digest != original.frame.header.digest
    279         || frame.header.revision <= original.frame.header.revision
    280         || head(&frame.header, raw) != frame.header.head
    281     {
    282         return Err(OperationError::RecoveryRequired);
    283     }
    284     let reason = raw[104];
    285     decode_reason(reason)?;
    286     let projection = Projection {
    287         operation: original.report.attempt().operation_id(),
    288         recipient: original.report.recipient(),
    289         kind: ProjectionKind::OriginalUnissued(reason),
    290     };
    291     let value = receipt(input, &frame.header, &original, reason)?;
    292     let retained = Retained {
    293         frame,
    294         value: Box::new(value),
    295         projection,
    296     };
    297     retained.confirm(connection).await?;
    298     Ok(Some(retained))
    299 }
    300 pub(in crate::workspace::stock) async fn lookup(
    301     connection: &mut SqliteConnection,
    302     input: &AttachmentInput,
    303     crypto: &WorkspaceCrypto,
    304     operation: OperationId,
    305     recipient: PublicKey,
    306 ) -> Result<Option<Retained>, OperationError> {
    307     let entry:Option<Vec<u8>>=sqlx::query_scalar("SELECT CASE WHEN length(entry_id)=32 THEN entry_id END FROM stock_original_unissued WHERE actor=? AND operation_id=? AND recipient=?")
    308         .bind(input.participant().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(recipient.as_bytes().as_slice())
    309         .fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?;
    310     let Some(entry) = entry else { return Ok(None) };
    311     let retained = Box::pin(read_entry(
    312         connection,
    313         input,
    314         crypto,
    315         OperationId::from_bytes(
    316             entry
    317                 .try_into()
    318                 .map_err(|_| OperationError::RecoveryRequired)?,
    319         ),
    320     ))
    321     .await?
    322     .ok_or(OperationError::RecoveryRequired)?;
    323     if retained.value.attempt.operation_id() != operation || retained.value.recipient != recipient {
    324         return Err(OperationError::RecoveryRequired);
    325     }
    326     Ok(Some(retained))
    327 }
    328 pub(in crate::workspace) async fn capture(
    329     turn: &mut Turn<'_>,
    330     request: Request,
    331     proof: AttachmentProof,
    332 ) -> Result<StockUnissuedOutcome, OperationError> {
    333     if *turn.uncertain {
    334         return Err(OperationError::RecoveryRequired);
    335     }
    336     turn.namespace.validate()?;
    337     let input = request.binding.input();
    338     if !SellerAuthoritySelection::from_attachment(turn.selected).matches_attachment(input) {
    339         return Err(OperationError::Unauthorized);
    340     }
    341     let (authority, record, root, grant) =
    342         super::super::read(turn.connection, input, turn.crypto).await?;
    343     if !matches!(authority.catalog, 14..=20) {
    344         return Err(OperationError::UnsupportedOperation);
    345     }
    346     record.authenticate_retained_capture(input, &proof)?;
    347     let original = Box::pin(claim::read_entry(
    348         turn.connection,
    349         input,
    350         turn.crypto,
    351         OperationId::from_bytes(*request.claim.as_bytes()),
    352     ))
    353     .await?
    354     .ok_or(OperationError::RecoveryRequired)?;
    355     if original.frame.header.actor != request.binding.actor()
    356         || original.report.attempt().operation_id() != request.operation
    357         || original.report.attempt().command_digest() != request.digest
    358         || original.report.recipient() != request.recipient
    359         || original.report.binding().digest() != &request.intent
    360     {
    361         return Err(OperationError::InvalidEvidence);
    362     }
    363     decode_reason(request.reason)?;
    364     let before = authority
    365         .inventory
    366         .ok_or(OperationError::RecoveryRequired)?;
    367     let witness = Box::pin(checkpoint::authenticate_minimum(
    368         turn.connection,
    369         turn.selected,
    370         turn.crypto,
    371         &request.binding,
    372         &authority,
    373         InventoryCheckpointRef::from_host_metadata(
    374             input.authority(),
    375             Sequence::new(0).map_err(|_| WorkspaceError::InvalidInput)?,
    376             None,
    377         )?,
    378     ))
    379     .await?;
    380     let existing = Box::pin(lookup(
    381         turn.connection,
    382         input,
    383         turn.crypto,
    384         request.operation,
    385         request.recipient,
    386     ))
    387     .await?;
    388     let (frame, updated_root, value) = if let Some(retained) = &existing {
    389         if retained.value.claim != request.claim
    390             || retained.value.reason != decode_reason(request.reason)?
    391         {
    392             return Err(OperationError::RecoveryRequired);
    393         }
    394         (None, None, *retained.value)
    395     } else {
    396         let entry = OperationId::from_bytes(super::super::super::random()?);
    397         let transaction = TransactionId::from_bytes(super::super::super::random()?);
    398         let revision = Sequence::new(
    399             before
    400                 .revision
    401                 .get()
    402                 .checked_add(1)
    403                 .ok_or(WorkspaceError::Capacity)?,
    404         )
    405         .map_err(|_| WorkspaceError::Capacity)?;
    406         let body = body(&original, request.reason);
    407         let mut header = ledger::Header {
    408             version: 5,
    409             family: ledger::Family::OriginalUnissued,
    410             namespace: SellerAuthoritySelection::from_attachment(turn.selected),
    411             actor: original.frame.header.actor,
    412             operation: entry,
    413             digest: original.frame.header.digest,
    414             transaction,
    415             revision,
    416             previous: before.head,
    417             head: CheckpointDigest::from_bytes([0; 32]),
    418             pool: None,
    419             order: original.frame.header.order,
    420             related_operation: original.frame.header.related_operation,
    421             subject_grant: None,
    422             bytes: 0,
    423             parts: 0,
    424             body_digest: [0; 32],
    425         };
    426         header.head = head(&header, &body);
    427         let value = receipt(input, &header, &original, request.reason)?;
    428         let mut next = authority.clone();
    429         next.inventory = Some(InventoryCheckpoint {
    430             revision,
    431             head: Some(header.head),
    432             ..before
    433         });
    434         let frame = ledger::prepare(turn.crypto, input, header, &body).await?;
    435         let updated = turn
    436             .crypto
    437             .seal_stock_root(input, next.catalog, &next.encode()?)
    438             .await?;
    439         (Some(frame), Some(updated), value)
    440     };
    441     let mut tx = turn
    442         .connection
    443         .begin_with("BEGIN IMMEDIATE")
    444         .await
    445         .map_err(|_| OperationError::StorageFailure)?;
    446     let changed:Result<(),OperationError>=async {
    447         turn.namespace.validate()?;
    448         super::super::unchanged(&mut tx,input,authority.catalog,&root,&grant).await?;
    449         record.authenticate_retained_capture(input,&proof)?;
    450         witness.confirm(&mut tx).await?;original.confirm(&mut tx).await?;
    451         if let Some(retained)=&existing {retained.confirm(&mut tx).await?;}
    452         if let Some(frame)=&frame {
    453             frame.insert_record(&mut tx).await?;
    454             sqlx::query("INSERT INTO stock_original_unissued(actor,operation_id,recipient,reason,entry_id) VALUES(?,?,?,?,?)")
    455                 .bind(input.participant().as_bytes().as_slice()).bind(request.operation.as_bytes().as_slice())
    456                 .bind(request.recipient.as_bytes().as_slice()).bind(i64::from(request.reason))
    457                 .bind(frame.header.operation.as_bytes().as_slice()).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?;
    458             let updated=sqlx::query("UPDATE stock_authority SET protected=? WHERE singleton=1 AND protected=?")
    459                 .bind(updated_root.as_ref().ok_or(OperationError::RecoveryRequired)?).bind(&root)
    460                 .execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?;
    461             if updated.rows_affected()!=1 {return Err(OperationError::RecoveryRequired);}
    462         }
    463         turn.namespace.validate()?;Ok(())
    464     }.await;
    465     if let Err(error) = changed {
    466         if tx.rollback().await.is_err() {
    467             *turn.uncertain = true;
    468             return Ok(StockUnissuedOutcome::Unknown(value.attempt));
    469         }
    470         return Err(error);
    471     }
    472     let done = if frame.is_some() {
    473         tx.commit().await
    474     } else {
    475         tx.rollback().await
    476     };
    477     if done.is_err() {
    478         *turn.uncertain = true;
    479         return Ok(StockUnissuedOutcome::Unknown(value.attempt));
    480     }
    481     Ok(StockUnissuedOutcome::Committed(Box::new(value)))
    482 }
    483 pub(in crate::workspace) async fn read(
    484     turn: &mut Turn<'_>,
    485     request: StockClaimRequest,
    486     proof: AttachmentProof,
    487 ) -> Result<Option<StockUnissuedReceipt>, OperationError> {
    488     let auth = super::super::signing_plan::load(
    489         turn,
    490         &request.binding,
    491         request.minimum,
    492         request.operation,
    493         request.digest,
    494         &proof,
    495     )
    496     .await?;
    497     if !matches!(auth.access.authority.catalog, 14..=20) {
    498         return Err(OperationError::UnsupportedOperation);
    499     }
    500     let witness = Box::pin(checkpoint::authenticate_minimum(
    501         turn.connection,
    502         turn.selected,
    503         turn.crypto,
    504         &auth.access.current,
    505         &auth.access.authority,
    506         InventoryCheckpointRef::from_host_metadata(
    507             turn.selected.authority(),
    508             Sequence::new(0).map_err(|_| WorkspaceError::InvalidInput)?,
    509             None,
    510         )?,
    511     ))
    512     .await?;
    513     let retained = Box::pin(lookup(
    514         turn.connection,
    515         turn.selected,
    516         turn.crypto,
    517         request.operation,
    518         request.recipient,
    519     ))
    520     .await?;
    521     let mut tx = turn
    522         .connection
    523         .begin_with("BEGIN IMMEDIATE")
    524         .await
    525         .map_err(|_| OperationError::StorageFailure)?;
    526     let checked: Result<(), OperationError> = async {
    527         witness.confirm(&mut tx).await?;
    528         if let Some(value) = &retained {
    529             value.confirm(&mut tx).await?;
    530         }
    531         auth.confirm(&mut tx, turn.namespace, turn.clock, &proof, false)
    532             .await?;
    533         Ok(())
    534     }
    535     .await;
    536     if tx.rollback().await.is_err() {
    537         *turn.uncertain = true;
    538         return Err(OperationError::RecoveryRequired);
    539     }
    540     checked?;
    541     Ok(retained.map(|v| *v.value))
    542 }
    543 impl super::super::NativeWorkspace {
    544     /// Borrows the actual owned original observation. Failed/uncertain writes
    545     /// leave that observation available; no new issuance or stock effect occurs.
    546     pub async fn capture_stock_original_unissued(
    547         &self,
    548         binding: WorkspaceBinding,
    549         observation: &StockUnissuedInvocation,
    550         proof: &AttachmentProof,
    551     ) -> Result<StockUnissuedOutcome, OperationError> {
    552         self.worker
    553             .capture_stock_original_unissued(
    554                 Request::from_observation(binding, observation)?,
    555                 proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?,
    556                 false,
    557             )
    558             .await
    559     }
    560     /// Reconciles only original material on this namespace's retained owner.
    561     pub async fn reconcile_stock_original_unissued(
    562         &self,
    563         binding: WorkspaceBinding,
    564         observation: &StockUnissuedInvocation,
    565         proof: &AttachmentProof,
    566     ) -> Result<StockUnissuedOutcome, OperationError> {
    567         self.worker
    568             .capture_stock_original_unissued(
    569                 Request::from_observation(binding, observation)?,
    570                 proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?,
    571                 true,
    572             )
    573             .await
    574     }
    575     /// Reads the authenticated original invocation fact; never a release permit.
    576     pub async fn stock_original_unissued(
    577         &self,
    578         request: StockClaimRequest,
    579         proof: &AttachmentProof,
    580     ) -> Result<Option<StockUnissuedReceipt>, OperationError> {
    581         self.worker
    582             .stock_original_unissued(
    583                 request,
    584                 proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?,
    585             )
    586             .await
    587     }
    588 }