Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: include connected peers in node #1206

Merged
merged 2 commits into from
Jan 22, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions sn_protocol/src/node_registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,39 @@ where
}
}

fn serialize_connected_peers<S>(
connected_peers: &Option<Vec<PeerId>>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match connected_peers {
Some(peers) => {
let peer_strs: Vec<String> = peers.iter().map(|p| p.to_string()).collect();
serializer.serialize_some(&peer_strs)
}
None => serializer.serialize_none(),
}
}

fn deserialize_connected_peers<'de, D>(deserializer: D) -> Result<Option<Vec<PeerId>>, D::Error>
where
D: Deserializer<'de>,
{
let vec: Option<Vec<String>> = Option::deserialize(deserializer)?;
match vec {
Some(peer_strs) => {
let peers: Result<Vec<PeerId>, _> = peer_strs
.into_iter()
.map(|s| PeerId::from_str(&s).map_err(DeError::custom))
.collect();
peers.map(Some)
}
None => Ok(None),
}
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Node {
pub genesis: bool,
Expand All @@ -70,6 +103,11 @@ pub struct Node {
pub data_dir_path: Option<PathBuf>,
pub log_dir_path: Option<PathBuf>,
pub safenode_path: Option<PathBuf>,
#[serde(
serialize_with = "serialize_connected_peers",
deserialize_with = "deserialize_connected_peers"
)]
pub connected_peers: Option<Vec<PeerId>>,
}

impl Node {
Expand Down Expand Up @@ -101,6 +139,11 @@ pub struct NodeRegistry {

impl NodeRegistry {
pub fn save(&self) -> Result<()> {
let path = Path::new(&self.save_path);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}

let json = serde_json::to_string(self)?;
let mut file = std::fs::File::create(self.save_path.clone())?;
file.write_all(json.as_bytes())?;
Expand Down
Loading