bc_components/id/
arid.rs

1use anyhow::{Result, bail};
2use bc_rand::random_data;
3use bc_ur::prelude::*;
4
5use crate::tags;
6
7/// An "Apparently Random Identifier" (ARID)
8///
9/// An ARID is a cryptographically strong, universally unique identifier with
10/// the following properties:
11/// - Non-correlatability: The sequence of bits cannot be correlated with its
12///   referent or any other ARID
13/// - Neutral semantics: Contains no inherent type information
14/// - Open generation: Any method of generation is allowed as long as it
15///   produces statistically random bits
16/// - Minimum strength: Must be 256 bits (32 bytes) in length
17/// - Cryptographic suitability: Can be used as inputs to cryptographic
18///   constructs
19///
20/// Unlike digests/hashes which identify a fixed, immutable state of data, ARIDs
21/// can serve as stable identifiers for mutable data structures.
22///
23/// ARIDs should not be confused with or cast to/from other identifier types
24/// (like UUIDs), used as nonces, keys, or cryptographic seeds.
25///
26/// As defined in [BCR-2022-002](https://github.com/BlockchainCommons/Research/blob/master/papers/bcr-2022-002-arid.md).
27#[derive(Clone, Copy, Eq, PartialEq, Hash)]
28pub struct ARID([u8; Self::ARID_SIZE]);
29
30impl ARID {
31    pub const ARID_SIZE: usize = 32;
32
33    /// Create a new random ARID.
34    pub fn new() -> Self {
35        let data = random_data(Self::ARID_SIZE);
36        Self::from_data_ref(data).unwrap()
37    }
38
39    /// Restore a ARID from a fixed-size array of bytes.
40    pub fn from_data(data: [u8; Self::ARID_SIZE]) -> Self { Self(data) }
41
42    /// Create a new ARID from a reference to an array of bytes.
43    pub fn from_data_ref(data: impl AsRef<[u8]>) -> Result<Self> {
44        let data = data.as_ref();
45        if data.len() != Self::ARID_SIZE {
46            bail!("Invalid ARID size");
47        }
48        let mut arr = [0u8; Self::ARID_SIZE];
49        arr.copy_from_slice(data);
50        Ok(Self::from_data(arr))
51    }
52
53    /// Get the data of the ARID as an array of bytes.
54    pub fn data(&self) -> &[u8; Self::ARID_SIZE] { &self.0 }
55
56    /// Get the data of the ARID as a byte slice.
57    pub fn as_bytes(&self) -> &[u8] { self.as_ref() }
58
59    /// Create a new ARID from the given hexadecimal string.
60    ///
61    /// # Panics
62    /// Panics if the string is not exactly 64 hexadecimal digits.
63    pub fn from_hex(hex: impl AsRef<str>) -> Self {
64        Self::from_data_ref(hex::decode(hex.as_ref()).unwrap()).unwrap()
65    }
66
67    /// The data as a hexadecimal string.
68    pub fn hex(&self) -> String { hex::encode(self.as_bytes()) }
69
70    /// The first four bytes of the ARID as a hexadecimal string.
71    pub fn short_description(&self) -> String { hex::encode(&self.0[0..4]) }
72}
73
74impl AsRef<[u8]> for ARID {
75    fn as_ref(&self) -> &[u8] { &self.0 }
76}
77
78/// Implements the Default trait to create a new random ARID.
79impl Default for ARID {
80    fn default() -> Self { Self::new() }
81}
82
83/// Implements conversion from an ARID reference to a byte slice reference.
84impl<'a> From<&'a ARID> for &'a [u8] {
85    fn from(value: &'a ARID) -> Self { &value.0 }
86}
87
88/// Implements the CBORTagged trait to provide CBOR tag information.
89impl CBORTagged for ARID {
90    fn cbor_tags() -> Vec<Tag> { tags_for_values(&[tags::TAG_ARID]) }
91}
92
93/// Implements conversion from ARID to CBOR for serialization.
94impl From<ARID> for CBOR {
95    fn from(value: ARID) -> Self { value.tagged_cbor() }
96}
97
98/// Implements CBORTaggedEncodable to provide CBOR encoding functionality.
99impl CBORTaggedEncodable for ARID {
100    fn untagged_cbor(&self) -> CBOR { CBOR::to_byte_string(self.as_bytes()) }
101}
102
103/// Implements `TryFrom<CBOR>` for ARID to support conversion from CBOR data.
104impl TryFrom<CBOR> for ARID {
105    type Error = dcbor::Error;
106
107    fn try_from(cbor: CBOR) -> dcbor::Result<Self> {
108        Self::from_tagged_cbor(cbor)
109    }
110}
111
112/// Implements CBORTaggedDecodable to provide CBOR decoding functionality.
113impl CBORTaggedDecodable for ARID {
114    fn from_untagged_cbor(untagged_cbor: CBOR) -> dcbor::Result<Self> {
115        let data = CBOR::try_into_byte_string(untagged_cbor)?;
116        Ok(Self::from_data_ref(data)?)
117    }
118}
119
120/// Implements Debug formatting for ARID showing the full hex representation.
121impl std::fmt::Debug for ARID {
122    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123        write!(f, "ARID({})", self.hex())
124    }
125}
126
127/// Implements Display formatting for ARID showing the hex representation.
128impl std::fmt::Display for ARID {
129    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130        write!(f, "ARID({})", self.hex())
131    }
132}
133
134/// Implements PartialOrd to allow ARIDs to be compared and ordered.
135impl PartialOrd for ARID {
136    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
137        Some(self.0.cmp(&other.0))
138    }
139}