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
//
// Copyright 2020 Signal Messenger, LLC.
// SPDX-License-Identifier: AGPL-3.0-only
//

#![allow(non_snake_case)]

use curve25519_dalek_signal::ristretto::RistrettoPoint;
use partial_default::PartialDefault;
use serde::{Deserialize, Serialize};
use subtle::{Choice, ConditionallySelectable};

use crate::common::constants::*;
use crate::common::sho::*;
use crate::common::simple_types::*;

#[derive(Copy, Clone, PartialEq, Eq, Serialize, Deserialize, PartialDefault)]
pub struct ProfileKeyStruct {
    pub(crate) bytes: ProfileKeyBytes,
    pub(crate) M3: RistrettoPoint,
    pub(crate) M4: RistrettoPoint,
}

impl ProfileKeyStruct {
    pub fn new(profile_key_bytes: ProfileKeyBytes, uid_bytes: UidBytes) -> Self {
        let mut encoded_profile_key = profile_key_bytes;
        encoded_profile_key[0] &= 254;
        encoded_profile_key[31] &= 63;
        let M3 = Self::calc_M3(profile_key_bytes, uid_bytes);
        let M4 = RistrettoPoint::from_uniform_bytes_single_elligator(&encoded_profile_key);

        ProfileKeyStruct {
            bytes: profile_key_bytes,
            M3,
            M4,
        }
    }

    pub fn calc_M3(profile_key_bytes: ProfileKeyBytes, uid_bytes: UidBytes) -> RistrettoPoint {
        let mut combined_array = [0u8; PROFILE_KEY_LEN + UUID_LEN];
        combined_array[..PROFILE_KEY_LEN].copy_from_slice(&profile_key_bytes);
        combined_array[PROFILE_KEY_LEN..].copy_from_slice(&uid_bytes);
        Sho::new(
            b"Signal_ZKGroup_20200424_ProfileKeyAndUid_ProfileKey_CalcM3",
            &combined_array,
        )
        .get_point_single_elligator()
    }

    pub fn to_bytes(&self) -> ProfileKeyBytes {
        self.bytes
    }
}

impl ConditionallySelectable for ProfileKeyStruct {
    #[allow(clippy::needless_range_loop)]
    fn conditional_select(
        a: &ProfileKeyStruct,
        b: &ProfileKeyStruct,
        choice: Choice,
    ) -> ProfileKeyStruct {
        let mut bytes: ProfileKeyBytes = [0u8; PROFILE_KEY_LEN];
        for i in 0..PROFILE_KEY_LEN {
            bytes[i] = u8::conditional_select(&a.bytes[i], &b.bytes[i], choice);
        }

        ProfileKeyStruct {
            bytes,
            M3: RistrettoPoint::conditional_select(&a.M3, &b.M3, choice),
            M4: RistrettoPoint::conditional_select(&a.M4, &b.M4, choice),
        }
    }
}

impl zkcredential::attributes::Attribute for ProfileKeyStruct {
    fn as_points(&self) -> [RistrettoPoint; 2] {
        [self.M3, self.M4]
    }
}