1use std::fmt;
4
5use borsh::{BorshDeserialize, BorshSerialize};
6use serde::{Deserialize, Serialize};
7
8use crate::crypto::{Keypair, PubKey, SecKey, SecretSigner, Signature};
9use crate::error::{BlossomError, Result};
10
11#[derive(
12 Serialize,
13 Deserialize,
14 BorshSerialize,
15 BorshDeserialize,
16 Clone,
17 PartialEq,
18 Eq,
19 Hash,
20 PartialOrd,
21 Ord,
22 Default,
23)]
24pub struct NodeIdentity {
25 pub public_key: PubKey,
26 #[serde(skip_serializing, skip_deserializing, default)]
27 #[borsh(skip)]
28 secret_key: Option<SecKey>,
29 pub protocol: String,
30 pub host: String,
31 pub port: u16,
32 pub shuffle: bool,
33}
34
35impl fmt::Debug for NodeIdentity {
36 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37 f.debug_struct("NodeIdentity")
38 .field("public_key", &self.public_key)
39 .field(
40 "signing_material",
41 &self.secret_key.as_ref().map(|_| "[REDACTED]"),
42 )
43 .field("protocol", &self.protocol)
44 .field("host", &self.host)
45 .field("port", &self.port)
46 .field("shuffle", &self.shuffle)
47 .finish()
48 }
49}
50
51impl NodeIdentity {
52 pub fn new(
53 public_key: PubKey,
54 secret_key: Option<SecKey>,
55 protocol: impl Into<String>,
56 host: impl Into<String>,
57 port: u16,
58 shuffle: bool,
59 ) -> Self {
60 Self {
61 public_key,
62 secret_key,
63 protocol: protocol.into(),
64 host: host.into(),
65 port,
66 shuffle,
67 }
68 }
69
70 pub fn generate(protocol: impl Into<String>, host: impl Into<String>, port: u16) -> Self {
71 let keypair = Keypair::generate();
72 Self::new(
73 keypair.public,
74 Some(keypair.secret.clone()),
75 protocol,
76 host,
77 port,
78 true,
79 )
80 }
81
82 pub fn public_key(&self) -> PubKey {
83 self.public_key
84 }
85
86 pub fn public_only(&self) -> Self {
87 let mut identity = self.clone();
88 identity.secret_key = None;
89 identity
90 }
91
92 pub fn has_signing_material(&self) -> bool {
93 self.secret_key.is_some()
94 }
95
96 pub fn signer(&self) -> Result<SecretSigner> {
97 let secret_key = self
98 .secret_key
99 .as_ref()
100 .ok_or(BlossomError::MissingSecretKey)?;
101 let signer = SecretSigner::new(secret_key);
102 if !signer.matches_public_key(&self.public_key) {
103 return Err(BlossomError::KeyMismatch);
104 }
105 Ok(signer)
106 }
107
108 pub fn sign(&self, message: &[u8]) -> Result<Signature> {
109 Ok(self.signer()?.sign(message))
110 }
111
112 pub fn verify(signature: &Signature, message: &[u8], public_key: &PubKey) -> Result<()> {
113 signature.verify(message, public_key)
114 }
115}
116
117#[derive(
118 Serialize, Deserialize, BorshSerialize, BorshDeserialize, Debug, Clone, PartialEq, Eq, Default,
119)]
120pub enum NodeType {
121 #[default]
122 Validator,
123 Observer,
124 Consort,
125}
126
127#[cfg(test)]
128mod tests {
129 use super::*;
130
131 #[test]
132 fn generated_node_can_sign_and_verify() {
133 let node = NodeIdentity::generate("tcp", "127.0.0.1", 8080);
134 let message = b"node-message";
135 let signature = node.sign(message).unwrap();
136
137 assert_eq!(node.protocol, "tcp");
138 assert_eq!(node.host, "127.0.0.1");
139 assert_eq!(node.port, 8080);
140 assert!(NodeIdentity::verify(&signature, message, &node.public_key()).is_ok());
141 }
142
143 #[test]
144 fn missing_secret_key_cannot_sign() {
145 let node = NodeIdentity::new(PubKey([9; 32]), None, "tcp", "localhost", 1, false);
146
147 assert_eq!(node.sign(b"message"), Err(BlossomError::MissingSecretKey));
148 }
149
150 #[test]
151 fn mismatched_secret_key_cannot_sign() {
152 let public = Keypair::generate().public;
153 let secret = Keypair::generate().secret;
154 let node = NodeIdentity::new(public, Some(secret), "tcp", "localhost", 1, false);
155
156 assert_eq!(node.sign(b"message"), Err(BlossomError::KeyMismatch));
157 }
158
159 #[test]
160 fn serialization_omits_secret_key() {
161 let node = NodeIdentity::generate("tcp", "localhost", 9000);
162 let json = serde_json::to_string(&node).unwrap();
163 let decoded = serde_json::from_str::<NodeIdentity>(&json).unwrap();
164 let borsh = borsh::to_vec(&node).unwrap();
165 let decoded_borsh = borsh::from_slice::<NodeIdentity>(&borsh).unwrap();
166
167 assert!(!json.contains("secret_key"));
168 assert_eq!(decoded.secret_key, None);
169 assert_eq!(decoded_borsh.secret_key, None);
170 assert_eq!(decoded.public_key, node.public_key);
171 assert!(
172 !format!("{node:?}")
173 .contains(&hex::encode(node.secret_key.as_ref().unwrap().as_array()))
174 );
175 }
176}