lib

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

command.rs (24901B)


      1 //! Common captured commands and the original closed chat-command profile.
      2 //! Parsing and hashing are pure data operations.
      3 //! They never authorize a principal, confirm a transaction or request signing.
      4 //!
      5 //! Canonical encoding follows the RFC 8785 subset specified for this profile:
      6 //! every schema key is ASCII, the only JSON number is fixed kind 30402, and
      7 //! exact integers are strings. Field order is explicit and independent of map
      8 //! features. Strings preserve their Unicode contents without normalization.
      9 
     10 use alloc::{boxed::Box, string::String, vec::Vec};
     11 use core::fmt;
     12 use radroots_domain::{
     13     ActorRef, ActorRole, Approval, ApprovalIntentDigest, AuthorityRef, CheckpointRef,
     14     CommandContextData, CommandDigest, ExpectedOrder, MessageId, PublicKey, SourceId, ThreadId,
     15 };
     16 use serde::{Deserialize, Serialize, ser::SerializeStruct};
     17 use sha2::{Digest, Sha256};
     18 use zeroize::Zeroizing;
     19 
     20 /// Maximum raw or canonical command bytes accepted by this closed boundary.
     21 pub const COMMAND_MAX_BYTES: usize = 65_536;
     22 /// Shared plain chat text budget, before JSON/encryption expansion.
     23 pub use radroots_domain::CHAT_MAX_BYTES;
     24 const JSON_MAX_DEPTH: usize = 16;
     25 
     26 /// Fixed input-free command data failures.
     27 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
     28 #[non_exhaustive]
     29 pub enum CommandError {
     30     /// The closed input shape or a value is invalid.
     31     InvalidInput,
     32     /// This command type is not implemented by the selected profile.
     33     UnsupportedCommand,
     34     /// A known command requires a profile feature not implemented here.
     35     UnsupportedProfile,
     36     /// A byte/depth bound was exceeded.
     37     LimitExceeded,
     38 }
     39 impl fmt::Display for CommandError {
     40     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     41         f.write_str(match self {
     42             Self::InvalidInput => "invalid command input",
     43             Self::UnsupportedCommand => "unsupported command",
     44             Self::UnsupportedProfile => "unsupported command profile",
     45             Self::LimitExceeded => "command limit exceeded",
     46         })
     47     }
     48 }
     49 impl core::error::Error for CommandError {}
     50 
     51 mod captured;
     52 mod inventory;
     53 mod order_acceptance;
     54 mod stock;
     55 mod stock_correction;
     56 mod stock_mapping;
     57 pub use captured::{CapturedCommand, CommandKind};
     58 pub use inventory::{CapturedInventoryCommand, InventoryCommandKind};
     59 pub use order_acceptance::{
     60     AcceptOrderInput, AllocationInput, AllocationSelection, CapturedOrderAcceptance,
     61 };
     62 mod order_terms;
     63 pub use order_terms::{CapturedTermsInstallation, InstallTermsInput};
     64 mod stock_commitment;
     65 pub use stock::{CapturedPoolCreation, CreatePoolInput};
     66 pub use stock_commitment::CapturedStockCommitment;
     67 pub use stock_correction::{CapturedPoolCorrection, PoolCorrectionInput};
     68 pub use stock_mapping::{CapturedOptionMapping, MapOptionInput};
     69 
     70 /// A captured public listing reference. This descriptor verifies neither its
     71 /// source event nor its availability, terms or stock backing.
     72 #[derive(Clone, Eq, PartialEq)]
     73 pub struct ListingRevisionRef {
     74     author: PublicKey,
     75     d: Box<str>,
     76     event_id: SourceId,
     77 }
     78 impl ListingRevisionRef {
     79     /// Validates the fixed 16-byte lowercase-hex listing coordinate component.
     80     pub fn new(author: PublicKey, d: &str, event_id: SourceId) -> Result<Self, CommandError> {
     81         if d.len() != 32
     82             || !d
     83                 .bytes()
     84                 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
     85         {
     86             return Err(CommandError::InvalidInput);
     87         }
     88         Ok(Self {
     89             author,
     90             d: Box::from(d),
     91             event_id,
     92         })
     93     }
     94     /// Returns the referenced listing author.
     95     pub const fn author(&self) -> PublicKey {
     96         self.author
     97     }
     98     /// Borrows the canonical listing discriminator.
     99     pub fn d(&self) -> &str {
    100         &self.d
    101     }
    102     /// Returns the referenced public event digest.
    103     pub const fn event_id(&self) -> SourceId {
    104         self.event_id
    105     }
    106 }
    107 impl fmt::Debug for ListingRevisionRef {
    108     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    109         f.write_str("ListingRevisionRef(<descriptor>)")
    110     }
    111 }
    112 
    113 /// Validated inquiry data, without command or participant authority.
    114 pub struct InquireInput {
    115     thread_id: ThreadId,
    116     peer: PublicKey,
    117     source: Option<ListingRevisionRef>,
    118     text: Zeroizing<String>,
    119 }
    120 impl InquireInput {
    121     /// Checks the plain UTF-8 budget before copying private text. Empty text is
    122     /// representable; nested rumor/encryption budgets remain separately checked.
    123     pub fn new(
    124         thread_id: ThreadId,
    125         peer: PublicKey,
    126         source: Option<ListingRevisionRef>,
    127         text: &str,
    128     ) -> Result<Self, CommandError> {
    129         if text.len() > CHAT_MAX_BYTES {
    130             return Err(CommandError::LimitExceeded);
    131         }
    132         Ok(Self {
    133             thread_id,
    134             peer,
    135             source,
    136             text: Zeroizing::new(String::from(text)),
    137         })
    138     }
    139     /// Returns the exact application thread.
    140     pub const fn thread_id(&self) -> ThreadId {
    141         self.thread_id
    142     }
    143     /// Returns the intended peer.
    144     pub const fn peer(&self) -> PublicKey {
    145         self.peer
    146     }
    147     /// Borrows the optional untrusted public-source descriptor.
    148     pub fn source(&self) -> Option<&ListingRevisionRef> {
    149         self.source.as_ref()
    150     }
    151     /// Exposes private text for its authorized encoder or participant view.
    152     pub fn text(&self) -> &str {
    153         &self.text
    154     }
    155 }
    156 impl fmt::Debug for InquireInput {
    157     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    158         f.write_str("InquireInput(<redacted>)")
    159     }
    160 }
    161 
    162 /// Validated reply data. A parent selector alone does not authenticate history.
    163 pub struct ReplyInput {
    164     thread_id: ThreadId,
    165     peer: PublicKey,
    166     parent: MessageId,
    167     text: Zeroizing<String>,
    168 }
    169 impl ReplyInput {
    170     /// Captures an exact logical parent and checks private text before copying.
    171     pub fn new(
    172         thread_id: ThreadId,
    173         peer: PublicKey,
    174         parent: MessageId,
    175         text: &str,
    176     ) -> Result<Self, CommandError> {
    177         if text.len() > CHAT_MAX_BYTES {
    178             return Err(CommandError::LimitExceeded);
    179         }
    180         Ok(Self {
    181             thread_id,
    182             peer,
    183             parent,
    184             text: Zeroizing::new(String::from(text)),
    185         })
    186     }
    187     /// Returns the captured thread.
    188     pub const fn thread_id(&self) -> ThreadId {
    189         self.thread_id
    190     }
    191     /// Returns the intended peer.
    192     pub const fn peer(&self) -> PublicKey {
    193         self.peer
    194     }
    195     /// Returns the logical rumor parent, independently of any outer envelope.
    196     pub const fn parent(&self) -> MessageId {
    197         self.parent
    198     }
    199     /// Exposes private text to an authorized consumer.
    200     pub fn text(&self) -> &str {
    201         &self.text
    202     }
    203 }
    204 impl fmt::Debug for ReplyInput {
    205     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    206         f.write_str("ReplyInput(<redacted>)")
    207     }
    208 }
    209 
    210 /// The two assigned known-kind private-chat jobs; no commerce kind is inferred.
    211 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    212 pub enum ChatKind {
    213     /// A private question, independent of an order.
    214     Inquire,
    215     /// A reply to authenticated thread history.
    216     Reply,
    217 }
    218 impl ChatKind {
    219     /// Returns the exact command-schema discriminator.
    220     pub const fn as_str(self) -> &'static str {
    221         match self {
    222             Self::Inquire => "inbox.inquire",
    223             Self::Reply => "inbox.reply",
    224         }
    225     }
    226 }
    227 enum Input {
    228     Inquire(InquireInput),
    229     Reply(ReplyInput),
    230 }
    231 
    232 /// Immutable, bounded command *data*, not an authenticated command context.
    233 /// The store must authenticate its separate protected proof and enforce every
    234 /// current precondition in the actual admission transaction. This type has no
    235 /// automatic private diagnostics, cloning or serialization.
    236 pub struct CapturedChatCommand {
    237     context: CommandContextData,
    238     input: Input,
    239     wire: Zeroizing<Box<[u8]>>,
    240     digest: CommandDigest,
    241     approval_intent: ApprovalIntentDigest,
    242 }
    243 impl CapturedChatCommand {
    244     /// Captures an inquiry and computes exact profile digests without effects.
    245     pub fn inquire(context: CommandContextData, input: InquireInput) -> Result<Self, CommandError> {
    246         Self::new(context, Input::Inquire(input))
    247     }
    248     /// Captures a reply without trusting its parent selector as evidence.
    249     pub fn reply(context: CommandContextData, input: ReplyInput) -> Result<Self, CommandError> {
    250         Self::new(context, Input::Reply(input))
    251     }
    252     fn new(context: CommandContextData, input: Input) -> Result<Self, CommandError> {
    253         let encode = |approval, correlation| -> Result<Zeroizing<Vec<u8>>, CommandError> {
    254             let bytes = Zeroizing::new(
    255                 serde_json::to_vec(&CanonicalCommand {
    256                     context: &context,
    257                     input: &input,
    258                     approval,
    259                     correlation,
    260                 })
    261                 .map_err(|_| CommandError::InvalidInput)?,
    262             );
    263             if bytes.len() > COMMAND_MAX_BYTES {
    264                 return Err(CommandError::LimitExceeded);
    265             }
    266             Ok(bytes)
    267         };
    268         let wire = Zeroizing::new(Box::from(encode(true, true)?.as_slice()));
    269         let digest = hash(b"radroots.command.v1\0", &encode(true, false)?);
    270         let approval_intent = hash(b"radroots.approval.v1\0", &encode(false, false)?);
    271         Ok(Self {
    272             context,
    273             input,
    274             wire,
    275             digest: CommandDigest::from_bytes(digest),
    276             approval_intent: ApprovalIntentDigest::from_bytes(approval_intent),
    277         })
    278     }
    279     /// Parses a bounded closed profile. JSON syntax supplies no grant or consent.
    280     pub fn parse(raw: &[u8]) -> Result<Self, CommandError> {
    281         check_frame(raw)?;
    282         let root: RawRoot<'_> = parse_object(raw)?;
    283         if root.kind.len() > 80 {
    284             return Err(CommandError::LimitExceeded);
    285         }
    286         match root.kind.as_str() {
    287             "inbox.inquire" => {
    288                 let raw: RawInquiry = parse_object(root.input.get().as_bytes())?;
    289                 if raw.text.len() > CHAT_MAX_BYTES {
    290                     return Err(CommandError::LimitExceeded);
    291                 }
    292                 let source = raw.source.map(|source| source.0.validate()).transpose()?;
    293                 Self::new(
    294                     root.context,
    295                     Input::Inquire(InquireInput {
    296                         thread_id: raw.thread_id,
    297                         peer: raw.peer,
    298                         source,
    299                         text: raw.text,
    300                     }),
    301                 )
    302             }
    303             "inbox.reply" => {
    304                 let raw: RawReply = parse_object(root.input.get().as_bytes())?;
    305                 if raw.text.len() > CHAT_MAX_BYTES {
    306                     return Err(CommandError::LimitExceeded);
    307                 }
    308                 Self::new(
    309                     root.context,
    310                     Input::Reply(ReplyInput {
    311                         thread_id: raw.thread_id,
    312                         peer: raw.peer,
    313                         parent: raw.parent,
    314                         text: raw.text,
    315                     }),
    316                 )
    317             }
    318             _ => Err(CommandError::UnsupportedCommand),
    319         }
    320     }
    321     /// Borrows untrusted captured context data for authoritative comparison.
    322     pub const fn context(&self) -> &CommandContextData {
    323         &self.context
    324     }
    325     /// Returns the command digest, with correlation removed entirely.
    326     pub const fn digest(&self) -> CommandDigest {
    327         self.digest
    328     }
    329     /// Returns the approval-intent digest with approval and correlation removed.
    330     /// The digest alone authenticates no consent origin.
    331     pub const fn approval_intent_digest(&self) -> ApprovalIntentDigest {
    332         self.approval_intent
    333     }
    334     /// Returns the known command discriminator.
    335     pub const fn kind(&self) -> ChatKind {
    336         match self.input {
    337             Input::Inquire(_) => ChatKind::Inquire,
    338             Input::Reply(_) => ChatKind::Reply,
    339         }
    340     }
    341     /// Returns the thread selected by this immutable command.
    342     pub const fn thread_id(&self) -> ThreadId {
    343         match &self.input {
    344             Input::Inquire(v) => v.thread_id,
    345             Input::Reply(v) => v.thread_id,
    346         }
    347     }
    348     /// Returns its intended peer.
    349     pub const fn peer(&self) -> PublicKey {
    350         match &self.input {
    351             Input::Inquire(v) => v.peer,
    352             Input::Reply(v) => v.peer,
    353         }
    354     }
    355     /// Borrows its exact logical parent where applicable.
    356     pub const fn parent(&self) -> Option<MessageId> {
    357         match &self.input {
    358             Input::Inquire(_) => None,
    359             Input::Reply(v) => Some(v.parent),
    360         }
    361     }
    362     /// Borrows an optional inquiry source descriptor.
    363     pub fn source(&self) -> Option<&ListingRevisionRef> {
    364         match &self.input {
    365             Input::Inquire(v) => v.source(),
    366             Input::Reply(_) => None,
    367         }
    368     }
    369     /// Exposes private text to its authorized store or wire encoder.
    370     pub fn text(&self) -> &str {
    371         match &self.input {
    372             Input::Inquire(v) => v.text(),
    373             Input::Reply(v) => v.text(),
    374         }
    375     }
    376     /// Exposes complete canonical private command bytes for protected handling.
    377     /// These include the original diagnostic correlation and are not the hash input.
    378     pub fn protected_wire(&self) -> &[u8] {
    379         &self.wire
    380     }
    381 }
    382 impl fmt::Debug for CapturedChatCommand {
    383     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    384         f.write_str("CapturedChatCommand(<redacted>)")
    385     }
    386 }
    387 
    388 pub(crate) fn hash(domain: &[u8], bytes: &[u8]) -> [u8; 32] {
    389     let mut hash = Sha256::new();
    390     hash.update(domain);
    391     hash.update(bytes);
    392     hash.finalize().into()
    393 }
    394 pub(crate) fn check_frame(raw: &[u8]) -> Result<(), CommandError> {
    395     if raw.len() > COMMAND_MAX_BYTES {
    396         return Err(CommandError::LimitExceeded);
    397     }
    398     let (mut depth, mut quoted, mut escaped) = (0usize, false, false);
    399     for byte in raw {
    400         if quoted {
    401             if escaped {
    402                 escaped = false;
    403             } else if *byte == b'\\' {
    404                 escaped = true;
    405             } else if *byte == b'"' {
    406                 quoted = false;
    407             }
    408         } else {
    409             match byte {
    410                 b'"' => quoted = true,
    411                 b'{' | b'[' => {
    412                     depth += 1;
    413                     if depth > JSON_MAX_DEPTH {
    414                         return Err(CommandError::LimitExceeded);
    415                     }
    416                 }
    417                 b'}' | b']' => depth = depth.checked_sub(1).ok_or(CommandError::InvalidInput)?,
    418                 _ => {}
    419             }
    420         }
    421     }
    422     if quoted || depth != 0 {
    423         return Err(CommandError::InvalidInput);
    424     }
    425     Ok(())
    426 }
    427 
    428 // Require maps without materializing a second JSON tree. The typed decoder
    429 // still owns duplicate, required-field and unknown-field checks, and borrowed
    430 // RawValue fields continue to refer to the bounded original frame.
    431 pub(crate) fn object<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(
    432     d: D,
    433 ) -> Result<T, D::Error> {
    434     struct ObjectVisitor<T>(core::marker::PhantomData<T>);
    435     impl<'de, T: Deserialize<'de>> serde::de::Visitor<'de> for ObjectVisitor<T> {
    436         type Value = T;
    437         fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    438             f.write_str("an object")
    439         }
    440         fn visit_map<M: serde::de::MapAccess<'de>>(self, map: M) -> Result<T, M::Error> {
    441             T::deserialize(serde::de::value::MapAccessDeserializer::new(map))
    442         }
    443     }
    444     d.deserialize_map(ObjectVisitor::<T>(core::marker::PhantomData))
    445 }
    446 struct MapOnly<T>(T);
    447 impl<'de, T: Deserialize<'de>> Deserialize<'de> for MapOnly<T> {
    448     fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
    449         object(d).map(Self)
    450     }
    451 }
    452 pub(crate) fn parse_object<'de, T: Deserialize<'de>>(raw: &'de [u8]) -> Result<T, CommandError> {
    453     serde_json::from_slice::<MapOnly<T>>(raw)
    454         .map(|value| value.0)
    455         .map_err(|_| CommandError::InvalidInput)
    456 }
    457 
    458 #[derive(Deserialize)]
    459 #[serde(deny_unknown_fields)]
    460 struct RawRoot<'a> {
    461     #[serde(rename = "type")]
    462     kind: String,
    463     context: CommandContextData,
    464     #[serde(borrow)]
    465     input: &'a serde_json::value::RawValue,
    466 }
    467 pub(crate) fn required_nullable<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(
    468     d: D,
    469 ) -> Result<Option<T>, D::Error> {
    470     Option::deserialize(d)
    471 }
    472 pub(crate) fn canonical_key<'de, D: serde::Deserializer<'de>>(d: D) -> Result<PublicKey, D::Error> {
    473     struct KeyVisitor;
    474     impl serde::de::Visitor<'_> for KeyVisitor {
    475         type Value = PublicKey;
    476         fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    477             f.write_str("a canonical public key")
    478         }
    479         fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<PublicKey, E> {
    480             let key = PublicKey::from_hex(value).map_err(|_| E::custom("invalid public key"))?;
    481             if key.to_hex() != value {
    482                 return Err(E::custom("noncanonical public key"));
    483             }
    484             Ok(key)
    485         }
    486     }
    487     d.deserialize_str(KeyVisitor)
    488 }
    489 #[cfg(any(feature = "listing", feature = "terms"))]
    490 pub(crate) fn nullable_canonical_key<'de, D: serde::Deserializer<'de>>(
    491     d: D,
    492 ) -> Result<Option<PublicKey>, D::Error> {
    493     #[derive(Deserialize)]
    494     struct Key(#[serde(deserialize_with = "canonical_key")] PublicKey);
    495     Option::<Key>::deserialize(d).map(|value| value.map(|key| key.0))
    496 }
    497 fn private_text<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Zeroizing<String>, D::Error> {
    498     String::deserialize(d).map(Zeroizing::new)
    499 }
    500 #[derive(Deserialize)]
    501 #[serde(deny_unknown_fields)]
    502 struct RawInquiry {
    503     thread_id: ThreadId,
    504     #[serde(deserialize_with = "canonical_key")]
    505     peer: PublicKey,
    506     #[serde(deserialize_with = "required_nullable")]
    507     source: Option<MapOnly<RawSource>>,
    508     #[serde(deserialize_with = "private_text")]
    509     text: Zeroizing<String>,
    510 }
    511 #[derive(Deserialize)]
    512 #[serde(deny_unknown_fields)]
    513 struct RawReply {
    514     thread_id: ThreadId,
    515     #[serde(deserialize_with = "canonical_key")]
    516     peer: PublicKey,
    517     parent: MessageId,
    518     #[serde(deserialize_with = "private_text")]
    519     text: Zeroizing<String>,
    520 }
    521 #[derive(Deserialize)]
    522 #[serde(deny_unknown_fields)]
    523 struct RawSource {
    524     #[serde(deserialize_with = "object")]
    525     coordinate: RawCoordinate,
    526     event_id: SourceId,
    527 }
    528 #[derive(Deserialize)]
    529 #[serde(deny_unknown_fields)]
    530 struct RawCoordinate {
    531     kind: u32,
    532     #[serde(deserialize_with = "canonical_key")]
    533     author: PublicKey,
    534     d: String,
    535 }
    536 impl RawSource {
    537     fn validate(self) -> Result<ListingRevisionRef, CommandError> {
    538         if self.coordinate.kind != 30402 {
    539             return Err(CommandError::InvalidInput);
    540         }
    541         ListingRevisionRef::new(self.coordinate.author, &self.coordinate.d, self.event_id)
    542     }
    543 }
    544 
    545 struct CanonicalCommand<'a> {
    546     context: &'a CommandContextData,
    547     input: &'a Input,
    548     approval: bool,
    549     correlation: bool,
    550 }
    551 impl Serialize for CanonicalCommand<'_> {
    552     fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
    553         let mut o = s.serialize_struct("ChatCommand", 3)?;
    554         o.serialize_field(
    555             "context",
    556             &Context(self.context, self.approval, self.correlation),
    557         )?;
    558         o.serialize_field("input", &CanonicalInput(self.input))?;
    559         o.serialize_field(
    560             "type",
    561             match self.input {
    562                 Input::Inquire(_) => "inbox.inquire",
    563                 Input::Reply(_) => "inbox.reply",
    564             },
    565         )?;
    566         o.end()
    567     }
    568 }
    569 pub(crate) struct Context<'a>(
    570     pub(crate) &'a CommandContextData,
    571     pub(crate) bool,
    572     pub(crate) bool,
    573 );
    574 impl Serialize for Context<'_> {
    575     fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
    576         let v = self.0;
    577         let mut o = s.serialize_struct("Context", 7 + usize::from(self.1) + usize::from(self.2))?;
    578         o.serialize_field("actor", &Actor(v.actor()))?;
    579         if self.1 {
    580             o.serialize_field("approval", &v.approval().map(CanonicalApproval))?;
    581         }
    582         o.serialize_field("authority", &Authority(v.authority()))?;
    583         if self.2 {
    584             o.serialize_field("correlation_id", &v.correlation_id().map(|c| c.as_str()))?;
    585         }
    586         o.serialize_field("expected", &v.expected().map(Expected))?;
    587         o.serialize_field("not_after", &v.not_after())?;
    588         o.serialize_field("operation_id", &v.operation_id())?;
    589         o.serialize_field("route_digest", &v.route_digest())?;
    590         o.serialize_field("workspace_id", &v.workspace_id())?;
    591         o.end()
    592     }
    593 }
    594 struct Actor(ActorRef);
    595 impl Serialize for Actor {
    596     fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
    597         let role = match self.0.role() {
    598             ActorRole::Buyer => "buyer",
    599             ActorRole::Seller => "seller",
    600             ActorRole::Coordinator => "coordinator",
    601             _ => return Err(serde::ser::Error::custom("unsupported actor role")),
    602         };
    603         let mut o = s.serialize_struct("Actor", 4)?;
    604         o.serialize_field("grant_id", &self.0.grant_id())?;
    605         o.serialize_field("organization", &self.0.organization())?;
    606         o.serialize_field("participant", &self.0.participant())?;
    607         o.serialize_field("role", role)?;
    608         o.end()
    609     }
    610 }
    611 struct Authority(AuthorityRef);
    612 impl Serialize for Authority {
    613     fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
    614         let mut o = s.serialize_struct("Authority", 2)?;
    615         o.serialize_field("executor_id", &self.0.executor_id())?;
    616         o.serialize_field("generation", &self.0.generation())?;
    617         o.end()
    618     }
    619 }
    620 struct CanonicalApproval<'a>(&'a Approval);
    621 impl Serialize for CanonicalApproval<'_> {
    622     fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
    623         let mut o = s.serialize_struct("Approval", 3)?;
    624         o.serialize_field("expires_at", &self.0.expires_at())?;
    625         o.serialize_field("intent_digest", &self.0.intent_digest())?;
    626         o.serialize_field("scope", self.0.scope())?;
    627         o.end()
    628     }
    629 }
    630 struct Expected<'a>(&'a ExpectedOrder);
    631 impl Serialize for Expected<'_> {
    632     fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
    633         let v = self.0;
    634         let mut o = s.serialize_struct("Expected", 5)?;
    635         o.serialize_field("agreement", &v.agreement())?;
    636         o.serialize_field("buyer_head", &v.buyer_head())?;
    637         o.serialize_field("checkpoint", &Checkpoint(v.checkpoint()))?;
    638         o.serialize_field("order_id", &v.order_id())?;
    639         o.serialize_field("seller_sequence", &v.seller_sequence())?;
    640         o.end()
    641     }
    642 }
    643 struct Checkpoint<'a>(&'a CheckpointRef);
    644 impl Serialize for Checkpoint<'_> {
    645     fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
    646         let v = self.0;
    647         let mut o = s.serialize_struct("Checkpoint", 4)?;
    648         o.serialize_field("coverage", &v.coverage())?;
    649         o.serialize_field("digest", &v.digest())?;
    650         o.serialize_field("missing", v.missing())?;
    651         o.serialize_field("sequence", &v.sequence())?;
    652         o.end()
    653     }
    654 }
    655 struct CanonicalInput<'a>(&'a Input);
    656 impl Serialize for CanonicalInput<'_> {
    657     fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
    658         let mut o = s.serialize_struct("ChatInput", 4)?;
    659         match self.0 {
    660             Input::Inquire(v) => {
    661                 o.serialize_field("peer", &v.peer)?;
    662                 o.serialize_field("source", &v.source)?;
    663                 o.serialize_field("text", v.text())?;
    664                 o.serialize_field("thread_id", &v.thread_id)?;
    665             }
    666             Input::Reply(v) => {
    667                 o.serialize_field("parent", &v.parent)?;
    668                 o.serialize_field("peer", &v.peer)?;
    669                 o.serialize_field("text", v.text())?;
    670                 o.serialize_field("thread_id", &v.thread_id)?;
    671             }
    672         }
    673         o.end()
    674     }
    675 }
    676 impl Serialize for ListingRevisionRef {
    677     fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
    678         let mut o = s.serialize_struct("ListingRevision", 2)?;
    679         o.serialize_field("coordinate", &Coordinate(self))?;
    680         o.serialize_field("event_id", &self.event_id)?;
    681         o.end()
    682     }
    683 }
    684 struct Coordinate<'a>(&'a ListingRevisionRef);
    685 impl Serialize for Coordinate<'_> {
    686     fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
    687         let mut o = s.serialize_struct("ListingCoordinate", 3)?;
    688         o.serialize_field("author", &self.0.author)?;
    689         o.serialize_field("d", &self.0.d)?;
    690         o.serialize_field("kind", &30402u32)?;
    691         o.end()
    692     }
    693 }