core_crypto_keystore/entities/
proteus.rs

1use zeroize::Zeroize;
2
3use crate::connection::FetchFromDatabase;
4
5#[derive(Debug, Clone, Zeroize, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
6#[zeroize(drop)]
7pub struct ProteusIdentity {
8    pub sk: Vec<u8>,
9    pub pk: Vec<u8>,
10}
11
12impl ProteusIdentity {
13    pub const SK_KEY_SIZE: usize = 64;
14    pub const PK_KEY_SIZE: usize = 32;
15    pub const ID: &[u8; 1] = b"1";
16
17    pub fn sk_raw(&self) -> zeroize::Zeroizing<[u8; Self::SK_KEY_SIZE]> {
18        let mut slice = zeroize::Zeroizing::new([0u8; Self::SK_KEY_SIZE]);
19        debug_assert_eq!(self.sk.len(), Self::SK_KEY_SIZE);
20        slice.copy_from_slice(&self.sk[..Self::SK_KEY_SIZE]);
21        slice
22    }
23
24    pub fn pk_raw(&self) -> zeroize::Zeroizing<[u8; Self::PK_KEY_SIZE]> {
25        let mut slice = zeroize::Zeroizing::new([0u8; Self::PK_KEY_SIZE]);
26        debug_assert_eq!(self.pk.len(), Self::PK_KEY_SIZE);
27        slice.copy_from_slice(&self.pk[..Self::PK_KEY_SIZE]);
28        slice
29    }
30}
31
32#[derive(Debug, Clone, Zeroize, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
33#[zeroize(drop)]
34pub struct ProteusPrekey {
35    pub id: u16,
36    id_bytes: Vec<u8>,
37    pub prekey: Vec<u8>,
38}
39
40impl ProteusPrekey {
41    pub fn from_raw(id: u16, prekey: Vec<u8>) -> Self {
42        Self {
43            id_bytes: id.to_le_bytes().into(),
44            id,
45            prekey,
46        }
47    }
48
49    pub fn id_bytes(&self) -> &[u8] {
50        &self.id_bytes
51    }
52
53    pub fn id_from_slice(slice: &[u8]) -> u16 {
54        if slice.len() < 2 {
55            panic!("Oops, Proteus Prekey id slice is too small!");
56        }
57
58        let mut id_buf = [0u8; 2];
59        id_buf.copy_from_slice(&slice[..2]);
60        let id: u16 = u16::from_le_bytes(id_buf);
61        id
62    }
63
64    pub fn set_id(&mut self, id: u16) {
65        self.id = id;
66        self.id_bytes = self.id.to_le_bytes().into();
67    }
68
69    pub async fn get_free_id(conn: &crate::Connection) -> crate::CryptoKeystoreResult<u16> {
70        let mut id = 1u16;
71        let limit = u16::MAX;
72        while id <= limit {
73            if id == limit {
74                return Err(crate::CryptoKeystoreError::NoFreePrekeyId);
75            }
76            if conn.find::<Self>(&id.to_le_bytes()).await?.is_none() {
77                break;
78            }
79            id += 1;
80        }
81
82        Ok(id)
83    }
84}
85
86#[derive(Debug, Clone, Zeroize, PartialEq, Eq, core_crypto_macros::Entity, serde::Serialize, serde::Deserialize)]
87#[zeroize(drop)]
88pub struct ProteusSession {
89    pub id: String,
90    pub session: Vec<u8>,
91}