Skip to main content

hashiverse_lib/tools/
server_id.rs

1//! # Server identity with proof-of-work birth certificate
2//!
3//! [`ServerId`] is the stable identity of a single server node. Unlike [`crate::tools::client_id::ClientId`],
4//! which costs nothing to produce, a `ServerId` is expensive: the server's 32-byte `Id`
5//! is the *reversed* bytes of a PoW hash computed over the server's keys, a random
6//! sponsor id, a timestamp, and a random content hash — with a minimum leading-zero-bit
7//! count (`SERVER_KEY_POW_MIN`) configured in [`crate::tools::config`].
8//!
9//! Reversing the PoW hash means the id naturally has a large number of **trailing**
10//! zero bits. The Kademlia DHT distributes responsibility by XOR distance, and the
11//! trailing-zero structure spreads servers evenly across the keyspace while making
12//! every id independently verifiable: anyone can recompute the PoW from the fields
13//! embedded in the `ServerId` and confirm the id is real.
14//!
15//! The PoW therefore acts as a "birth certificate" that gates server identities —
16//! you can't cheaply spin up thousands of sybil servers targeting a specific keyspace
17//! region because each id costs real CPU time.
18//!
19//! Beyond identity:
20//! - [`ServerId::to_peer`] wraps the identity into a [`crate::protocol::peer::Peer`]
21//!   for gossip on the DHT, signing the result with the server's private key.
22//! - [`ServerId::encode`] / [`ServerId::decode`] provide a compact fixed-length byte
23//!   representation for on-disk persistence.
24//! - [`ServerId::verify`] re-runs the PoW check and confirms the embedded id matches.
25
26use crate::protocol::peer::{Peer, PeerPow};
27use crate::tools::keys::Keys;
28use crate::tools::parallel_pow_generator::ParallelPowGenerator;
29use crate::tools::time::{TimeMillis, TimeMillisBytes, TIME_MILLIS_BYTES};
30use crate::tools::time_provider::time_provider::TimeProvider;
31use crate::tools::types::{Hash, Id, PQCommitmentBytes, Pow, Salt, Signature, SignatureKey, VerificationKey, VerificationKeyBytes, HASH_BYTES, ID_BYTES, PQ_COMMITMENT_BYTES, SALT_BYTES, SIGNATURE_KEY_BYTES, VERIFICATION_KEY_BYTES};
32use crate::tools::{config, pow, tools, types};
33use std::fmt;
34
35#[derive(Clone)]
36pub struct ServerId {
37    pub keys: Keys,
38
39    // Proof of initial work
40    pub sponsor_id: Id,
41    pub timestamp: TimeMillis,
42    pub hash: Hash,
43    pub salt: Salt,
44    pub pow: Pow,
45
46    pub id: Id,
47}
48
49impl ServerId {
50    pub fn id_hex(&self) -> String {
51        hex::encode(self.id)
52    }
53
54    pub fn server_pow_hash_to_id(hash: Hash) -> anyhow::Result<Id> {
55        if hash.len() != ID_BYTES {
56            anyhow::bail!("Invalid Hash length: expected {} bytes, got {} bytes", ID_BYTES, hash.len());
57        }
58
59        let id = Id(tools::reverse_bytes(hash.as_bytes()));
60        Ok(id)
61    }
62
63    // Generates the initial pow hash for a server.
64    pub async fn pow_generate(
65        label: &str,
66        time_provider: &dyn TimeProvider,
67        pow_min: Pow,
68        sponsor_id: &Id,
69        verification_key: &VerificationKeyBytes,
70        pq_commitment_bytes: &PQCommitmentBytes,
71        content_hash: &Hash,
72        pow_generator: &dyn ParallelPowGenerator,
73    ) -> anyhow::Result<(TimeMillis, Salt, Pow, Hash)> {
74        let timestamp = time_provider.current_time_millis();
75        let timestamp_be = timestamp.encode_be();
76        let datas = [sponsor_id.as_ref(), verification_key.as_ref(), pq_commitment_bytes.as_ref(), timestamp_be.as_ref(), content_hash.as_ref()];
77        let data_hash = pow::pow_compute_data_hash(&datas);
78        let (salt, pow, pow_hash) = pow_generator.generate(label, pow_min, data_hash).await?;
79        Ok((timestamp, salt, pow, pow_hash))
80    }
81
82    pub fn pow_measure(sponsor_id: &Id, verification_key: &VerificationKeyBytes, pqcommitment_bytes: &PQCommitmentBytes, timestamp_be: &TimeMillisBytes, content_hash: &Hash, salt: &Salt) -> anyhow::Result<(Pow, Hash)> {
83        pow::pow_measure(&[sponsor_id.as_ref(), verification_key.as_ref(), pqcommitment_bytes.as_ref(), timestamp_be.as_ref(), content_hash.as_ref()], salt)
84    }
85
86    pub async fn new(label: &str, time_provider: &dyn TimeProvider, pow_min: Pow, skip_pq_commitment_bytes: bool, pow_generator: &dyn ParallelPowGenerator) -> anyhow::Result<Self> {
87        let sponsor_id = Id::random();
88        let keys = Keys::from_rnd(skip_pq_commitment_bytes)?;
89        let hash = Hash::random();
90        let (timestamp, salt, pow, pow_hash) = ServerId::pow_generate(label, time_provider, pow_min, &sponsor_id, &keys.verification_key_bytes, &keys.pq_commitment_bytes, &hash, pow_generator).await?;
91        let id = ServerId::server_pow_hash_to_id(pow_hash)?;
92
93        Ok(ServerId {
94            keys,
95            sponsor_id,
96            timestamp,
97            hash,
98            salt,
99            pow,
100            id,
101        })
102    }
103
104    pub fn to_peer(&self, time_provider: &dyn TimeProvider) -> anyhow::Result<Peer> {
105        let mut peer = Peer {
106            id: self.id,
107            verification_key_bytes: self.keys.verification_key_bytes,
108            pq_commitment_bytes: self.keys.pq_commitment_bytes,
109
110            pow_initial: PeerPow {
111                sponsor_id: self.sponsor_id,
112                timestamp: self.timestamp,
113                content_hash: self.hash,
114                salt: self.salt,
115                pow: self.pow,
116            },
117
118            pow_current_day: PeerPow {
119                sponsor_id: self.sponsor_id,
120                timestamp: self.timestamp,
121                content_hash: self.hash,
122                salt: self.salt,
123                pow: self.pow,
124            },
125
126            pow_current_month: PeerPow {
127                sponsor_id: self.sponsor_id,
128                timestamp: self.timestamp,
129                content_hash: self.hash,
130                salt: self.salt,
131                pow: self.pow,
132            },
133
134            address: "".to_string(),
135            version: env!("CARGO_PKG_VERSION").to_string(),
136
137            timestamp: TimeMillis::zero(),
138            signature: Signature::zero(),
139        };
140
141        // Sign the peer
142        peer.sign(time_provider, &self.keys.signature_key)?;
143
144        Ok(peer)
145    }
146
147    pub fn verify(&self) -> anyhow::Result<()> {
148        let (pow, pow_hash) = ServerId::pow_measure(&self.sponsor_id, &self.keys.verification_key_bytes, &self.keys.pq_commitment_bytes, &self.timestamp.encode_be(), &self.hash, &self.salt)?;
149        if pow != self.pow {
150            anyhow::bail!("ServerID pow does not verify");
151        }
152
153        if pow < config::SERVER_KEY_POW_MIN {
154            anyhow::bail!("ServerID pow is not sufficient");
155        }
156
157        let id = ServerId::server_pow_hash_to_id(pow_hash)?;
158
159        if id != self.id {
160            anyhow::bail!("ServerID id does not verify");
161        }
162
163        Ok(())
164    }
165
166    pub fn encode(&self) -> anyhow::Result<Vec<u8>> {
167        let mut bytes = Vec::new();
168        {
169            bytes.extend_from_slice(self.keys.signature_key.as_ref());
170            bytes.extend_from_slice(self.keys.verification_key.as_ref());
171            bytes.extend_from_slice(self.keys.pq_commitment_bytes.as_ref());
172            bytes.extend_from_slice(self.sponsor_id.as_ref());
173            bytes.extend_from_slice(self.timestamp.encode_be().as_ref());
174            bytes.extend_from_slice(self.hash.as_ref());
175            bytes.extend_from_slice(self.salt.as_ref());
176            bytes.push(self.pow.0);
177            bytes.extend_from_slice(self.id.as_ref());
178        }
179
180        // Sanity check
181        let expected_len = SIGNATURE_KEY_BYTES + VERIFICATION_KEY_BYTES + PQ_COMMITMENT_BYTES + ID_BYTES + TIME_MILLIS_BYTES + HASH_BYTES + SALT_BYTES + 1 + types::ID_BYTES;
182        if bytes.len() != expected_len {
183            anyhow::bail!("incorrect byte count: expected {}, got {}", expected_len, bytes.len());
184        }
185
186        Ok(bytes)
187    }
188
189    pub fn decode(bytes: &[u8]) -> anyhow::Result<Self> {
190        // Sanity check
191        let expected_len = SIGNATURE_KEY_BYTES + VERIFICATION_KEY_BYTES + PQ_COMMITMENT_BYTES + ID_BYTES + TIME_MILLIS_BYTES + HASH_BYTES + SALT_BYTES + 1 + types::ID_BYTES;
192        if bytes.len() != expected_len {
193            anyhow::bail!("incorrect byte count: expected {}, got {}", expected_len, bytes.len());
194        }
195
196        let mut pos = 0;
197
198        let signature_key_bytes = &bytes[pos..pos + SIGNATURE_KEY_BYTES];
199        pos += SIGNATURE_KEY_BYTES;
200        let verification_key_bytes = &bytes[pos..pos + VERIFICATION_KEY_BYTES];
201        pos += VERIFICATION_KEY_BYTES;
202        let pq_commitment_bytes = &bytes[pos..pos + PQ_COMMITMENT_BYTES];
203        pos += PQ_COMMITMENT_BYTES;
204        let sponsor_id = Id::from_slice(bytes[pos..pos + ID_BYTES].try_into()?)?;
205        pos += ID_BYTES;
206        let timestamp = TimeMillis::timestamp_decode_be(&TimeMillisBytes::from_bytes(&bytes[pos..pos + 8])?);
207        pos += TIME_MILLIS_BYTES;
208        let hash = Hash::from_slice(bytes[pos..pos + HASH_BYTES].try_into()?)?;
209        pos += HASH_BYTES;
210        let salt = Salt::from_slice(bytes[pos..pos + SALT_BYTES].try_into()?)?;
211        pos += SALT_BYTES;
212        let pow = Pow(bytes[pos]);
213        pos += 1;
214        let id_bytes = &bytes[pos..pos + types::ID_BYTES];
215
216        // Recreate keys
217        let signature_key_arr: &[u8; 32] = signature_key_bytes.try_into()?;
218        let verification_key_arr: &[u8; 32] = verification_key_bytes.try_into()?;
219        let signature_key = SignatureKey::from_bytes(signature_key_arr)?;
220        let verification_key = VerificationKey::from_bytes_raw(verification_key_arr)?;
221        let verification_key_bytes = verification_key.to_verification_key_bytes();
222        let pq_commitment = PQCommitmentBytes::from_slice(pq_commitment_bytes)?;
223
224        let keys = Keys {
225            signature_key,
226            verification_key,
227            verification_key_bytes,
228            pq_commitment_bytes: pq_commitment,
229        };
230
231        let id = Id::from_slice(id_bytes)?;
232
233        Ok(ServerId {
234            keys,
235            sponsor_id,
236            timestamp,
237            hash,
238            salt,
239            pow,
240            id,
241        })
242    }
243}
244
245impl fmt::Display for ServerId {
246    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
247        write!(f, "[ id={} pow={} hash={} salt={} keys={} ]", self.id,  self.pow, self.hash, self.salt, self.keys)
248    }
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254    use crate::tools::parallel_pow_generator::StubParallelPowGenerator;
255    use crate::tools::time_provider::time_provider::RealTimeProvider;
256
257    #[tokio::test]
258    async fn pow_test() -> anyhow::Result<()> {
259        let time_provider = RealTimeProvider::default();
260        let pow_generator = StubParallelPowGenerator::new();
261        const POW_MAX: u8 = 2 * 8;
262        for pow_min in 0..POW_MAX {
263            let server_id = ServerId::new("own_pow", &time_provider, Pow(pow_min), true, &pow_generator).await?;
264            assert!(server_id.pow >= Pow(pow_min));
265        }
266
267        Ok(())
268    }
269
270    #[tokio::test]
271    async fn server_id_encode_decode_verify() -> anyhow::Result<()> {
272        let time_provider = RealTimeProvider::default();
273        let pow_generator = StubParallelPowGenerator::new();
274        let server_id = ServerId::new("own_pow", &time_provider, Pow(8), false, &pow_generator).await?;
275        let encoded = server_id.encode()?;
276        let decoded = ServerId::decode(&encoded)?;
277        decoded.verify()?;
278        Ok(())
279    }
280
281    #[tokio::test]
282    async fn server_id_encode_decode_reversibility() -> anyhow::Result<()> {
283        let time_provider = RealTimeProvider::default();
284        let pow_generator = StubParallelPowGenerator::new();
285        let server_id = ServerId::new("own_pow", &time_provider, Pow(8), false, &pow_generator).await?;
286
287        let server_id_encoded = server_id.encode()?;
288        let server_id2 = ServerId::decode(&server_id_encoded)?;
289
290        // Thoroughly compare all fields
291        // If Keys/Id derive PartialEq, this is enough:
292        assert_eq!(server_id.keys.signature_key, server_id2.keys.signature_key, "Keys do not match after decode");
293        assert_eq!(server_id.keys.verification_key, server_id2.keys.verification_key, "Keys do not match after decode");
294        assert_eq!(server_id.keys.pq_commitment_bytes, server_id2.keys.pq_commitment_bytes, "Keys do not match after decode");
295        assert_eq!(server_id.timestamp, server_id2.timestamp, "Timestamps do not match");
296        assert_eq!(server_id.salt, server_id2.salt, "Salts do not match");
297        assert_eq!(server_id.pow, server_id2.pow, "PoW bits do not match");
298        assert_eq!(server_id.id, server_id2.id, "IDs do not match");
299
300        Ok(())
301    }
302}