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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
use sha2::{Digest, Sha224};
use std::convert::TryFrom;
use thiserror::Error;

/// An error happened while encoding, decoding or serializing a principal.
#[derive(Error, Clone, Debug, Eq, PartialEq)]
pub enum PrincipalError {
    #[error("Buffer is too long.")]
    BufferTooLong(),

    #[error(r#"Invalid textual format: expected "{0}""#)]
    AbnormalTextualFormat(String),

    #[error("Text must be a base 32 string.")]
    InvalidTextualFormatNotBase32(),

    #[error("Text cannot be converted to a Principal; too small.")]
    TextTooSmall(),

    #[error("A custom tool returned an error instead of a Principal: {0}")]
    ExternalError(String),
}

const ID_ANONYMOUS_BYTES: &[u8] = &[PrincipalClass::Anonymous as u8];

/// A class of principal. Because this should not be exposed it
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub(crate) enum PrincipalClass {
    Unassigned = 0,
    OpaqueId = 1,
    SelfAuthenticating = 2,
    DerivedId = 3,
    Anonymous = 4,
}

impl TryFrom<u8> for PrincipalClass {
    type Error = PrincipalError;

    fn try_from(byte: u8) -> Result<Self, Self::Error> {
        match byte {
            1 => Ok(PrincipalClass::OpaqueId),
            2 => Ok(PrincipalClass::SelfAuthenticating),
            3 => Ok(PrincipalClass::DerivedId),
            4 => Ok(PrincipalClass::Anonymous),
            _ => Ok(PrincipalClass::Unassigned),
        }
    }
}

/// A principal describes the security context of an identity, namely
/// any identity that can be authenticated along with a specific
/// role. In the case of the Internet Computer this maps currently to
/// the identities that can be authenticated by a canister. For example,
/// a canister ID is a Principal. So is a user.
///
/// Note a principal is not necessarily tied with a public key-pair,
/// yet we need at least a key-pair of a related principal to sign
/// requests.
///
/// A Principal can be serialized to a byte array ([`Vec<u8>`]) or a text
/// representation, but the inner structure of the byte representation
/// is kept private.
///
/// Example of using a Principal object:
/// ```
/// use ic_types::Principal;
///
/// let text = "aaaaa-aa";  // The management canister ID.
/// let principal = Principal::from_text(text).expect("Could not decode the principal.");
/// assert_eq!(principal.as_slice(), &[]);
/// assert_eq!(principal.to_text(), text);
/// ```
///
/// Serialization is enabled with the "serde" feature. It supports serializing
/// to a byte bufer for non-human readable serializer, and a string version for human
/// readable serializers.
///
/// ```
/// use ic_types::Principal;
/// use serde::{Deserialize, Serialize};
/// use std::str::FromStr;
///
/// #[derive(Serialize)]
/// struct Data {
///     id: Principal,
/// }
///
/// let id = Principal::from_str("2chl6-4hpzw-vqaaa-aaaaa-c").unwrap();
///
/// // JSON is human readable, so this will serialize to a textual
/// // main.rsrepresentation of the Principal.
/// assert_eq!(
///     serde_json::to_string(&Data { id: id.clone() }).unwrap(),
///     r#"{"id":"2chl6-4hpzw-vqaaa-aaaaa-c"}"#
/// );
///
/// // CBOR is not human readable, so will serialize to bytes.
/// assert_eq!(
///     serde_cbor::to_vec(&Data { id: id.clone() }).unwrap(),
///     &[161, 98, 105, 100, 73, 239, 205, 171, 0, 0, 0, 0, 0, 1],
/// );
/// ```
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Principal(PrincipalInner);

/// Inner structure of a Principal. This is not meant to be public as the different classes
/// of principals are not public.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum PrincipalInner {
    /// An empty principal that marks the system canister.
    ManagementCanister,

    /// A Principal created by the system (the Internet Computer). This can only be created by
    /// using [`try_from`].
    OpaqueId(Vec<u8>),

    /// Defined as H(public_key) || 0x02.
    SelfAuthenticating(Vec<u8>),

    /// A Principal derived by another.
    /// Defined as H(|registering_principal| || registering_principal || derivation_nonce) || 0x03
    DerivedId(Vec<u8>),

    /// The anonymous Principal.
    Anonymous,

    /// An unknown principal class was found. This is unspecified from the spec, but we can use it.
    Unassigned(Vec<u8>),
}

impl Principal {
    pub fn management_canister() -> Self {
        Self(PrincipalInner::ManagementCanister)
    }

    /// Right now we are enforcing a Twisted Edwards Curve 25519 point
    /// as the public key.
    pub fn self_authenticating<P: AsRef<[u8]>>(public_key: P) -> Self {
        let mut bytes: Vec<u8> = Vec::with_capacity(Sha224::output_size() + 1);
        let hash = Sha224::digest(public_key.as_ref());
        bytes.extend(&hash);

        // Now add a suffix denoting the identifier as representing a
        // self-authenticating principal.
        bytes.push(PrincipalClass::SelfAuthenticating as u8);
        Self(PrincipalInner::SelfAuthenticating(bytes))
    }

    /// An anonymous Principal.
    pub fn anonymous() -> Self {
        Self(PrincipalInner::Anonymous)
    }

    /// Parse the text format for canister IDs (e.g., `jkies-sibbb-ap6`).
    ///
    /// The text format follows the public spec (see Textual IDs section).
    pub fn from_text<S: AsRef<str>>(text: S) -> Result<Self, PrincipalError> {
        // Strategy: Parse very liberally, then pretty-print and compare output
        // This is both simpler and yields better error messages

        let mut s = text.as_ref().to_string();
        s.make_ascii_lowercase();
        s.retain(|c| c != '-');
        match base32::decode(base32::Alphabet::RFC4648 { padding: false }, &s) {
            Some(mut bytes) => {
                if bytes.len() < 4 {
                    return Err(PrincipalError::TextTooSmall());
                }
                let result = Self::try_from(bytes.split_off(4))?;
                let expected = format!("{}", result);

                if text.as_ref() != expected {
                    return Err(PrincipalError::AbnormalTextualFormat(expected));
                }
                Ok(result)
            }
            None => Err(PrincipalError::InvalidTextualFormatNotBase32()),
        }
    }

    /// Returns this Principal's text representation. The text representation is described
    /// in the spec.
    pub fn to_text(&self) -> String {
        format!("{}", self)
    }

    /// Returns this Principal's bytes.
    pub fn as_slice(&self) -> &[u8] {
        self.as_ref()
    }
}

impl std::fmt::Display for Principal {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let blob: &[u8] = self.0.as_ref();

        // calc checksum
        let mut hasher = crc32fast::Hasher::new();
        hasher.update(blob);
        let checksum = hasher.finalize();

        // combine blobs
        let mut bytes = vec![];
        bytes.extend_from_slice(&checksum.to_be_bytes());
        bytes.extend_from_slice(blob);

        // base32
        let mut s = base32::encode(base32::Alphabet::RFC4648 { padding: false }, &bytes);
        s.make_ascii_lowercase();

        // write out string with dashes
        while s.len() > 5 {
            // to bad split_off does not work the other way
            let rest = s.split_off(5);
            f.write_fmt(format_args!("{}-", s))?;
            s = rest;
        }
        f.write_str(&s)
    }
}

impl std::str::FromStr for Principal {
    type Err = PrincipalError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Principal::from_text(s)
    }
}

impl TryFrom<&str> for Principal {
    type Error = PrincipalError;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        Principal::from_text(s)
    }
}

/// Vector TryFrom. The slice and array version of this trait are defined below.
impl TryFrom<Vec<u8>> for Principal {
    type Error = PrincipalError;

    fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
        if let Some(last_byte) = bytes.last() {
            match PrincipalClass::try_from(*last_byte)? {
                PrincipalClass::OpaqueId => Ok(Principal(PrincipalInner::OpaqueId(bytes))),
                PrincipalClass::SelfAuthenticating => {
                    Ok(Principal(PrincipalInner::SelfAuthenticating(bytes)))
                }
                PrincipalClass::DerivedId => Ok(Principal(PrincipalInner::DerivedId(bytes))),
                PrincipalClass::Anonymous => {
                    if bytes.len() == 1 {
                        Ok(Principal(PrincipalInner::Anonymous))
                    } else {
                        Err(PrincipalError::BufferTooLong())
                    }
                }
                PrincipalClass::Unassigned => Ok(Principal(PrincipalInner::Unassigned(bytes))),
            }
        } else {
            Ok(Principal(PrincipalInner::ManagementCanister))
        }
    }
}

impl TryFrom<&Vec<u8>> for Principal {
    type Error = PrincipalError;

    fn try_from(bytes: &Vec<u8>) -> Result<Self, Self::Error> {
        Self::try_from(bytes.as_slice())
    }
}

/// Implement try_from for a generic sized slice.
impl TryFrom<&[u8]> for Principal {
    type Error = PrincipalError;

    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
        Self::try_from(bytes.to_vec())
    }
}

impl AsRef<[u8]> for Principal {
    fn as_ref(&self) -> &[u8] {
        self.0.as_ref()
    }
}

impl AsRef<[u8]> for PrincipalInner {
    fn as_ref(&self) -> &[u8] {
        match self {
            PrincipalInner::Unassigned(v) => v,
            PrincipalInner::ManagementCanister => &[],
            PrincipalInner::OpaqueId(v) => v,
            PrincipalInner::SelfAuthenticating(v) => v,
            PrincipalInner::DerivedId(v) => v,
            PrincipalInner::Anonymous => ID_ANONYMOUS_BYTES,
        }
    }
}

// Serialization
#[cfg(feature = "serde")]
impl serde::Serialize for Principal {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        if serializer.is_human_readable() {
            self.to_text().serialize(serializer)
        } else {
            serializer.serialize_bytes(self.0.as_ref())
        }
    }
}

// Deserialization
#[cfg(feature = "serde")]
mod deserialize {
    use super::Principal;
    use std::convert::TryFrom;

    /// Simple visitor for deserialization from bytes. We don't support other number types
    /// as there's no need for it.
    pub(super) struct PrincipalVisitor;

    impl<'de> serde::de::Visitor<'de> for PrincipalVisitor {
        type Value = super::Principal;

        fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            formatter.write_str("bytes or string")
        }

        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            Principal::from_text(v).map_err(E::custom)
        }

        fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            Principal::try_from(value).map_err(E::custom)
        }
        /// This visitor should only be used by the Candid crate.
        fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            if v.is_empty() || v[0] != 2u8 {
                Err(E::custom("Not called by Candid"))
            } else {
                Principal::try_from(&v[1..]).map_err(E::custom)
            }
        }
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Principal {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Principal, D::Error> {
        use serde::de::Error;
        deserializer
            .deserialize_bytes(deserialize::PrincipalVisitor)
            .map_err(D::Error::custom)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::str::FromStr;

    #[cfg(feature = "serde")]
    #[test]
    fn serializes() {
        let seed = [
            0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22,
            0x11, 0x00, 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, 0x77, 0x66, 0x55, 0x44,
            0x33, 0x22, 0x11, 0x00,
        ];
        let principal: Principal = Principal::self_authenticating(&seed);
        assert_eq!(
            serde_cbor::from_slice::<Principal>(
                serde_cbor::to_vec(&principal)
                    .expect("Failed to serialize")
                    .as_slice()
            )
            .unwrap(),
            principal
        );
    }

    #[test]
    fn parse_management_canister_ok() {
        assert_eq!(
            Principal::from_str("aaaaa-aa").unwrap(),
            Principal(PrincipalInner::ManagementCanister)
        );
    }

    #[test]
    fn parse_management_canister_to_text_ok() {
        assert_eq!(Principal::from_str("aaaaa-aa").unwrap().as_slice(), &[]);
    }

    #[test]
    fn create_managment_cid_from_empty_blob_ok() {
        assert_eq!(Principal::management_canister().to_text(), "aaaaa-aa");
    }

    #[test]
    fn create_managment_cid_from_text_ok() {
        assert_eq!(
            Principal::from_str("aaaaa-aa").unwrap().to_text(),
            "aaaaa-aa",
        );
    }

    #[test]
    fn display_canister_id() {
        assert_eq!(
            Principal::try_from(vec![0xef, 0xcd, 0xab, 0, 0, 0, 0, 0, 1])
                .unwrap()
                .to_text(),
            "2chl6-4hpzw-vqaaa-aaaaa-c",
        );
    }

    #[test]
    fn display_canister_id_from_bytes_as_bytes() {
        assert_eq!(
            Principal::try_from(vec![0xef, 0xcd, 0xab, 0, 0, 0, 0, 0, 1])
                .unwrap()
                .as_slice(),
            &[0xef, 0xcd, 0xab, 0, 0, 0, 0, 0, 1],
        );
    }

    #[test]
    fn display_canister_id_from_blob_as_bytes() {
        assert_eq!(
            Principal::try_from(vec![0xef, 0xcd, 0xab, 0, 0, 0, 0, 0, 1])
                .unwrap()
                .as_slice(),
            &[0xef, 0xcd, 0xab, 0, 0, 0, 0, 0, 1],
        );
    }

    #[test]
    fn display_canister_id_from_text_as_bytes() {
        assert_eq!(
            Principal::from_str("2chl6-4hpzw-vqaaa-aaaaa-c")
                .unwrap()
                .as_slice(),
            &[0xef, 0xcd, 0xab, 0, 0, 0, 0, 0, 1],
        );
    }

    #[cfg(feature = "serde")]
    #[test]
    fn check_serialize_deserialize() {
        let id = Principal::from_str("2chl6-4hpzw-vqaaa-aaaaa-c").unwrap();

        // Use cbor serialization.
        let vec = serde_cbor::to_vec(&id).unwrap();
        let value = serde_cbor::from_slice(vec.as_slice()).unwrap();

        assert_eq!(id, value);
    }

    #[test]
    fn text_form() {
        let cid = Principal::try_from(vec![1, 8, 64, 255]).unwrap();
        let text = cid.to_text();
        let cid2 = Principal::from_str(&text).unwrap();
        assert_eq!(cid, cid2);
        assert_eq!(text, "jkies-sibbb-ap6");
    }
}