lib

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

stock_mapping.rs (7487B)


      1 //! Exact owner-private option mapping capture, without ownership or stock effects.
      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     ApprovalIntentDigest, CommandContextData, CommandDigest, ListingOptionId, PoolId, Quantity,
      7     Sequence, listing::ListingCoordinate, stock::OptionMappingKey,
      8 };
      9 use serde::{Deserialize, Serialize, ser::SerializeStruct};
     10 use zeroize::Zeroizing;
     11 
     12 /// An explicit private draw claim. Version0 means the mapping must not exist;
     13 /// positive versions compare an existing mapping before an actual update.
     14 pub struct MapOptionInput {
     15     key: OptionMappingKey,
     16     pool: PoolId,
     17     per_sale_unit: Quantity,
     18     expected: Sequence,
     19 }
     20 impl MapOptionInput {
     21     /// Captures a positive declared draw. Pool existence, unit conversion,
     22     /// ownership and freshness are verified by the authoritative executor.
     23     pub fn new(
     24         key: OptionMappingKey,
     25         pool: PoolId,
     26         per_sale_unit: Quantity,
     27         expected: Sequence,
     28     ) -> Result<Self, CommandError> {
     29         if per_sale_unit.amount().is_zero() {
     30             return Err(CommandError::InvalidInput);
     31         }
     32         Ok(Self {
     33             key,
     34             pool,
     35             per_sale_unit,
     36             expected,
     37         })
     38     }
     39     /// Returns the complete listing/option identity.
     40     pub const fn key(&self) -> OptionMappingKey {
     41         self.key
     42     }
     43     /// Returns the referenced private pool without asserting it exists.
     44     pub const fn pool_id(&self) -> PoolId {
     45         self.pool
     46     }
     47     /// Returns the exact original per-sale-unit quantity.
     48     pub const fn per_sale_unit(&self) -> Quantity {
     49         self.per_sale_unit
     50     }
     51     /// Returns the expected mapping version, including absence at0.
     52     pub const fn expected_mapping_version(&self) -> Sequence {
     53         self.expected
     54     }
     55 }
     56 impl fmt::Debug for MapOptionInput {
     57     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     58         f.write_str("MapOptionInput(<redacted>)")
     59     }
     60 }
     61 
     62 /// Closed bounded `stock.map_option` data; capturing it reserves no physical stock.
     63 pub struct CapturedOptionMapping {
     64     context: CommandContextData,
     65     input: MapOptionInput,
     66     wire: Zeroizing<Box<[u8]>>,
     67     digest: CommandDigest,
     68     approval: ApprovalIntentDigest,
     69 }
     70 impl CapturedOptionMapping {
     71     /// Retains the complete command and separate canonical command/approval hashes.
     72     pub fn new(context: CommandContextData, input: MapOptionInput) -> Result<Self, CommandError> {
     73         let encode = |approval, correlation| -> Result<Zeroizing<Vec<u8>>, CommandError> {
     74             let bytes = Zeroizing::new(
     75                 serde_json::to_vec(&Wire {
     76                     context: &context,
     77                     input: &input,
     78                     approval,
     79                     correlation,
     80                 })
     81                 .map_err(|_| CommandError::InvalidInput)?,
     82             );
     83             if bytes.len() > COMMAND_MAX_BYTES {
     84                 return Err(CommandError::LimitExceeded);
     85             }
     86             Ok(bytes)
     87         };
     88         let wire = Zeroizing::new(Box::from(encode(true, true)?.as_slice()));
     89         let digest =
     90             CommandDigest::from_bytes(hash(b"radroots.command.v1\0", &encode(true, false)?));
     91         let approval = ApprovalIntentDigest::from_bytes(hash(
     92             b"radroots.approval.v1\0",
     93             &encode(false, false)?,
     94         ));
     95         Ok(Self {
     96             context,
     97             input,
     98             wire,
     99             digest,
    100             approval,
    101         })
    102     }
    103     /// Validates a duplicate-safe bounded closed command and canonical values.
    104     pub fn parse(raw: &[u8]) -> Result<Self, CommandError> {
    105         check_frame(raw)?;
    106         #[derive(Deserialize)]
    107         #[serde(deny_unknown_fields)]
    108         struct Root<'a> {
    109             #[serde(rename = "type")]
    110             kind: String,
    111             context: CommandContextData,
    112             #[serde(borrow)]
    113             input: &'a serde_json::value::RawValue,
    114         }
    115         #[derive(Deserialize)]
    116         #[serde(deny_unknown_fields)]
    117         struct Input {
    118             listing: ListingCoordinate,
    119             option_id: ListingOptionId,
    120             pool_id: PoolId,
    121             per_sale_unit: Quantity,
    122             expected_mapping_version: Sequence,
    123         }
    124         let root: Root<'_> = parse_object(raw)?;
    125         if root.kind != "stock.map_option" {
    126             return Err(CommandError::UnsupportedCommand);
    127         }
    128         let input: Input = parse_object(root.input.get().as_bytes())?;
    129         Self::new(
    130             root.context,
    131             MapOptionInput::new(
    132                 OptionMappingKey::new(input.listing, input.option_id),
    133                 input.pool_id,
    134                 input.per_sale_unit,
    135                 input.expected_mapping_version,
    136             )?,
    137         )
    138     }
    139     /// Borrows exact captured context; no field is refreshed during replay.
    140     pub const fn context(&self) -> &CommandContextData {
    141         &self.context
    142     }
    143     /// Borrows the private mapping input.
    144     pub const fn input(&self) -> &MapOptionInput {
    145         &self.input
    146     }
    147     /// Borrows bounded canonical protected bytes.
    148     pub fn protected_wire(&self) -> &[u8] {
    149         &self.wire
    150     }
    151     /// Returns the exact command digest, excluding diagnostic correlation only.
    152     pub const fn digest(&self) -> CommandDigest {
    153         self.digest
    154     }
    155     /// Returns the non-circular intent digest without approval or correlation.
    156     pub const fn approval_intent_digest(&self) -> ApprovalIntentDigest {
    157         self.approval
    158     }
    159 }
    160 impl fmt::Debug for CapturedOptionMapping {
    161     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    162         f.write_str("CapturedOptionMapping(<redacted>)")
    163     }
    164 }
    165 struct Wire<'a> {
    166     context: &'a CommandContextData,
    167     input: &'a MapOptionInput,
    168     approval: bool,
    169     correlation: bool,
    170 }
    171 impl Serialize for Wire<'_> {
    172     fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
    173         let mut value = serializer.serialize_struct("OptionMapping", 3)?;
    174         value.serialize_field(
    175             "context",
    176             &Context(self.context, self.approval, self.correlation),
    177         )?;
    178         value.serialize_field("input", &InputWire(self.input))?;
    179         value.serialize_field("type", "stock.map_option")?;
    180         value.end()
    181     }
    182 }
    183 struct InputWire<'a>(&'a MapOptionInput);
    184 impl Serialize for InputWire<'_> {
    185     fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
    186         let v = self.0;
    187         let mut value = serializer.serialize_struct("MapOptionInput", 5)?;
    188         value.serialize_field("expected_mapping_version", &v.expected)?;
    189         value.serialize_field("listing", &Coordinate(v.key.listing()))?;
    190         value.serialize_field("option_id", &v.key.option_id())?;
    191         value.serialize_field("per_sale_unit", &v.per_sale_unit)?;
    192         value.serialize_field("pool_id", &v.pool)?;
    193         value.end()
    194     }
    195 }
    196 struct Coordinate(ListingCoordinate);
    197 impl Serialize for Coordinate {
    198     fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
    199         let mut value = serializer.serialize_struct("ListingCoordinate", 3)?;
    200         value.serialize_field("author", &self.0.author())?;
    201         value.serialize_field("d", &self.0.d())?;
    202         value.serialize_field("kind", &self.0.kind())?;
    203         value.end()
    204     }
    205 }