changelog shortlog graph tags branches changeset files revisions annotate raw help

Mercurial > core / rust/lib/hash/src/lib.rs

changeset 698: 96958d3eb5b0
parent: 8e94959e96bd
author: Richard Westhaver <ellis@rwest.io>
date: Fri, 04 Oct 2024 22:04:59 -0400
permissions: -rw-r--r--
description: fixes
1 //! hash - wrapper for hash algorithms and types
2 pub use blake3::{
3  derive_key, hash, keyed_hash, Hash as B3Hash, Hasher as B3Hasher,
4  OutputReader,
5 };
6 pub use hex;
7 pub use phf;
8 use rand::Rng;
9 use serde::{Deserialize, Serialize};
10 pub use sha2::Sha512;
11 // hashbrown is now the default for the Rust stdlib. We only need to
12 // re-export in no_std envs.
13 pub use hashbrown::{HashMap, HashSet};
14 pub use std::hash::{Hash, Hasher};
15 
16 pub const KEY_LEN: usize = 32;
17 pub const OUT_LEN: usize = 32;
18 pub const OUT_LEN_HEX: usize = OUT_LEN * 2;
19 
20 //mod tree;
21 #[cfg(test)]
22 mod tests;
23 /// a simple Id abstraction with help functions. I'm finding this easier than
24 /// state machines and traits for the time-being.
25 #[derive(
26  Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Serialize, Deserialize, Hash,
27 )]
28 pub struct Id(pub Vec<u8>);
29 
30 impl Id {
31  pub fn rand() -> Self {
32  let mut rng = rand::thread_rng();
33  let vals: Vec<u8> =
34  (0..KEY_LEN).map(|_| rng.gen_range(0..u8::MAX)).collect();
35  Id(vals)
36  }
37 
38  pub fn state_hash(&self, state: &mut B3Hasher) -> Self {
39  let mut output = vec![0; OUT_LEN];
40  state.update(&self.0);
41  let mut res = state.finalize_xof();
42  res.fill(&mut output);
43  Id(output)
44  }
45 
46  pub fn to_hex(&self) -> String {
47  hex::encode(&self.0)
48  }
49 }
50 
51 /// PeerId
52 ///
53 /// identifies a unique Peer
54 #[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd, Debug, Default)]
55 pub struct PeerId {
56  id: [u8; 32],
57 }
58 
59 impl PeerId {
60  pub fn new() -> Self {
61  Self::default()
62  }
63 
64  pub fn rand() -> Self {
65  let pd = rand::thread_rng().gen::<[u8; 32]>();
66  Self { id: pd }
67  }
68 
69  pub fn from_bytes(data: &[u8]) -> Self {
70  let pd = blake3::hash(data);
71  let hash = pd.as_bytes();
72  Self { id: *hash }
73  }
74 }