lib

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

identifier.rs (5965B)


      1 use core::{fmt, str::FromStr};
      2 
      3 /// An identifier representation failure with no retained input or context.
      4 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
      5 #[non_exhaustive]
      6 pub enum IdentifierError {
      7     /// The string does not contain exactly 64 bytes.
      8     InvalidLength,
      9     /// A character is outside lowercase ASCII hexadecimal.
     10     InvalidEncoding,
     11 }
     12 
     13 impl fmt::Display for IdentifierError {
     14     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     15         f.write_str(match self {
     16             Self::InvalidLength => "identifier must contain 64 hexadecimal characters",
     17             Self::InvalidEncoding => "identifier must use lowercase ASCII hexadecimal",
     18         })
     19     }
     20 }
     21 
     22 impl core::error::Error for IdentifierError {}
     23 
     24 fn nibble(byte: u8) -> Result<u8, IdentifierError> {
     25     match byte {
     26         b'0'..=b'9' => Ok(byte - b'0'),
     27         b'a'..=b'f' => Ok(byte - b'a' + 10),
     28         _ => Err(IdentifierError::InvalidEncoding),
     29     }
     30 }
     31 
     32 fn parse(input: &str) -> Result<[u8; 32], IdentifierError> {
     33     if input.len() != 64 {
     34         return Err(IdentifierError::InvalidLength);
     35     }
     36     let mut bytes = [0; 32];
     37     // Validated width gives exactly 32 complete pairs, with no remainder.
     38     let (pairs, _) = input.as_bytes().as_chunks::<2>();
     39     for (target, &[high, low]) in bytes.iter_mut().zip(pairs) {
     40         *target = nibble(high)? << 4 | nibble(low)?;
     41     }
     42     Ok(bytes)
     43 }
     44 
     45 macro_rules! identifier {
     46     ($name:ident, $description:literal) => {
     47         #[doc = $description]
     48         #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
     49         pub struct $name([u8; 32]);
     50 
     51         impl $name {
     52             /// Constructs the fixed-width representation; generation belongs to
     53             /// the execution owner's qualified entropy boundary.
     54             pub const fn from_bytes(bytes: [u8; 32]) -> Self {
     55                 Self(bytes)
     56             }
     57 
     58             /// Borrows the exact identifier bytes without conversion.
     59             pub const fn as_bytes(&self) -> &[u8; 32] {
     60                 &self.0
     61             }
     62 
     63             /// Returns the exact identifier bytes without conversion.
     64             pub const fn into_bytes(self) -> [u8; 32] {
     65                 self.0
     66             }
     67         }
     68 
     69         impl FromStr for $name {
     70             type Err = IdentifierError;
     71 
     72             fn from_str(input: &str) -> Result<Self, Self::Err> {
     73                 parse(input).map(Self)
     74             }
     75         }
     76 
     77         impl fmt::Display for $name {
     78             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     79                 for byte in self.0 {
     80                     write!(f, "{byte:02x}")?;
     81                 }
     82                 Ok(())
     83             }
     84         }
     85 
     86         #[cfg(feature = "serde")]
     87         impl serde::Serialize for $name {
     88             fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
     89                 serializer.collect_str(self)
     90             }
     91         }
     92 
     93         #[cfg(feature = "serde")]
     94         impl<'de> serde::Deserialize<'de> for $name {
     95             fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
     96                 struct IdentifierVisitor;
     97                 impl serde::de::Visitor<'_> for IdentifierVisitor {
     98                     type Value = $name;
     99 
    100                     fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    101                         f.write_str("a canonical lowercase hexadecimal identifier")
    102                     }
    103 
    104                     fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<$name, E> {
    105                         value.parse().map_err(E::custom)
    106                     }
    107                 }
    108                 deserializer.deserialize_str(IdentifierVisitor)
    109             }
    110         }
    111     };
    112 }
    113 
    114 identifier!(OrderId, "An exact 256-bit bilateral order identifier.");
    115 identifier!(
    116     ListingOptionId,
    117     "An exact 256-bit public sale-option identifier."
    118 );
    119 identifier!(
    120     AgreementLineId,
    121     "An exact 256-bit line identity within an agreement lineage."
    122 );
    123 identifier!(
    124     FulfillmentGroupId,
    125     "An exact 256-bit private fulfillment-group identity."
    126 );
    127 identifier!(
    128     TermsDigest,
    129     "A canonical complete-terms commitment; bytes alone convey no consent."
    130 );
    131 identifier!(ThreadId, "An exact 256-bit private thread identifier.");
    132 identifier!(
    133     WorkspaceId,
    134     "An exact 256-bit participant workspace identifier."
    135 );
    136 identifier!(ExecutorId, "An exact 256-bit selected executor identifier.");
    137 identifier!(
    138     PoolId,
    139     "An exact 256-bit physical stock pool identifier, not authority."
    140 );
    141 identifier!(
    142     OperationId,
    143     "An exact 256-bit retained operation identifier."
    144 );
    145 identifier!(
    146     TransactionId,
    147     "An exact 256-bit retained transaction identity."
    148 );
    149 identifier!(
    150     MessageId,
    151     "An unsigned NIP-17 rumor identity, distinct from its signed carriers."
    152 );
    153 identifier!(
    154     RumorEventId,
    155     "An unsigned NIP-01 rumor identity, distinct from signed carriers and structured record IDs."
    156 );
    157 identifier!(
    158     EnvelopeEventId,
    159     "A signed NIP-01 artifact identity, distinct from a logical record or rumor."
    160 );
    161 identifier!(
    162     GrantId,
    163     "An exact 256-bit scoped grant identifier; not a credential."
    164 );
    165 identifier!(
    166     RecordId,
    167     "A structured record content digest, distinct from rumor and envelope identities."
    168 );
    169 identifier!(
    170     SourceId,
    171     "A missing authenticated-source digest; provenance identifies its event or record family."
    172 );
    173 identifier!(
    174     CommandDigest,
    175     "A domain-separated exact command commitment."
    176 );
    177 identifier!(
    178     RouteDigest,
    179     "A commitment to one explicitly selected execution route."
    180 );
    181 identifier!(
    182     CheckpointDigest,
    183     "A checkpoint commitment; its bytes alone establish no coverage."
    184 );
    185 identifier!(
    186     ApprovalIntentDigest,
    187     "A commitment to the exact intent presented for approval."
    188 );
    189 
    190 identifier!(
    191     SigningAttemptId,
    192     "An exact 256-bit retained signing invocation identity, distinct from an operation or artifact."
    193 );