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