lib

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

stock_correction.rs (7766B)


      1 //! Exact owner-private correction claims, without inventory permission or 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, PoolId, PositiveDecimal, Sequence,
      7     stock::AvailableStockCorrection,
      8 };
      9 use serde::{Deserialize, Serialize, ser::SerializeStruct};
     10 use zeroize::Zeroizing;
     11 
     12 /// Positive correction quantity in the referenced pool's fixed unit. Resolving
     13 /// that unit, current version and affected obligations belongs to the executor.
     14 pub struct PoolCorrectionInput {
     15     pool: PoolId,
     16     expected: Sequence,
     17     kind: AvailableStockCorrection,
     18     amount: PositiveDecimal,
     19     reason: Zeroizing<String>,
     20 }
     21 impl PoolCorrectionInput {
     22     pub fn new(
     23         pool: PoolId,
     24         expected: Sequence,
     25         kind: AvailableStockCorrection,
     26         amount: PositiveDecimal,
     27         reason: &str,
     28     ) -> Result<Self, CommandError> {
     29         if expected.get() == 0 {
     30             return Err(CommandError::InvalidInput);
     31         }
     32         if reason.len() > 4096 || reason.chars().count() > 1024 {
     33             return Err(CommandError::LimitExceeded);
     34         }
     35         Ok(Self {
     36             pool,
     37             expected,
     38             kind,
     39             amount,
     40             reason: Zeroizing::new(String::from(reason)),
     41         })
     42     }
     43     pub const fn pool_id(&self) -> PoolId {
     44         self.pool
     45     }
     46     pub const fn expected_version(&self) -> Sequence {
     47         self.expected
     48     }
     49     pub const fn kind(&self) -> AvailableStockCorrection {
     50         self.kind
     51     }
     52     pub const fn amount(&self) -> PositiveDecimal {
     53         self.amount
     54     }
     55     pub fn reason(&self) -> &str {
     56         &self.reason
     57     }
     58 }
     59 impl fmt::Debug for PoolCorrectionInput {
     60     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     61         f.write_str("PoolCorrectionInput(<redacted>)")
     62     }
     63 }
     64 
     65 /// Complete bounded `stock.adjust` or `stock.spoil` commitment. Construction
     66 /// acquires no host and does not authorize changes to physical backing.
     67 pub struct CapturedPoolCorrection {
     68     context: CommandContextData,
     69     input: PoolCorrectionInput,
     70     wire: Zeroizing<Box<[u8]>>,
     71     digest: CommandDigest,
     72     approval: ApprovalIntentDigest,
     73 }
     74 impl CapturedPoolCorrection {
     75     pub fn new(
     76         context: CommandContextData,
     77         input: PoolCorrectionInput,
     78     ) -> Result<Self, CommandError> {
     79         let encode = |approval, correlation| -> Result<Zeroizing<Vec<u8>>, CommandError> {
     80             let bytes = Zeroizing::new(
     81                 serde_json::to_vec(&Wire {
     82                     context: &context,
     83                     input: &input,
     84                     approval,
     85                     correlation,
     86                 })
     87                 .map_err(|_| CommandError::InvalidInput)?,
     88             );
     89             if bytes.len() > COMMAND_MAX_BYTES {
     90                 return Err(CommandError::LimitExceeded);
     91             }
     92             Ok(bytes)
     93         };
     94         let wire = Zeroizing::new(Box::from(encode(true, true)?.as_slice()));
     95         let digest =
     96             CommandDigest::from_bytes(hash(b"radroots.command.v1\0", &encode(true, false)?));
     97         let approval = ApprovalIntentDigest::from_bytes(hash(
     98             b"radroots.approval.v1\0",
     99             &encode(false, false)?,
    100         ));
    101         Ok(Self {
    102             context,
    103             input,
    104             wire,
    105             digest,
    106             approval,
    107         })
    108     }
    109     pub fn parse(raw: &[u8]) -> Result<Self, CommandError> {
    110         check_frame(raw)?;
    111         #[derive(Deserialize)]
    112         #[serde(deny_unknown_fields)]
    113         struct Root<'a> {
    114             #[serde(rename = "type")]
    115             kind: String,
    116             context: CommandContextData,
    117             #[serde(borrow)]
    118             input: &'a serde_json::value::RawValue,
    119         }
    120         #[derive(Deserialize)]
    121         #[serde(deny_unknown_fields)]
    122         struct Adjust {
    123             amount: PositiveDecimal,
    124             direction: String,
    125             expected_version: Sequence,
    126             pool_id: PoolId,
    127             reason: String,
    128         }
    129         #[derive(Deserialize)]
    130         #[serde(deny_unknown_fields)]
    131         struct Spoil {
    132             amount: PositiveDecimal,
    133             expected_version: Sequence,
    134             pool_id: PoolId,
    135             reason: String,
    136         }
    137         let root: Root<'_> = parse_object(raw)?;
    138         let input = match root.kind.as_str() {
    139             "stock.adjust" => {
    140                 let v: Adjust = parse_object(root.input.get().as_bytes())?;
    141                 let kind = match v.direction.as_str() {
    142                     "add" => AvailableStockCorrection::Add,
    143                     "remove" => AvailableStockCorrection::Remove,
    144                     _ => return Err(CommandError::InvalidInput),
    145                 };
    146                 PoolCorrectionInput::new(v.pool_id, v.expected_version, kind, v.amount, &v.reason)?
    147             }
    148             "stock.spoil" => {
    149                 let v: Spoil = parse_object(root.input.get().as_bytes())?;
    150                 PoolCorrectionInput::new(
    151                     v.pool_id,
    152                     v.expected_version,
    153                     AvailableStockCorrection::Spoil,
    154                     v.amount,
    155                     &v.reason,
    156                 )?
    157             }
    158             _ => return Err(CommandError::UnsupportedCommand),
    159         };
    160         Self::new(root.context, input)
    161     }
    162     pub const fn context(&self) -> &CommandContextData {
    163         &self.context
    164     }
    165     pub const fn input(&self) -> &PoolCorrectionInput {
    166         &self.input
    167     }
    168     pub fn protected_wire(&self) -> &[u8] {
    169         &self.wire
    170     }
    171     pub const fn digest(&self) -> CommandDigest {
    172         self.digest
    173     }
    174     pub const fn approval_intent_digest(&self) -> ApprovalIntentDigest {
    175         self.approval
    176     }
    177 }
    178 impl fmt::Debug for CapturedPoolCorrection {
    179     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    180         f.write_str("CapturedPoolCorrection(<redacted>)")
    181     }
    182 }
    183 struct Wire<'a> {
    184     context: &'a CommandContextData,
    185     input: &'a PoolCorrectionInput,
    186     approval: bool,
    187     correlation: bool,
    188 }
    189 impl Serialize for Wire<'_> {
    190     fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
    191         let mut object = s.serialize_struct("PoolCorrection", 3)?;
    192         object.serialize_field(
    193             "context",
    194             &Context(self.context, self.approval, self.correlation),
    195         )?;
    196         object.serialize_field("input", &InputWire(self.input))?;
    197         object.serialize_field(
    198             "type",
    199             if self.input.kind == AvailableStockCorrection::Spoil {
    200                 "stock.spoil"
    201             } else {
    202                 "stock.adjust"
    203             },
    204         )?;
    205         object.end()
    206     }
    207 }
    208 struct InputWire<'a>(&'a PoolCorrectionInput);
    209 impl Serialize for InputWire<'_> {
    210     fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
    211         let v = self.0;
    212         let direction = match v.kind {
    213             AvailableStockCorrection::Add => Some("add"),
    214             AvailableStockCorrection::Remove => Some("remove"),
    215             AvailableStockCorrection::Spoil => None,
    216         };
    217         let mut object = s.serialize_struct(
    218             "PoolCorrectionInput",
    219             if direction.is_some() { 5 } else { 4 },
    220         )?;
    221         object.serialize_field("amount", &v.amount)?;
    222         if let Some(direction) = direction {
    223             object.serialize_field("direction", direction)?;
    224         }
    225         object.serialize_field("expected_version", &v.expected)?;
    226         object.serialize_field("pool_id", &v.pool)?;
    227         object.serialize_field("reason", v.reason())?;
    228         object.end()
    229     }
    230 }