1use std::{error::Error, path::Path};
2
3use base64::prelude::*;
4use libp2p_identity::{Keypair, PeerId};
5use serde::{Deserialize, Serialize};
6
7#[derive(Clone, Serialize, Deserialize)]
8#[serde(rename_all = "PascalCase")]
9pub(crate) struct Config {
10 pub(crate) identity: Identity,
11}
12
13impl Config {
14 pub(crate) fn from_file(path: &Path) -> Result<Self, Box<dyn Error>> {
15 Ok(serde_json::from_str(&std::fs::read_to_string(path)?)?)
16 }
17
18 pub(crate) fn from_key_material(
19 peer_id: PeerId,
20 keypair: &Keypair,
21 ) -> Result<Self, Box<dyn Error>> {
22 let priv_key = BASE64_STANDARD.encode(keypair.to_protobuf_encoding()?);
23 let peer_id = peer_id.to_base58();
24 Ok(Self {
25 identity: Identity { peer_id, priv_key },
26 })
27 }
28}
29
30#[derive(Clone, Serialize, Deserialize)]
31#[serde(rename_all = "PascalCase")]
32pub(crate) struct Identity {
33 #[serde(rename = "PeerID")]
34 pub(crate) peer_id: String,
35 pub(crate) priv_key: String,
36}
37
38impl zeroize::Zeroize for Config {
39 fn zeroize(&mut self) {
40 self.identity.peer_id.zeroize();
41 self.identity.priv_key.zeroize();
42 }
43}