1use crate::error::ModelsError;
4use massa_signature::PublicKey;
5use serde_with::{DeserializeFromStr, SerializeDisplay};
6
7#[derive(
9 Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd, SerializeDisplay, DeserializeFromStr,
10)]
11pub struct NodeId(PublicKey);
12
13const NODEID_PREFIX: char = 'N';
14
15impl NodeId {
16 pub fn new(public_key: PublicKey) -> Self {
18 Self(public_key)
19 }
20
21 pub fn get_public_key(&self) -> PublicKey {
23 self.0
24 }
25}
26
27impl std::fmt::Display for NodeId {
28 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
29 write!(
30 f,
31 "{}{}",
32 NODEID_PREFIX,
33 bs58::encode(self.0.to_bytes()).with_check().into_string()
34 )
35 }
36}
37
38impl std::fmt::Debug for NodeId {
39 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
40 write!(f, "{}", self)
41 }
42}
43
44impl std::str::FromStr for NodeId {
45 type Err = ModelsError;
46 fn from_str(s: &str) -> Result<Self, Self::Err> {
61 let mut chars = s.chars();
62 match chars.next() {
63 Some(prefix) if prefix == NODEID_PREFIX => {
64 let data = chars.collect::<String>();
65 let decoded_bs58_check = bs58::decode(data)
66 .with_check(None)
67 .into_vec()
68 .map_err(|_| ModelsError::NodeIdParseError)?;
69 Ok(NodeId(PublicKey::from_bytes(&decoded_bs58_check)?))
70 }
71 _ => Err(ModelsError::NodeIdParseError),
72 }
73 }
74}