Skip to main content

ouisync/crypto/
sign.rs

1use crate::crypto::{Digest, Hashable};
2use ed25519_dalek::{self as ext, Signer, Verifier};
3use rand::{CryptoRng, Rng};
4use serde::{Deserialize, Serialize};
5use sqlx::{
6    Sqlite,
7    sqlite::{SqliteArgumentValue, SqliteTypeInfo, SqliteValueRef},
8};
9use std::{cmp::Ordering, fmt, str::FromStr};
10use thiserror::Error;
11
12#[derive(Serialize, Deserialize)]
13#[repr(transparent)]
14#[serde(transparent)]
15pub struct Keypair(ext::SigningKey);
16
17impl Keypair {
18    pub const SECRET_KEY_SIZE: usize = ext::SECRET_KEY_LENGTH;
19
20    pub fn generate<R: Rng + CryptoRng>(rng: &mut R) -> Self {
21        // NOTE: There is also `SigningKey::generate` but we are purposefully not using it here to
22        // not be forced to use the same version of `rand` as `ed25519_dalek` uses (which was a
23        // notorious source of hassle in the past).
24        let mut secret = ext::SecretKey::default();
25        rng.fill_bytes(&mut secret);
26        Self(ext::SigningKey::from_bytes(&secret))
27    }
28
29    pub fn random() -> Self {
30        Self::generate(&mut rand::rng())
31    }
32
33    pub fn to_bytes(&self) -> [u8; Self::SECRET_KEY_SIZE] {
34        self.0.to_bytes()
35    }
36
37    pub fn public_key(&self) -> PublicKey {
38        PublicKey(self.0.verifying_key())
39    }
40
41    pub fn sign(&self, msg: &[u8]) -> Signature {
42        Signature(self.0.sign(msg))
43    }
44}
45
46impl From<&'_ [u8; Self::SECRET_KEY_SIZE]> for Keypair {
47    fn from(bytes: &'_ [u8; Self::SECRET_KEY_SIZE]) -> Self {
48        Self(ext::SigningKey::from(bytes))
49    }
50}
51
52impl TryFrom<&'_ [u8]> for Keypair {
53    type Error = SignatureError;
54
55    fn try_from(bytes: &'_ [u8]) -> Result<Self, Self::Error> {
56        Ok(Self(ext::SigningKey::try_from(bytes)?))
57    }
58}
59
60impl fmt::Debug for Keypair {
61    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
62        f.debug_struct("Keypair")
63            .field("public_key", &self.public_key())
64            .finish_non_exhaustive()
65    }
66}
67
68#[derive(PartialEq, Eq, Hash, Clone, Copy, Deserialize, Serialize)]
69#[repr(transparent)]
70#[serde(transparent)]
71pub struct PublicKey(ext::VerifyingKey);
72
73impl PublicKey {
74    pub const SIZE: usize = ext::PUBLIC_KEY_LENGTH;
75
76    #[cfg(test)]
77    pub fn generate<R: Rng + CryptoRng>(rng: &mut R) -> Self {
78        Keypair::generate(rng).public_key()
79    }
80
81    #[cfg(test)]
82    pub fn random() -> Self {
83        Self::generate(&mut rand::rng())
84    }
85
86    pub fn verify(&self, msg: &[u8], signature: &Signature) -> bool {
87        self.0.verify(msg, &signature.0).is_ok()
88    }
89
90    pub fn starts_with(&self, needle: &[u8]) -> bool {
91        self.0.as_ref().starts_with(needle)
92    }
93}
94
95impl PartialOrd for PublicKey {
96    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
97        Some(self.cmp(other))
98    }
99}
100
101impl Ord for PublicKey {
102    fn cmp(&self, other: &Self) -> Ordering {
103        self.0.as_bytes().cmp(other.0.as_bytes())
104    }
105}
106
107impl fmt::LowerHex for PublicKey {
108    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
109        hex_fmt::HexFmt(self.0.as_bytes()).fmt(f)
110    }
111}
112
113impl Hashable for PublicKey {
114    fn update_hash<S: Digest>(&self, state: &mut S) {
115        self.0.as_bytes().update_hash(state)
116    }
117}
118
119impl AsRef<[u8]> for PublicKey {
120    fn as_ref(&self) -> &[u8] {
121        self.0.as_bytes()
122    }
123}
124
125impl TryFrom<&'_ [u8]> for PublicKey {
126    type Error = ext::SignatureError;
127
128    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
129        Ok(Self(bytes.try_into()?))
130    }
131}
132
133impl From<PublicKey> for [u8; PublicKey::SIZE] {
134    fn from(key: PublicKey) -> Self {
135        key.0.to_bytes()
136    }
137}
138
139impl fmt::Display for PublicKey {
140    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
141        write!(f, "{self:x}")
142    }
143}
144
145impl fmt::Debug for PublicKey {
146    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
147        write!(f, "{self:<8x}")
148    }
149}
150
151impl FromStr for PublicKey {
152    type Err = ParseError;
153
154    fn from_str(s: &str) -> Result<Self, Self::Err> {
155        let mut bytes = [0; Self::SIZE];
156        hex::decode_to_slice(s, &mut bytes).map_err(|_| ParseError)?;
157        Self::try_from(&bytes[..]).map_err(|_| ParseError)
158    }
159}
160
161#[derive(Debug, Error)]
162#[error("failed to parse public key")]
163pub struct ParseError;
164
165derive_sqlx_traits_for_byte_array_wrapper!(PublicKey);
166
167#[cfg(test)]
168mod test_utils {
169    use super::{Keypair, PublicKey};
170    use proptest::{
171        arbitrary::{Arbitrary, any},
172        array::UniformArrayStrategy,
173        num,
174        strategy::{Map, NoShrink, Strategy},
175    };
176
177    impl Arbitrary for Keypair {
178        type Parameters = ();
179        type Strategy = Map<
180            NoShrink<UniformArrayStrategy<num::u8::Any, [u8; Keypair::SECRET_KEY_SIZE]>>,
181            fn([u8; Keypair::SECRET_KEY_SIZE]) -> Self,
182        >;
183
184        fn arbitrary_with(_: Self::Parameters) -> Self::Strategy {
185            any::<[u8; Keypair::SECRET_KEY_SIZE]>()
186                .no_shrink()
187                .prop_map(|array| Keypair::from(&array))
188        }
189    }
190
191    impl Arbitrary for PublicKey {
192        type Parameters = ();
193        type Strategy = Map<<Keypair as Arbitrary>::Strategy, fn(Keypair) -> Self>;
194
195        fn arbitrary_with(_: Self::Parameters) -> Self::Strategy {
196            any::<Keypair>().prop_map(|keypair| keypair.public_key())
197        }
198    }
199}
200
201#[derive(PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
202#[repr(transparent)]
203pub struct Signature(ext::Signature);
204
205impl Signature {
206    pub const SIZE: usize = ext::SIGNATURE_LENGTH;
207
208    pub fn to_bytes(&self) -> [u8; Self::SIZE] {
209        self.0.to_bytes()
210    }
211}
212
213impl From<&'_ [u8; Self::SIZE]> for Signature {
214    fn from(bytes: &'_ [u8; Self::SIZE]) -> Self {
215        Self(ext::Signature::from(bytes))
216    }
217}
218
219impl TryFrom<&'_ [u8]> for Signature {
220    type Error = ext::SignatureError;
221
222    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
223        Ok(Signature(ext::Signature::try_from(bytes)?))
224    }
225}
226
227impl fmt::Debug for Signature {
228    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
229        write!(f, "Signature(_)")
230    }
231}
232
233impl sqlx::Type<Sqlite> for Signature {
234    fn type_info() -> SqliteTypeInfo {
235        <&[u8] as sqlx::Type<Sqlite>>::type_info()
236    }
237}
238
239impl<'q> sqlx::Encode<'q, Sqlite> for &'q Signature {
240    fn encode_by_ref(
241        &self,
242        args: &mut Vec<SqliteArgumentValue<'q>>,
243    ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
244        // It seems there is no way to avoid the allocation here because sqlx doesn't implement
245        // `Encode` for arrays.
246        sqlx::Encode::<Sqlite>::encode(self.to_bytes().to_vec(), args)
247    }
248}
249
250impl<'r> sqlx::Decode<'r, Sqlite> for Signature {
251    fn decode(value: SqliteValueRef<'r>) -> Result<Self, sqlx::error::BoxDynError> {
252        let slice = <&[u8] as sqlx::Decode<Sqlite>>::decode(value)?;
253        Ok(slice.try_into()?)
254    }
255}
256
257pub type SignatureError = ext::SignatureError;
258
259#[cfg(test)]
260mod tests {
261    use super::*;
262    use rand::{RngExt, SeedableRng, rngs::StdRng};
263
264    // This test asserts that signatures from the same keys and input are identical between
265    // different versions.
266    #[test]
267    fn compatibility() {
268        let mut rng = StdRng::seed_from_u64(0);
269        let keypair = Keypair::generate(&mut rng);
270
271        assert_eq!(
272            dump_signature(&keypair.sign(b"")),
273            "51ad17bc6bfbeeddd86c2a328d7a9b37197453244f4470a446ac9516acb4f243add7f93a5a6ba44bd21b9ed45c830dbbe28e2c40f7819d4c42c45b844258140a"
274        );
275
276        assert_eq!(
277            dump_signature(&keypair.sign(b"hello world")),
278            "bcbd9b3aee0031f9616ed873106f2a0a136572fb5182c71e8d56c1308098c7c687367608e99bb64ace8de09544e8d87dc46e0cdaa7d188ee78bfbfb7d754a703"
279        );
280
281        assert_eq!(
282            dump_signature(&keypair.sign(&rng.random::<[u8; 32]>())),
283            "3230b7f98529273c71f8af92b1581d290bf424fd7bd5015399c6213cbc461ca79ff932a7fcbb5e19d2ef6efa8ed9b833b6d17431793facf1b810c3b579570d0d"
284        );
285    }
286
287    fn dump_signature(signature: &Signature) -> String {
288        hex::encode(signature.to_bytes())
289    }
290}