changelog shortlog graph tags branches changeset files revisions annotate raw help

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

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