1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
#[cfg(test)]
use snarkvm_circuit_types::environment::assert_scope;
mod equal;
mod from_bits;
mod from_field;
mod size_in_bits;
mod to_bits;
mod to_field;
use snarkvm_circuit_network::Aleo;
use snarkvm_circuit_types::{environment::prelude::*, Boolean, Field, U8};
use snarkvm_utilities::ToBits as TB;
#[derive(Clone)]
pub struct Identifier<A: Aleo>(Field<A>, u8); #[cfg(console)]
impl<A: Aleo> Inject for Identifier<A> {
    type Primitive = console::Identifier<A::Network>;
    fn new(_: Mode, identifier: Self::Primitive) -> Self {
        let identifier = identifier.to_string();
        let field = Field::from_bits_le(&Vec::<Boolean<_>>::constant(identifier.to_bits_le()));
        Self(field, identifier.len() as u8)
    }
}
#[cfg(console)]
impl<A: Aleo> Eject for Identifier<A> {
    type Primitive = console::Identifier<A::Network>;
    fn eject_mode(&self) -> Mode {
        match self.0.eject_mode() == Mode::Constant {
            true => Mode::Constant,
            false => A::halt("Identifier::eject_mode: Identifier mode is not constant."),
        }
    }
    fn eject_value(&self) -> Self::Primitive {
        match console::FromField::from_field(&self.0.eject_value()) {
            Ok(identifier) => identifier,
            Err(error) => A::halt(format!("Failed to convert an identifier to a string: {error}")),
        }
    }
}
#[cfg(console)]
impl<A: Aleo> Parser for Identifier<A> {
    #[inline]
    fn parse(string: &str) -> ParserResult<Self> {
        let (string, identifier) = console::Identifier::parse(string)?;
        Ok((string, Identifier::constant(identifier)))
    }
}
#[cfg(console)]
impl<A: Aleo> FromStr for Identifier<A> {
    type Err = Error;
    #[inline]
    fn from_str(string: &str) -> Result<Self> {
        match Self::parse(string) {
            Ok((remainder, object)) => {
                ensure!(remainder.is_empty(), "Failed to parse string. Found invalid character in: \"{remainder}\"");
                Ok(object)
            }
            Err(error) => bail!("Failed to parse string. {error}"),
        }
    }
}
#[cfg(console)]
impl<A: Aleo> Debug for Identifier<A> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        Display::fmt(self, f)
    }
}
#[cfg(console)]
impl<A: Aleo> Display for Identifier<A> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "{}", self.eject_value())
    }
}
impl<A: Aleo> Eq for Identifier<A> {}
impl<A: Aleo> PartialEq for Identifier<A> {
    fn eq(&self, other: &Self) -> bool {
        self.0.eject_value() == other.0.eject_value()
    }
}
impl<A: Aleo> core::hash::Hash for Identifier<A> {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.0.eject_value().hash(state);
    }
}
impl<A: Aleo> From<Identifier<A>> for LinearCombination<A::BaseField> {
    fn from(identifier: Identifier<A>) -> Self {
        From::from(&identifier)
    }
}
impl<A: Aleo> From<&Identifier<A>> for LinearCombination<A::BaseField> {
    fn from(identifier: &Identifier<A>) -> Self {
        LinearCombination::from(&identifier.0)
    }
}
#[cfg(all(test, console))]
pub(crate) mod tests {
    use super::*;
    use crate::Circuit;
    use console::{Rng, TestRng};
    use anyhow::{bail, Result};
    use core::str::FromStr;
    use rand::distributions::Alphanumeric;
    pub(crate) fn sample_console_identifier<A: Aleo>() -> Result<console::Identifier<A::Network>> {
        let string = sample_console_identifier_as_string::<A>()?;
        console::Identifier::from_str(&string)
    }
    pub(crate) fn sample_console_identifier_as_string<A: Aleo>() -> Result<String> {
        let rng = &mut TestRng::default();
        let string = "a".to_string()
            + &rng
                .sample_iter(&Alphanumeric)
                .take(A::BaseField::size_in_data_bits() / (8 * 2))
                .map(char::from)
                .collect::<String>();
        let max_bytes = A::BaseField::size_in_data_bits() / 8; match string.len() <= max_bytes {
            true => Ok(string),
            false => bail!("Identifier exceeds the maximum capacity allowed"),
        }
    }
    #[test]
    fn test_identifier_parse() -> Result<()> {
        let candidate = Identifier::<Circuit>::parse("foo_bar").unwrap();
        assert_eq!("", candidate.0);
        assert_eq!(Identifier::<Circuit>::constant("foo_bar".try_into()?).eject(), candidate.1.eject());
        Ok(())
    }
    #[test]
    fn test_identifier_parse_fails() -> Result<()> {
        let identifier = Identifier::<Circuit>::parse("foo_bar~baz").unwrap();
        assert_eq!(("~baz", Identifier::<Circuit>::from_str("foo_bar")?.eject()), (identifier.0, identifier.1.eject()));
        let identifier = Identifier::<Circuit>::parse("foo_bar-baz").unwrap();
        assert_eq!(("-baz", Identifier::<Circuit>::from_str("foo_bar")?.eject()), (identifier.0, identifier.1.eject()));
        assert!(Identifier::<Circuit>::parse("_").is_err());
        assert!(Identifier::<Circuit>::parse("__").is_err());
        assert!(Identifier::<Circuit>::parse("___").is_err());
        assert!(Identifier::<Circuit>::parse("____").is_err());
        assert!(Identifier::<Circuit>::parse("1").is_err());
        assert!(Identifier::<Circuit>::parse("2").is_err());
        assert!(Identifier::<Circuit>::parse("3").is_err());
        assert!(Identifier::<Circuit>::parse("1foo").is_err());
        assert!(Identifier::<Circuit>::parse("12").is_err());
        assert!(Identifier::<Circuit>::parse("111").is_err());
        let identifier =
            Identifier::<Circuit>::parse("foo_bar_baz_qux_quux_quuz_corge_grault_garply_waldo_fred_plugh_xyzzy");
        assert!(identifier.is_err());
        Ok(())
    }
    #[test]
    fn test_identifier_display() -> Result<()> {
        let identifier = Identifier::<Circuit>::from_str("foo_bar")?;
        assert_eq!("foo_bar", format!("{identifier}"));
        Ok(())
    }
    #[test]
    fn test_identifier_bits() -> Result<()> {
        let identifier = Identifier::<Circuit>::from_str("foo_bar")?;
        assert_eq!(
            identifier.to_bits_le().eject(),
            Identifier::from_bits_le(&identifier.to_bits_le()).to_bits_le().eject()
        );
        assert_eq!(
            identifier.to_bits_be().eject(),
            Identifier::from_bits_be(&identifier.to_bits_be()).to_bits_be().eject()
        );
        Ok(())
    }
}