ouisync/protocol/
repository.rs

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
use crate::crypto::{
    sign::{self, PublicKey},
    Digest, Hash, Hashable,
};
use serde::{Deserialize, Serialize};
use std::str::FromStr;

#[derive(PartialEq, Eq, Hash, Clone, Debug, Copy, Serialize, Deserialize)]
#[repr(transparent)]
#[serde(transparent)]
pub struct RepositoryId(PublicKey);

derive_sqlx_traits_for_byte_array_wrapper!(RepositoryId);

impl RepositoryId {
    pub const SIZE: usize = PublicKey::SIZE;

    #[cfg(test)]
    pub fn generate<R: rand::Rng + rand::CryptoRng>(rng: &mut R) -> Self {
        crate::crypto::sign::Keypair::generate(rng)
            .public_key()
            .into()
    }

    #[cfg(test)]
    pub fn random() -> Self {
        Self::generate(&mut rand::rngs::OsRng)
    }

    /// Hash of this id using the given salt.
    pub fn salted_hash(&self, salt: &[u8]) -> Hash {
        (self, salt).hash()
    }

    pub fn write_public_key(&self) -> &PublicKey {
        &self.0
    }
}

impl FromStr for RepositoryId {
    type Err = sign::ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self(PublicKey::from_str(s)?))
    }
}

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

impl TryFrom<&'_ [u8]> for RepositoryId {
    type Error = sign::SignatureError;

    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
        Ok(Self(PublicKey::try_from(bytes)?))
    }
}

impl From<PublicKey> for RepositoryId {
    fn from(pk: PublicKey) -> Self {
        Self(pk)
    }
}

impl Hashable for RepositoryId {
    fn update_hash<S: Digest>(&self, state: &mut S) {
        self.0.update_hash(state)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::crypto::sign::Keypair;

    #[test]
    fn serialize_deserialize() {
        let public_key = Keypair::random().public_key();
        let id = RepositoryId::from(public_key);

        let bytes = public_key.as_ref();

        let serialized_expected = serde_json::to_string(bytes).unwrap();
        let serialized_actual = serde_json::to_string(&id).unwrap();

        assert_eq!(serialized_actual, serialized_expected);

        let deserialized_actual: RepositoryId = serde_json::from_str(&serialized_actual).unwrap();
        assert_eq!(deserialized_actual, id);
    }
}