Skip to main content

syncweb_core/node/
identity.rs

1use iroh::SecretKey;
2use std::path::{Path, PathBuf};
3use anyhow::Result;
4
5#[derive(Clone)]
6pub struct IdentityManager {
7    secret_key: SecretKey,
8    path: PathBuf,
9}
10
11impl IdentityManager {
12    pub fn new(path: impl Into<PathBuf>) -> Result<Self> {
13        let path = path.into();
14        if path.exists() {
15            let bytes = std::fs::read(&path)?;
16            let arr: [u8; 32] = bytes.try_into().map_err(|_| {
17                anyhow::anyhow!("invalid secret key file: expected 32 bytes")
18            })?;
19            let secret_key = SecretKey::from_bytes(&arr);
20            Ok(Self { secret_key, path })
21        } else {
22            let secret_key = SecretKey::generate();
23            let bytes = secret_key.to_bytes();
24            if let Some(parent) = path.parent() {
25                std::fs::create_dir_all(parent)?;
26            }
27            std::fs::write(&path, bytes)?;
28            Ok(Self { secret_key, path })
29        }
30    }
31
32    pub fn node_id(&self) -> iroh::PublicKey {
33        self.secret_key.public()
34    }
35
36    pub fn secret_key(&self) -> &SecretKey {
37        &self.secret_key
38    }
39
40    pub fn path(&self) -> &Path {
41        &self.path
42    }
43}