qs_core/
utils.rs

1use bincode::{Decode, Encode};
2use rustls::pki_types::{CertificateDer, PrivateKeyDer};
3
4use crate::common::FileSendRecvTree;
5/// Generate a self signed certificate and private key
6pub fn self_signed_cert() -> Result<(CertificateDer<'static>, PrivateKeyDer<'static>), rcgen::Error>
7{
8    let cert_key = rcgen::generate_simple_self_signed(vec!["localhost".to_string()])?;
9    let cert = cert_key.cert.der();
10    let key = cert_key.key_pair.serialize_der();
11
12    // let cer = CertificateDer::from(cert);
13
14    Ok((cert.to_owned(), key.try_into().unwrap()))
15}
16
17pub fn hash_files(files: FileSendRecvTree) -> u64 {
18    use std::collections::hash_map::DefaultHasher;
19    use std::hash::{Hash, Hasher};
20
21    let mut hasher = DefaultHasher::new();
22    files.hash(&mut hasher);
23    hasher.finish()
24}
25
26/// Helper struct to store the version, because [semver::Version] does not implement [Encode] and [Decode]
27#[derive(Debug, Clone, Encode, Decode)]
28pub struct Version {
29    /// The Major version represents the Protocol version used by qs-core & the roundezvous server
30    pub major: u64,
31    pub minor: u64,
32    pub patch: u64,
33}
34
35impl Version {
36    pub fn to_semver(&self) -> semver::Version {
37        semver::Version::new(self.major, self.minor, self.patch)
38    }
39
40    pub fn from_semver(version: semver::Version) -> Self {
41        Self {
42            major: version.major,
43            minor: version.minor,
44            patch: version.patch,
45        }
46    }
47
48    /// Check if the major version matches (only this matters for compatibility)
49    pub fn matches_major(&self, other: &Version) -> bool {
50        self.major == other.major
51    }
52}
53
54impl From<&'static str> for Version {
55    fn from(version: &str) -> Self {
56        let version = semver::Version::parse(version).unwrap();
57        Self::from_semver(version)
58    }
59}
60
61impl From<semver::Version> for Version {
62    fn from(version: semver::Version) -> Self {
63        Self::from_semver(version)
64    }
65}
66
67impl std::fmt::Display for Version {
68    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
70    }
71}