lib

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

acceptance.rs (34808B)


      1 //! Native T0: retained command, complete preparatory holds and one order fence.
      2 //! This boundary performs no signing, installation, delivery or physical claim.
      3 use super::super::{consent, ledger, source};
      4 use super::*;
      5 use radroots_domain::{CheckpointRef, OrderId, RecordId, TermsDigest};
      6 use radroots_protocol::command::CapturedStockCommitment;
      7 use radroots_storage::inventory::InventoryCheckpointRef;
      8 use radroots_storage::workspace::seller_stock::{
      9     StockListingCheckpointRef, StockSourceCheckpointRef,
     10 };
     11 use std::collections::{BTreeMap, BTreeSet};
     12 pub(in crate::workspace::stock) mod codec;
     13 mod plan;
     14 pub(super) mod replacement;
     15 
     16 #[derive(Serialize, Deserialize)]
     17 #[serde(deny_unknown_fields)]
     18 struct Body<'a> {
     19     version: u8,
     20     #[serde(borrow)]
     21     command: &'a RawValue,
     22     #[serde(borrow)]
     23     terms: &'a RawValue,
     24     #[serde(default, borrow, skip_serializing_if = "Option::is_none")]
     25     original_request: Option<&'a RawValue>,
     26     #[serde(borrow, deserialize_with = "super::super::required_nullable")]
     27     original_quote: Option<&'a RawValue>,
     28     #[serde(
     29         default,
     30         borrow,
     31         skip_serializing_if = "Option::is_none",
     32         deserialize_with = "super::super::optional_present"
     33     )]
     34     replacement: Option<replacement::Basis<'a>>,
     35     #[serde(deserialize_with = "super::super::required_nullable")]
     36     seller_author_head: Option<RecordId>,
     37     seller_author_sequence: Sequence,
     38     minimum_revision: Sequence,
     39     #[serde(deserialize_with = "super::super::required_nullable")]
     40     minimum_head: Option<CheckpointDigest>,
     41     authorization: StockAuthorizationRef,
     42     source_minimum: Progress,
     43     listing_minimum: Progress,
     44     coverage: CheckpointRef,
     45     buyer_head: Option<RecordId>,
     46     observed_at: UnixSeconds,
     47     expires: UnixSeconds,
     48     issue_before: UnixSeconds,
     49     consent: OperationId,
     50     mappings: Vec<radroots_domain::stock::OptionPoolMapping>,
     51     pools: Vec<PoolSnapshot>,
     52     allocations: Vec<plan::Allocation>,
     53     effects: Vec<plan::Effect>,
     54     movements: Vec<[u8; 32]>,
     55 }
     56 #[derive(Serialize, Deserialize)]
     57 #[serde(deny_unknown_fields)]
     58 struct Progress {
     59     authority: radroots_domain::AuthorityRef,
     60     revision: Sequence,
     61     #[serde(deserialize_with = "super::super::required_nullable")]
     62     head: Option<CheckpointDigest>,
     63     authorization: StockAuthorizationRef,
     64 }
     65 impl Progress {
     66     fn source(value: StockSourceCheckpointRef) -> Result<Self, OperationError> {
     67         Ok(Self {
     68             authority: value.authority(),
     69             revision: value.revision(),
     70             head: value.head(),
     71             authorization: value
     72                 .authorization()
     73                 .ok_or(OperationError::RecoveryRequired)?,
     74         })
     75     }
     76     fn listing(value: StockListingCheckpointRef) -> Result<Self, OperationError> {
     77         Ok(Self {
     78             authority: value.authority(),
     79             revision: value.revision(),
     80             head: value.head(),
     81             authorization: value
     82                 .authorization()
     83                 .ok_or(OperationError::RecoveryRequired)?,
     84         })
     85     }
     86 }
     87 #[derive(Serialize, Deserialize, Eq, PartialEq)]
     88 #[serde(deny_unknown_fields)]
     89 struct Fence {
     90     version: u8,
     91     order: OrderId,
     92     operation: OperationId,
     93     digest: CommandDigest,
     94     transaction: TransactionId,
     95     revision: Sequence,
     96     request: RecordId,
     97     terms: TermsDigest,
     98 }
     99 fn fence(
    100     header: &ledger::Header,
    101     command: &CapturedStockCommitment,
    102 ) -> Result<Fence, OperationError> {
    103     Ok(Fence {
    104         version: 1,
    105         order: header.order.ok_or(OperationError::RecoveryRequired)?,
    106         operation: header.operation,
    107         digest: header.digest,
    108         transaction: header.transaction,
    109         revision: Sequence::new(1).map_err(|_| OperationError::RecoveryRequired)?,
    110         request: command.authorization(),
    111         terms: command.terms_digest(),
    112     })
    113 }
    114 fn bytes(value: &impl Serialize) -> Result<zeroize::Zeroizing<Vec<u8>>, OperationError> {
    115     let bytes = zeroize::Zeroizing::new(
    116         serde_json::to_vec(value).map_err(|_| OperationError::StorageFailure)?,
    117     );
    118     if bytes.is_empty() || bytes.len() > ledger::BODY_MAX_BYTES {
    119         return Err(WorkspaceError::Capacity.into());
    120     }
    121     Ok(bytes)
    122 }
    123 fn head(header: &ledger::Header, body: &[u8]) -> CheckpointDigest {
    124     let mut h = Sha256::new();
    125     h.update(b"radroots.seller_stock.acceptance_chain.v1\0");
    126     h.update(header.namespace.workspace_id().as_bytes());
    127     h.update(header.namespace.authority().executor_id().as_bytes());
    128     h.update(
    129         header
    130             .namespace
    131             .authority()
    132             .generation()
    133             .get()
    134             .to_be_bytes(),
    135     );
    136     h.update(header.namespace.route_digest().as_bytes());
    137     h.update([u8::from(header.previous.is_some())]);
    138     h.update(
    139         header
    140             .previous
    141             .map(|value| *value.as_bytes())
    142             .unwrap_or([0; 32]),
    143     );
    144     h.update(header.revision.get().to_be_bytes());
    145     h.update(header.actor.participant().as_bytes());
    146     h.update(
    147         header
    148             .actor
    149             .grant_id()
    150             .map(|value| *value.as_bytes())
    151             .unwrap_or([0; 32]),
    152     );
    153     h.update(header.operation.as_bytes());
    154     h.update(header.digest.as_bytes());
    155     h.update(header.transaction.as_bytes());
    156     h.update(Sha256::digest(body));
    157     CheckpointDigest::from_bytes(h.finalize().into())
    158 }
    159 pub(in crate::workspace::stock) fn check_consent(
    160     access: &Access,
    161     scope: &consent::Retained,
    162     command: &CapturedStockCommitment,
    163     fresh: bool,
    164     at: UnixSeconds,
    165 ) -> Result<(), OperationError> {
    166     if scope.command.digest() != command.digest() {
    167         return Err(OperationError::IdempotencyConflict);
    168     }
    169     if scope.subject != access.current.input().grant_id()
    170         || scope.authorization
    171             != access
    172                 .authority
    173                 .authorization
    174                 .ok_or(OperationError::RecoveryRequired)?
    175         || scope.subject_digest != <[u8; 32]>::from(Sha256::digest(&access.grant))
    176         || (fresh && scope.mode != consent::StockConsentMode::ExecuteAndRecover)
    177     {
    178         return Err(OperationError::Unauthorized);
    179     }
    180     if at >= scope.expires {
    181         return Err(OperationError::DeadlineExceeded);
    182     }
    183     if fresh {
    184         if command.context().actor() != access.current.actor() {
    185             return Err(OperationError::Unauthorized);
    186         }
    187         if at >= command.context().not_after()
    188             || command
    189                 .context()
    190                 .approval()
    191                 .is_none_or(|approval| at >= approval.expires_at())
    192         {
    193             return Err(OperationError::DeadlineExceeded);
    194         }
    195     }
    196     Ok(())
    197 }
    198 pub(in crate::workspace::stock) async fn current_consent(
    199     turn: &mut Turn<'_>,
    200     access: &Access,
    201     command: &CapturedStockCommitment,
    202 ) -> Result<(consent::Retained, MinimumProof), OperationError> {
    203     let operation = consent::natural(
    204         turn.connection,
    205         turn.selected.participant(),
    206         command.context().operation_id(),
    207         access.current.input().grant_id(),
    208     )
    209     .await?;
    210     let retained = if let Some(operation) = operation {
    211         consent::read(
    212             turn.connection,
    213             turn.selected,
    214             turn.crypto,
    215             access.authority.input.grant_id(),
    216             operation,
    217         )
    218         .await?
    219     } else {
    220         None
    221     };
    222     let proof = checkpoint::authenticate_identity(
    223         turn.connection,
    224         turn.selected,
    225         turn.crypto,
    226         &access.current,
    227         &access.authority,
    228         checkpoint::IdentityTarget::Consent {
    229             operation: command.context().operation_id(),
    230             subject: access.current.input().grant_id(),
    231             expected: retained.as_ref().map(consent::Retained::identity),
    232         },
    233     )
    234     .await?;
    235     Ok((retained.ok_or(OperationError::Unauthorized)?, proof))
    236 }
    237 
    238 /// Preserves one original operation across lost observers and store reopen.
    239 pub(in crate::workspace) async fn admit(
    240     turn: &mut Turn<'_>,
    241     request: StockAcceptanceRequest,
    242     proof: AttachmentProof,
    243 ) -> Result<StockAcceptanceOutcome, OperationError> {
    244     let access = turn
    245         .access(request.binding(), request.minimum_checkpoint(), &proof)
    246         .await?;
    247     if !matches!(access.authority.catalog, 9..=20) {
    248         return Err(OperationError::UnsupportedOperation);
    249     }
    250     let command = request.command();
    251     // This retained preparation format describes an initial acceptance only.
    252     // Capturing a replacement never grants the initial request path authority.
    253     if command.proposal().is_some() && access.authority.catalog < 20 {
    254         return Err(OperationError::UnsupportedOperation);
    255     }
    256     let operation = command.context().operation_id();
    257     let original = codec::read(turn.connection, turn.selected, turn.crypto, operation).await?;
    258     let identity = checkpoint::authenticate_identity(
    259         turn.connection,
    260         turn.selected,
    261         turn.crypto,
    262         &access.current,
    263         &access.authority,
    264         checkpoint::IdentityTarget::Operation(
    265             operation,
    266             original.as_ref().map(|value| value.identity()),
    267         ),
    268     )
    269     .await?;
    270     let (consent, consent_proof) = current_consent(turn, &access, command).await?;
    271     check_consent(
    272         &access,
    273         &consent,
    274         command,
    275         original.is_none(),
    276         access.current.observed_at(),
    277     )?;
    278     if let Some(original) = original {
    279         if original.frame.header.digest != command.digest() {
    280             return Err(OperationError::IdempotencyConflict);
    281         }
    282         for pool in original.receipt.held_pools() {
    283             if !consent.resources.contains(pool.id()) {
    284                 return Err(OperationError::Unauthorized);
    285             }
    286         }
    287         let aborted = if access.authority.catalog >= 13 {
    288             Some(Box::pin(super::abort::existing(turn, &access, operation)).await?)
    289         } else {
    290             None
    291         };
    292         let mut tx = turn
    293             .connection
    294             .begin_with("BEGIN IMMEDIATE")
    295             .await
    296             .map_err(|_| OperationError::StorageFailure)?;
    297         let checked: Result<(), OperationError> = async {
    298             identity.confirm(&mut tx).await?;
    299             consent_proof.confirm(&mut tx).await?;
    300             original.confirm(&mut tx).await?;
    301             if let Some((retained, witness)) = &aborted {
    302                 witness.confirm(&mut tx).await?;
    303                 if let Some(retained) = retained {
    304                     retained.confirm(&mut tx).await?;
    305                 }
    306             }
    307             let current = access
    308                 .confirm(&mut tx, turn.namespace, turn.clock, &proof)
    309                 .await?;
    310             check_consent(&access, &consent, command, false, current.observed_at())?;
    311             Ok(())
    312         }
    313         .await;
    314         if tx.rollback().await.is_err() {
    315             *turn.uncertain = true;
    316             return Err(OperationError::RecoveryRequired);
    317         }
    318         checked?;
    319         if let Some((Some(aborted), _)) = aborted {
    320             return Ok(StockAcceptanceOutcome::Aborted(Box::new(aborted.receipt)));
    321         }
    322         return Ok(StockAcceptanceOutcome::Prepared(Box::new(original.receipt)));
    323     }
    324     // All fresh source/mapping/pool planning follows original identity recovery.
    325     super::super::check_source_counts(
    326         turn.connection,
    327         access
    328             .authority
    329             .sources
    330             .ok_or(OperationError::RecoveryRequired)?,
    331     )
    332     .await?;
    333     if request.source_checkpoint().authorization() != access.authority.authorization {
    334         return Err(WorkspaceError::StaleCheckpoint.into());
    335     }
    336     let source_minimum = source::checkpoint::authenticate(
    337         turn.connection,
    338         turn.selected,
    339         turn.crypto,
    340         access
    341             .authority
    342             .sources
    343             .ok_or(OperationError::RecoveryRequired)?,
    344         source::checkpoint::Target::Minimum(request.source_checkpoint()),
    345     )
    346     .await?;
    347     let base = if command.proposal().is_some() {
    348         Some(Box::pin(replacement::load(turn, &access, command)).await?)
    349     } else {
    350         None
    351     };
    352     let inventory_read = source::history::InventoryRead {
    353         binding: &access.current,
    354         authority: &access.authority,
    355         minimum: request.minimum_checkpoint(),
    356     };
    357     let admitted = if let (CapturedStockCommitment::TermsInstallation(command), Some(base)) =
    358         (command, base.as_ref())
    359     {
    360         Box::pin(source::request::prepare_terms(
    361             turn.connection,
    362             turn.selected,
    363             turn.crypto,
    364             inventory_read,
    365             source::request::ReplacementSource {
    366                 command,
    367                 base: &base.record,
    368             },
    369             request.listing_checkpoint(),
    370             access.current.observed_at(),
    371         ))
    372         .await?
    373     } else {
    374         source::request::prepare(
    375             turn.connection,
    376             turn.selected,
    377             turn.crypto,
    378             inventory_read,
    379             command.authorization(),
    380             request.listing_checkpoint(),
    381             access.current.observed_at(),
    382         )
    383         .await?
    384     };
    385     let expected = command
    386         .context()
    387         .expected()
    388         .ok_or(OperationError::InvalidCommand)?;
    389     if expected.order_id() != admitted.scope.order_id()
    390         || (base.is_none()
    391             && (expected.agreement().is_some() || expected.seller_sequence().get() != 0))
    392         || expected.buyer_head() != admitted.history.analysis.buyer_head()
    393         || Some(expected.checkpoint()) != admitted.history.checkpoint.as_ref()
    394         || command.terms_digest() != admitted.digest
    395         || command.context().workspace_id() != turn.selected.workspace_id()
    396         || command.context().authority() != turn.selected.authority()
    397         || command.context().route_digest() != turn.selected.route_digest()
    398     {
    399         return Err(OperationError::StaleState);
    400     }
    401     let current_order = if access.authority.catalog >= 13 {
    402         let checked = Box::pin(checkpoint::authenticate_order_state(
    403             turn.connection,
    404             turn.selected,
    405             turn.crypto,
    406             &access.current,
    407             &access.authority,
    408             expected.order_id(),
    409         ))
    410         .await?;
    411         let stale = match (&base, checked.witness.expected) {
    412             (None, Some(value)) => value.phase != super::super::order_state::Phase::Aborted,
    413             (Some(base), Some(value)) => {
    414                 value.phase == super::super::order_state::Phase::Prepared
    415                     || (value.phase == super::super::order_state::Phase::Installed
    416                         && (value.operation != base.operation || value.entry != base.installation))
    417             }
    418             (Some(_), None) => true,
    419             (None, None) => false,
    420         };
    421         if stale {
    422             return Err(OperationError::StaleState);
    423         }
    424         Some(checked)
    425     } else {
    426         None
    427     };
    428     let order_proof = if current_order.is_none() {
    429         Some(
    430             checkpoint::authenticate_order_absence(
    431                 turn.connection,
    432                 turn.selected,
    433                 turn.crypto,
    434                 &access.current,
    435                 &access.authority,
    436                 expected.order_id(),
    437             )
    438             .await?,
    439         )
    440     } else {
    441         None
    442     };
    443     let mut mappings = Vec::new();
    444     let mut mapping_reads = Vec::new();
    445     let mut pool_ids = BTreeSet::new();
    446     let old_terms = base
    447         .as_ref()
    448         .map(|base| base.preparation.terms())
    449         .transpose()?;
    450     let old_mappings = base
    451         .as_ref()
    452         .map(|base| base.preparation.mappings())
    453         .transpose()?
    454         .unwrap_or_default();
    455     if let Some(base) = &base {
    456         pool_ids.extend(base.originals.iter().map(|draw| draw.allocation.pool_id()));
    457     }
    458     if matches!(
    459         admitted.terms()?.supply(),
    460         radroots_domain::SupplyCommitment::StockBacked
    461     ) {
    462         for line in admitted.terms()?.lines() {
    463             if let Some(old) = old_terms
    464                 .as_ref()
    465                 .and_then(|terms| terms.lines().iter().find(|old| old.id() == line.id()))
    466             {
    467                 if old.source().coordinate() != line.source().coordinate()
    468                     || old.option_id() != line.option_id()
    469                 {
    470                     return Err(OperationError::UnsupportedOperation);
    471                 }
    472                 let key = radroots_domain::stock::OptionMappingKey::new(
    473                     old.source().coordinate(),
    474                     old.option_id(),
    475                 );
    476                 if let Some(mapping) = old_mappings.iter().find(|mapping| mapping.key() == key) {
    477                     pool_ids.insert(mapping.pool_id());
    478                     mappings.push(*mapping);
    479                     continue;
    480                 }
    481             }
    482             let key = radroots_domain::stock::OptionMappingKey::new(
    483                 line.source().coordinate(),
    484                 line.option_id(),
    485             );
    486             let retained = mapping::read(turn.connection, turn.selected, turn.crypto, key).await?;
    487             let witness = checkpoint::authenticate_mapping_projection(
    488                 turn.connection,
    489                 turn.selected,
    490                 turn.crypto,
    491                 &access.current,
    492                 &access.authority,
    493                 key,
    494                 retained.as_ref().map(|value| value.value),
    495             )
    496             .await?;
    497             let value = retained.as_ref().ok_or(OperationError::StaleState)?.value;
    498             pool_ids.insert(value.pool_id());
    499             mappings.push(value);
    500             mapping_reads.push(mapping::MappingRead {
    501                 key,
    502                 retained,
    503                 proof: witness,
    504             });
    505         }
    506         if let Some(explicit) = command.allocation().explicit_allocations() {
    507             pool_ids.extend(explicit.iter().map(|value| value.pool_id()));
    508         }
    509     }
    510     let mut pool_reads = BTreeMap::new();
    511     let mut pool_proofs = Vec::new();
    512     let mut before_pools = Vec::new();
    513     for id in pool_ids {
    514         if !consent.resources.contains(id) {
    515             return Err(OperationError::Unauthorized);
    516         }
    517         let retained = read_pool(turn.connection, turn.selected, turn.crypto, id).await?;
    518         pool_proofs.push(
    519             checkpoint::authenticate_projection(
    520                 turn.connection,
    521                 turn.selected,
    522                 turn.crypto,
    523                 &access.current,
    524                 &access.authority,
    525                 id,
    526                 retained.as_ref().map(|value| value.pool),
    527             )
    528             .await?,
    529         );
    530         let retained = retained.ok_or(OperationError::StaleState)?;
    531         before_pools.push(retained.pool);
    532         pool_reads.insert(id, retained);
    533     }
    534     let replacement::Resolution {
    535         allocations,
    536         effects,
    537         desired,
    538         releases,
    539     } = if let Some(base) = &base {
    540         replacement::resolve(
    541             admitted.terms()?,
    542             command,
    543             &mappings,
    544             &before_pools,
    545             &base.originals,
    546         )?
    547     } else {
    548         let (allocations, effects) =
    549             plan::resolve(admitted.terms()?, command, &mappings, &before_pools)?;
    550         replacement::Resolution {
    551             allocations,
    552             effects,
    553             desired: Vec::new(),
    554             releases: Vec::new(),
    555         }
    556     };
    557     let before = access
    558         .authority
    559         .inventory
    560         .ok_or(OperationError::RecoveryRequired)?;
    561     let transaction = TransactionId::from_bytes(super::super::super::random()?);
    562     let revision = Sequence::new(
    563         before
    564             .revision
    565             .get()
    566             .checked_add(1)
    567             .ok_or(WorkspaceError::Capacity)?,
    568     )
    569     .map_err(|_| WorkspaceError::Capacity)?;
    570     let expires = admitted
    571         .expires
    572         .min(command.context().not_after())
    573         .min(consent.expires)
    574         .min(
    575             command
    576                 .context()
    577                 .approval()
    578                 .ok_or(OperationError::UnverifiedApproval)?
    579                 .expires_at(),
    580         )
    581         .min(access.current.expires_at());
    582     let issue_before = UnixSeconds::new(
    583         access
    584             .current
    585             .observed_at()
    586             .get()
    587             .checked_add(120)
    588             .ok_or(WorkspaceError::Capacity)?,
    589     )
    590     .map_err(|_| WorkspaceError::Capacity)?
    591     .min(expires);
    592     let mut movements = Vec::new();
    593     for _ in &effects {
    594         movements.push(super::super::super::random()?);
    595     }
    596     let terms = radroots_protocol::terms::EncodedTerms::capture(admitted.terms()?)
    597         .map_err(|_| OperationError::InvalidEvidence)?;
    598     let original_request = if base.is_none() {
    599         Some(replacement::encoded(
    600             &admitted.history.records,
    601             admitted.authorization,
    602         )?)
    603     } else {
    604         None
    605     };
    606     let replacement_records = admitted
    607         .replacement
    608         .map(|selected| {
    609             Ok::<_, OperationError>([
    610                 replacement::encoded(&admitted.history.records, selected.base_agreement())?,
    611                 replacement::encoded(&admitted.history.records, selected.proposal())?,
    612                 replacement::encoded(&admitted.history.records, selected.authorization())?,
    613             ])
    614         })
    615         .transpose()?;
    616     let original_quote = admitted
    617         .quote
    618         .map(|id| {
    619             radroots_protocol::commerce::EncodedRecord::capture(
    620                 admitted
    621                     .history
    622                     .records
    623                     .get(&id)
    624                     .ok_or(OperationError::RecoveryRequired)?
    625                     .content(),
    626             )
    627             .map_err(|_| OperationError::RecoveryRequired)
    628         })
    629         .transpose()?;
    630     let seller_author_head = admitted.history.analysis.seller_head();
    631     let seller_author_sequence = seller_author_head
    632         .map(|id| {
    633             admitted
    634                 .history
    635                 .records
    636                 .get(&id)
    637                 .map(|record| record.content().header().author_sequence())
    638                 .ok_or(OperationError::RecoveryRequired)
    639         })
    640         .transpose()?
    641         .unwrap_or(Sequence::new(0).map_err(|_| OperationError::RecoveryRequired)?);
    642     let body = Body {
    643         version: if base.is_some() { 2 } else { 1 },
    644         command: serde_json::from_slice(command.protected_wire())
    645             .map_err(|_| OperationError::InvalidCommand)?,
    646         terms: serde_json::from_slice(terms.protected_wire())
    647             .map_err(|_| OperationError::InvalidEvidence)?,
    648         original_request: original_request
    649             .as_ref()
    650             .map(|record| {
    651                 serde_json::from_slice(record.protected_wire())
    652                     .map_err(|_| OperationError::RecoveryRequired)
    653             })
    654             .transpose()?,
    655         original_quote: original_quote
    656             .as_ref()
    657             .map(|quote| {
    658                 serde_json::from_slice(quote.protected_wire())
    659                     .map_err(|_| OperationError::RecoveryRequired)
    660             })
    661             .transpose()?,
    662         replacement: match (base, replacement_records.as_ref()) {
    663             (Some(base), Some(records)) => Some(replacement::Basis {
    664                 base_operation: base.operation,
    665                 base_installation: base.installation,
    666                 base: serde_json::from_slice(records[0].protected_wire())
    667                     .map_err(|_| OperationError::RecoveryRequired)?,
    668                 proposal: serde_json::from_slice(records[1].protected_wire())
    669                     .map_err(|_| OperationError::RecoveryRequired)?,
    670                 authorization: serde_json::from_slice(records[2].protected_wire())
    671                     .map_err(|_| OperationError::RecoveryRequired)?,
    672                 originals: base.originals,
    673                 desired,
    674                 releases,
    675             }),
    676             (None, None) => None,
    677             _ => return Err(OperationError::RecoveryRequired),
    678         },
    679         seller_author_head,
    680         seller_author_sequence,
    681         minimum_revision: request.minimum_checkpoint().revision(),
    682         minimum_head: request.minimum_checkpoint().head(),
    683         authorization: access
    684             .authority
    685             .authorization
    686             .ok_or(OperationError::RecoveryRequired)?,
    687         source_minimum: Progress::source(request.source_checkpoint())?,
    688         listing_minimum: Progress::listing(request.listing_checkpoint())?,
    689         coverage: expected.checkpoint().clone(),
    690         buyer_head: expected.buyer_head(),
    691         observed_at: access.current.observed_at(),
    692         expires,
    693         issue_before,
    694         consent: consent.frame.header.operation,
    695         mappings,
    696         pools: before_pools,
    697         allocations,
    698         effects,
    699         movements,
    700     };
    701     let raw = bytes(&body)?;
    702     let mut header = ledger::Header {
    703         version: 5,
    704         family: ledger::Family::Acceptance,
    705         namespace: SellerAuthoritySelection::from_attachment(turn.selected),
    706         actor: command.context().actor(),
    707         operation,
    708         digest: command.digest(),
    709         transaction,
    710         revision,
    711         previous: before.head,
    712         head: CheckpointDigest::from_bytes([0; 32]),
    713         pool: None,
    714         order: Some(expected.order_id()),
    715         related_operation: None,
    716         subject_grant: None,
    717         bytes: 0,
    718         parts: 0,
    719         body_digest: [0; 32],
    720     };
    721     header.head = head(&header, &raw);
    722     let framed = ledger::prepare(
    723         turn.crypto,
    724         turn.selected,
    725         header_for_prepare(&header),
    726         &raw,
    727     )
    728     .await?;
    729     let fence = fence(&header, command)?;
    730     let order_cipher = turn
    731         .crypto
    732         .seal_stock_record(
    733             turn.selected,
    734             "order",
    735             fence.order.as_bytes(),
    736             &bytes(&fence)?,
    737         )
    738         .await?;
    739     let mut changed_pools = Vec::new();
    740     let mut changed_movements = Vec::new();
    741     for (effect, movement) in body.effects.iter().zip(&body.movements) {
    742         let original = &pool_reads[&effect.before().id()];
    743         changed_pools.push(
    744             turn.crypto
    745                 .seal_stock_record(
    746                     turn.selected,
    747                     "pool",
    748                     effect.after().id().as_bytes(),
    749                     &encode(&PoolWire {
    750                         version: 1,
    751                         label: original.view.label(),
    752                         pool: effect.after(),
    753                     })?,
    754                 )
    755                 .await?,
    756         );
    757         changed_movements.push(
    758             turn.crypto
    759                 .seal_stock_record(
    760                     turn.selected,
    761                     "acceptance_movement",
    762                     movement,
    763                     &bytes(&codec::Hold {
    764                         version: 1,
    765                         operation,
    766                         digest: command.digest(),
    767                         order: fence.order,
    768                         effect: *effect,
    769                     })?,
    770                 )
    771                 .await?,
    772         );
    773     }
    774     let mut next = access.authority.clone();
    775     next.inventory = Some(InventoryCheckpoint {
    776         revision,
    777         head: Some(header.head),
    778         orders: Some(
    779             Sequence::new(
    780                 before
    781                     .orders
    782                     .ok_or(OperationError::RecoveryRequired)?
    783                     .get()
    784                     .checked_add(1)
    785                     .ok_or(WorkspaceError::Capacity)?,
    786             )
    787             .map_err(|_| WorkspaceError::Capacity)?,
    788         ),
    789         movements: Sequence::new(
    790             before
    791                 .movements
    792                 .get()
    793                 .checked_add(body.effects.len() as u64)
    794                 .ok_or(WorkspaceError::Capacity)?,
    795         )
    796         .map_err(|_| WorkspaceError::Capacity)?,
    797         ..before
    798     });
    799     let root = turn
    800         .crypto
    801         .seal_stock_root(turn.selected, next.catalog, &next.encode()?)
    802         .await?;
    803     let receipt = codec::receipt(turn.selected, &header, &body, command)?;
    804     let mut tx = turn
    805         .connection
    806         .begin_with("BEGIN IMMEDIATE")
    807         .await
    808         .map_err(|_| OperationError::StorageFailure)?;
    809     let changed: Result<(), OperationError> = async {
    810         identity.confirm(&mut tx).await?; consent_proof.confirm(&mut tx).await?; source_minimum.confirm(&mut tx).await?;
    811         if let Some(order_proof) = &order_proof {order_proof.confirm(&mut tx).await?;} admitted.confirm(&mut tx).await?;
    812         super::super::check_source_counts(&mut tx, access.authority.sources.ok_or(OperationError::RecoveryRequired)?).await?;
    813         for mapping in &mapping_reads { mapping.confirm(&mut tx).await?; }
    814         for witness in &pool_proofs { witness.confirm(&mut tx).await?; }
    815         for retained in pool_reads.values() {
    816             let count: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_pools WHERE pool_id=? AND revision=? AND protected=?").bind(retained.pool.id().as_bytes().as_slice()).bind(retained.pool.version().get() as i64).bind(&retained.protected).fetch_one(&mut *tx).await.map_err(|_| OperationError::RecoveryRequired)?;
    817             if count != 1 { return Err(OperationError::RecoveryRequired); }
    818         }
    819         let current = access.confirm(&mut tx, turn.namespace, turn.clock, &proof).await?;
    820         check_consent(&access, &consent, command, true, current.observed_at())?; admitted.validate_at(current.observed_at())?;
    821         if current.observed_at() >= body.issue_before { return Err(OperationError::DeadlineExceeded); }
    822         if current_order.is_none() {
    823             let count: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_orders WHERE order_id=?").bind(fence.order.as_bytes().as_slice()).fetch_one(&mut *tx).await.map_err(|_| OperationError::StorageFailure)?;
    824             if count != 0 { return Err(OperationError::StaleState); }
    825         }
    826         sqlx::query("INSERT INTO stock_operations(actor,grant_id,operation_id,command_digest,transaction_id,pool_id,revision,chain_head,protected,family,order_id,related_operation,subject_grant) VALUES(?,?,?,?,?,NULL,?,?,?,2,?,NULL,NULL)")
    827             .bind(header.actor.participant().as_bytes().as_slice()).bind(access.current.input().grant_id().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(header.digest.as_bytes().as_slice()).bind(transaction.as_bytes().as_slice()).bind(revision.get() as i64).bind(header.head.as_bytes().as_slice()).bind(&framed.protected).bind(fence.order.as_bytes().as_slice()).execute(&mut *tx).await.map_err(|_| OperationError::StorageFailure)?;
    828         framed.insert_parts(&mut tx, header.actor, operation).await?;
    829         for (index, effect) in body.effects.iter().enumerate() {
    830             let original = &pool_reads[&effect.before().id()];
    831             let updated = sqlx::query("UPDATE stock_pools SET revision=?,protected=? WHERE pool_id=? AND revision=? AND protected=?").bind(effect.after().version().get() as i64).bind(&changed_pools[index]).bind(effect.before().id().as_bytes().as_slice()).bind(effect.before().version().get() as i64).bind(&original.protected).execute(&mut *tx).await.map_err(|_| OperationError::StorageFailure)?;
    832             if updated.rows_affected() != 1 { return Err(OperationError::StaleState); }
    833             sqlx::query("INSERT INTO stock_movements(movement_id,actor,grant_id,operation_id,pool_id,protected) VALUES(?,?,?,?,?,?)").bind(body.movements[index].as_slice()).bind(header.actor.participant().as_bytes().as_slice()).bind(access.current.input().grant_id().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(effect.before().id().as_bytes().as_slice()).bind(&changed_movements[index]).execute(&mut *tx).await.map_err(|_| OperationError::StorageFailure)?;
    834         }
    835         if let Some(current_order) = &current_order {
    836             sqlx::query("INSERT INTO stock_orders(actor,operation_id,order_id,revision,protected) VALUES(?,?,?,?,?)")
    837                 .bind(header.actor.participant().as_bytes().as_slice()).bind(operation.as_bytes().as_slice())
    838                 .bind(fence.order.as_bytes().as_slice()).bind(fence.revision.get() as i64).bind(order_cipher)
    839                 .execute(&mut *tx).await.map_err(|_| OperationError::StorageFailure)?;
    840             current_order.advance(&mut tx, super::super::order_state::Marker::from_header(&framed.header, super::super::order_state::Phase::Prepared)?).await?;
    841         } else {
    842             sqlx::query("INSERT INTO stock_orders(order_id,revision,protected) VALUES(?,?,?)").bind(fence.order.as_bytes().as_slice()).bind(fence.revision.get() as i64).bind(order_cipher).execute(&mut *tx).await.map_err(|_| OperationError::StorageFailure)?;
    843         }
    844         let updated = sqlx::query("UPDATE stock_authority SET protected=? WHERE singleton=1 AND protected=?").bind(root).bind(&access.root).execute(&mut *tx).await.map_err(|_| OperationError::StorageFailure)?;
    845         if updated.rows_affected() != 1 { return Err(OperationError::RecoveryRequired); }
    846         turn.namespace.validate()?; Ok(())
    847     }.await;
    848     let attempt = receipt.attempt();
    849     if let Err(error) = changed {
    850         if tx.rollback().await.is_err() {
    851             *turn.uncertain = true;
    852             return Ok(StockAcceptanceOutcome::Unknown(attempt));
    853         }
    854         return Err(error);
    855     }
    856     if tx.commit().await.is_err() {
    857         *turn.uncertain = true;
    858         return Ok(StockAcceptanceOutcome::Unknown(attempt));
    859     }
    860     Ok(StockAcceptanceOutcome::Prepared(Box::new(receipt)))
    861 }
    862 fn header_for_prepare(header: &ledger::Header) -> ledger::Header {
    863     ledger::Header {
    864         version: header.version,
    865         family: header.family,
    866         namespace: header.namespace.clone(),
    867         actor: header.actor,
    868         operation: header.operation,
    869         digest: header.digest,
    870         transaction: header.transaction,
    871         revision: header.revision,
    872         previous: header.previous,
    873         head: header.head,
    874         pool: header.pool,
    875         order: header.order,
    876         related_operation: header.related_operation,
    877         subject_grant: header.subject_grant,
    878         bytes: header.bytes,
    879         parts: header.parts,
    880         body_digest: header.body_digest,
    881     }
    882 }
    883 impl NativeWorkspace {
    884     /// Atomically prepares an original acceptance and its physical holds. This
    885     /// never invokes a signer or installs a bilateral agreement.
    886     pub async fn prepare_stock_acceptance(
    887         &self,
    888         request: StockAcceptanceRequest,
    889         proof: &AttachmentProof,
    890     ) -> Result<StockAcceptanceOutcome, OperationError> {
    891         let proof = proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?;
    892         self.worker.prepare_stock_acceptance(request, proof).await
    893     }
    894 }