lib

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

order_acceptance.rs (13409B)


      1 //! Exact T0 command data. Capture establishes no source, approval, grant or hold.
      2 use super::{COMMAND_MAX_BYTES, CommandError, Context, check_frame, hash, parse_object};
      3 use alloc::{boxed::Box, string::String, vec::Vec};
      4 use core::fmt;
      5 use radroots_domain::{
      6     ActorRole, AgreementLineId, ApprovalIntentDigest, CommandContextData, CommandDigest, PoolId,
      7     Quantity, RecordId, Sequence, TermsDigest,
      8 };
      9 use serde::{
     10     Deserialize, Serialize,
     11     ser::{SerializeSeq, SerializeStruct},
     12 };
     13 use serde_json::value::RawValue;
     14 use zeroize::Zeroizing;
     15 
     16 /// One advanced seller allocation claim, before live validation and acquisition.
     17 #[derive(Clone, Copy, Eq, PartialEq)]
     18 pub struct AllocationInput {
     19     line: AgreementLineId,
     20     pool: PoolId,
     21     quantity: Quantity,
     22     expected: Sequence,
     23 }
     24 impl AllocationInput {
     25     /// Requires positive quantity and an existing pool version. The executor
     26     /// separately checks line coverage, compatible units and the actual pool.
     27     pub fn new(
     28         line: AgreementLineId,
     29         pool: PoolId,
     30         quantity: Quantity,
     31         expected: Sequence,
     32     ) -> Result<Self, CommandError> {
     33         if quantity.amount().is_zero() || expected.get() == 0 {
     34             return Err(CommandError::InvalidInput);
     35         }
     36         Ok(Self {
     37             line,
     38             pool,
     39             quantity,
     40             expected,
     41         })
     42     }
     43     pub const fn line_id(self) -> AgreementLineId {
     44         self.line
     45     }
     46     pub const fn pool_id(self) -> PoolId {
     47         self.pool
     48     }
     49     pub const fn quantity(self) -> Quantity {
     50         self.quantity
     51     }
     52     pub const fn expected_pool_version(self) -> Sequence {
     53         self.expected
     54     }
     55 }
     56 impl fmt::Debug for AllocationInput {
     57     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     58         f.write_str("AllocationInput(<redacted>)")
     59     }
     60 }
     61 /// Automatic mapping resolution or an explicit, nonempty bounded seller choice.
     62 /// Neither choice authorizes stock-free acceptance or proves physical backing.
     63 pub struct AllocationSelection(Choice);
     64 enum Choice {
     65     Automatic,
     66     Explicit(Box<[AllocationInput]>),
     67 }
     68 impl AllocationSelection {
     69     pub const MAX_ALLOCATIONS: usize = 64;
     70     pub const fn automatic() -> Self {
     71         Self(Choice::Automatic)
     72     }
     73     /// Refuses empty/oversized lists and ambiguous duplicate line/pool pairs.
     74     /// Capture preserves supplied order; acquisition order belongs to the plan.
     75     pub fn explicit(allocations: Vec<AllocationInput>) -> Result<Self, CommandError> {
     76         if allocations.is_empty() || allocations.len() > Self::MAX_ALLOCATIONS {
     77             return Err(CommandError::InvalidInput);
     78         }
     79         for (index, value) in allocations.iter().enumerate() {
     80             if allocations[..index]
     81                 .iter()
     82                 .any(|prior| prior.line == value.line && prior.pool == value.pool)
     83             {
     84                 return Err(CommandError::InvalidInput);
     85             }
     86         }
     87         Ok(Self(Choice::Explicit(allocations.into_boxed_slice())))
     88     }
     89     pub const fn is_automatic(&self) -> bool {
     90         matches!(self.0, Choice::Automatic)
     91     }
     92     pub fn explicit_allocations(&self) -> Option<&[AllocationInput]> {
     93         match &self.0 {
     94             Choice::Automatic => None,
     95             Choice::Explicit(values) => Some(values),
     96         }
     97     }
     98 }
     99 impl fmt::Debug for AllocationSelection {
    100     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    101         f.write_str("AllocationSelection(<redacted>)")
    102     }
    103 }
    104 /// Exact request and Terms identities; source lookup and authorization are IO.
    105 pub struct AcceptOrderInput {
    106     request: RecordId,
    107     terms: TermsDigest,
    108     allocation: AllocationSelection,
    109 }
    110 impl AcceptOrderInput {
    111     pub const fn new(
    112         request: RecordId,
    113         terms: TermsDigest,
    114         allocation: AllocationSelection,
    115     ) -> Self {
    116         Self {
    117             request,
    118             terms,
    119             allocation,
    120         }
    121     }
    122     pub const fn request(&self) -> RecordId {
    123         self.request
    124     }
    125     pub const fn terms_digest(&self) -> TermsDigest {
    126         self.terms
    127     }
    128     pub const fn allocation(&self) -> &AllocationSelection {
    129         &self.allocation
    130     }
    131 }
    132 impl fmt::Debug for AcceptOrderInput {
    133     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    134         f.write_str("AcceptOrderInput(<redacted>)")
    135     }
    136 }
    137 /// Closed `orders.accept` capture. A concrete authority must revalidate source,
    138 /// approval, current access, order/mapping/pool state and commit actual holds.
    139 pub struct CapturedOrderAcceptance {
    140     context: CommandContextData,
    141     input: AcceptOrderInput,
    142     wire: Zeroizing<Box<[u8]>>,
    143     digest: CommandDigest,
    144     approval: ApprovalIntentDigest,
    145 }
    146 impl CapturedOrderAcceptance {
    147     /// Requires seller/order descriptors as data. Approval may be absent while
    148     /// computing an intent for consent; capture never verifies that consent.
    149     pub fn new(context: CommandContextData, input: AcceptOrderInput) -> Result<Self, CommandError> {
    150         if context.actor().role() != ActorRole::Seller || context.expected().is_none() {
    151             return Err(CommandError::InvalidInput);
    152         }
    153         let encode = |approval, correlation| -> Result<Zeroizing<Vec<u8>>, CommandError> {
    154             let bytes = Zeroizing::new(
    155                 serde_json::to_vec(&Wire {
    156                     context: &context,
    157                     input: &input,
    158                     approval,
    159                     correlation,
    160                 })
    161                 .map_err(|_| CommandError::InvalidInput)?,
    162             );
    163             if bytes.len() > COMMAND_MAX_BYTES {
    164                 return Err(CommandError::LimitExceeded);
    165             }
    166             Ok(bytes)
    167         };
    168         let wire = Zeroizing::new(encode(true, true)?.to_vec().into_boxed_slice());
    169         let digest =
    170             CommandDigest::from_bytes(hash(b"radroots.command.v1\0", &encode(true, false)?));
    171         let approval = ApprovalIntentDigest::from_bytes(hash(
    172             b"radroots.approval.v1\0",
    173             &encode(false, false)?,
    174         ));
    175         Ok(Self {
    176             context,
    177             input,
    178             wire,
    179             digest,
    180             approval,
    181         })
    182     }
    183     pub fn parse(raw: &[u8]) -> Result<Self, CommandError> {
    184         check_frame(raw)?;
    185         #[derive(Deserialize)]
    186         #[serde(deny_unknown_fields)]
    187         struct Root<'a> {
    188             #[serde(rename = "type")]
    189             kind: String,
    190             context: CommandContextData,
    191             #[serde(borrow)]
    192             input: &'a RawValue,
    193         }
    194         #[derive(Deserialize)]
    195         #[serde(deny_unknown_fields)]
    196         struct Input<'a> {
    197             request: RecordId,
    198             terms_digest: TermsDigest,
    199             #[serde(borrow)]
    200             allocation: &'a RawValue,
    201         }
    202         let root: Root<'_> = parse_object(raw)?;
    203         if root.kind != "orders.accept" {
    204             return Err(CommandError::UnsupportedCommand);
    205         }
    206         let input: Input<'_> = parse_object(root.input.get().as_bytes())?;
    207         Self::new(
    208             root.context,
    209             AcceptOrderInput::new(
    210                 input.request,
    211                 input.terms_digest,
    212                 parse_selection(input.allocation.get().as_bytes())?,
    213             ),
    214         )
    215     }
    216     pub const fn context(&self) -> &CommandContextData {
    217         &self.context
    218     }
    219     pub const fn input(&self) -> &AcceptOrderInput {
    220         &self.input
    221     }
    222     pub fn protected_wire(&self) -> &[u8] {
    223         &self.wire
    224     }
    225     pub const fn digest(&self) -> CommandDigest {
    226         self.digest
    227     }
    228     pub const fn approval_intent_digest(&self) -> ApprovalIntentDigest {
    229         self.approval
    230     }
    231 }
    232 impl fmt::Debug for CapturedOrderAcceptance {
    233     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    234         f.write_str("CapturedOrderAcceptance(<redacted>)")
    235     }
    236 }
    237 #[derive(Deserialize)]
    238 #[serde(deny_unknown_fields)]
    239 struct AllocationWire {
    240     line_id: AgreementLineId,
    241     pool_id: PoolId,
    242     quantity: Quantity,
    243     expected_pool_version: Sequence,
    244 }
    245 pub(super) fn parse_selection(raw: &[u8]) -> Result<AllocationSelection, CommandError> {
    246     #[derive(Deserialize)]
    247     struct Probe {
    248         #[serde(rename = "type")]
    249         kind: String,
    250     }
    251     let probe: Probe = parse_object(raw)?;
    252     match probe.kind.as_str() {
    253         "automatic" => {
    254             #[derive(Deserialize)]
    255             #[serde(deny_unknown_fields)]
    256             struct Automatic {
    257                 #[serde(rename = "type")]
    258                 _kind: String,
    259             }
    260             let _: Automatic = parse_object(raw)?;
    261             Ok(AllocationSelection::automatic())
    262         }
    263         "explicit" => {
    264             #[derive(Deserialize)]
    265             #[serde(deny_unknown_fields)]
    266             struct Explicit<'a> {
    267                 #[serde(rename = "type")]
    268                 _kind: String,
    269                 #[serde(borrow)]
    270                 allocations: &'a RawValue,
    271             }
    272             let value: Explicit<'_> = parse_object(raw)?;
    273             let mut decoder = serde_json::Deserializer::from_str(value.allocations.get());
    274             struct Allocations;
    275             impl<'de> serde::de::Visitor<'de> for Allocations {
    276                 type Value = Vec<AllocationInput>;
    277                 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    278                     f.write_str("one through64 closed allocation objects")
    279                 }
    280                 fn visit_seq<A: serde::de::SeqAccess<'de>>(
    281                     self,
    282                     mut seq: A,
    283                 ) -> Result<Self::Value, A::Error> {
    284                     let mut values = Vec::new();
    285                     while let Some(raw) = seq.next_element::<&RawValue>()? {
    286                         if values.len() == AllocationSelection::MAX_ALLOCATIONS {
    287                             return Err(serde::de::Error::custom("allocation count limit"));
    288                         }
    289                         let value: AllocationWire =
    290                             parse_object(raw.get().as_bytes()).map_err(serde::de::Error::custom)?;
    291                         values.push(
    292                             AllocationInput::new(
    293                                 value.line_id,
    294                                 value.pool_id,
    295                                 value.quantity,
    296                                 value.expected_pool_version,
    297                             )
    298                             .map_err(serde::de::Error::custom)?,
    299                         );
    300                     }
    301                     Ok(values)
    302                 }
    303             }
    304             let values = serde::Deserializer::deserialize_seq(&mut decoder, Allocations)
    305                 .map_err(|_| CommandError::InvalidInput)?;
    306             decoder.end().map_err(|_| CommandError::InvalidInput)?;
    307             AllocationSelection::explicit(values)
    308         }
    309         _ => Err(CommandError::InvalidInput),
    310     }
    311 }
    312 struct Wire<'a> {
    313     context: &'a CommandContextData,
    314     input: &'a AcceptOrderInput,
    315     approval: bool,
    316     correlation: bool,
    317 }
    318 impl Serialize for Wire<'_> {
    319     fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
    320         let mut out = s.serialize_struct("OrderAcceptance", 3)?;
    321         out.serialize_field(
    322             "context",
    323             &Context(self.context, self.approval, self.correlation),
    324         )?;
    325         out.serialize_field("input", &InputWire(self.input))?;
    326         out.serialize_field("type", "orders.accept")?;
    327         out.end()
    328     }
    329 }
    330 struct InputWire<'a>(&'a AcceptOrderInput);
    331 impl Serialize for InputWire<'_> {
    332     fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
    333         let mut out = s.serialize_struct("AcceptOrderInput", 3)?;
    334         out.serialize_field("allocation", &self.0.allocation)?;
    335         out.serialize_field("request", &self.0.request)?;
    336         out.serialize_field("terms_digest", &self.0.terms)?;
    337         out.end()
    338     }
    339 }
    340 impl Serialize for AllocationSelection {
    341     fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
    342         let mut out = s.serialize_struct(
    343             "AllocationSelection",
    344             if self.is_automatic() { 1 } else { 2 },
    345         )?;
    346         if let Some(values) = self.explicit_allocations() {
    347             out.serialize_field("allocations", &AllocationsWire(values))?;
    348         }
    349         out.serialize_field(
    350             "type",
    351             if self.is_automatic() {
    352                 "automatic"
    353             } else {
    354                 "explicit"
    355             },
    356         )?;
    357         out.end()
    358     }
    359 }
    360 struct AllocationsWire<'a>(&'a [AllocationInput]);
    361 impl Serialize for AllocationsWire<'_> {
    362     fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
    363         let mut out = s.serialize_seq(Some(self.0.len()))?;
    364         for value in self.0 {
    365             out.serialize_element(&AllocationWrite(value))?;
    366         }
    367         out.end()
    368     }
    369 }
    370 struct AllocationWrite<'a>(&'a AllocationInput);
    371 impl Serialize for AllocationWrite<'_> {
    372     fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
    373         let mut out = s.serialize_struct("AllocationInput", 4)?;
    374         out.serialize_field("expected_pool_version", &self.0.expected)?;
    375         out.serialize_field("line_id", &self.0.line)?;
    376         out.serialize_field("pool_id", &self.0.pool)?;
    377         out.serialize_field("quantity", &self.0.quantity)?;
    378         out.end()
    379     }
    380 }