modality_network_node/
config.rs

1use anyhow::{Context, Result};
2use libp2p::Multiaddr;
3use std::path::{Path,PathBuf};
4use std::fs;
5use serde::{Deserialize, Serialize};
6use serde_json;
7use libp2p::identity::Keypair;
8
9#[derive(Debug, Deserialize, Serialize, Default, Clone)]
10pub struct Config {
11    pub id: Option<String>,
12    pub passkey_path: Option<PathBuf>,
13    pub storage_path: Option<PathBuf>,
14    pub listeners: Option<Vec<Multiaddr>>,
15    pub bootstrappers: Option<Vec<Multiaddr>>,
16}
17
18impl Config {
19    pub fn from_filepath(path: &Path) -> Result<Config> {
20        let file = fs::File::open(path)
21            .context("Failed to open config file")?;
22        let mut config: Config = serde_json::from_reader(file)
23            .context("Failed to parse config file")?;
24    
25        let config_dir = path.parent().unwrap();
26    
27        if let Some(passkey_path_buf) = config.passkey_path {
28            let passkey_path = passkey_path_buf.as_path();
29            let abs_passkey_path = to_absolute_path(config_dir, passkey_path)?;
30            config.passkey_path = Some(abs_passkey_path);
31        }
32    
33        if let Some(storage_path_buf) = config.storage_path {
34            let storage_path = storage_path_buf.as_path();
35            let abs_storage_path = to_absolute_path(config_dir, storage_path)?;
36            config.storage_path = Some(abs_storage_path);
37        }
38    
39        Ok(config)
40    }
41
42    pub async fn get_libp2p_keypair(&self) -> Result<Keypair>{
43        let passkey = modality_utils::passkey::Passkey::load_file(self.passkey_path.clone().unwrap(), true).await?;
44        let node_keypair = modality_utils::libp2p_identity_keypair::libp2p_identity_from_private_key(passkey.keypair.private_key().as_str()).await?;
45        Ok(node_keypair)
46    }
47}
48
49pub fn to_absolute_path<P: AsRef<Path>>(base_dir: P, relative_path: P) -> Result<PathBuf> {
50    let base_dir = base_dir.as_ref().canonicalize()?;
51    let path = relative_path.as_ref();
52    
53    if path.is_absolute() {
54        Ok(path.to_path_buf())
55    } else {
56        Ok(base_dir.join(path))
57    }
58}