Skip to main content

hypercore_protocol/
util.rs

1use blake2::{
2    Blake2bMac,
3    digest::{FixedOutput, Update, typenum::U32},
4};
5use std::{
6    convert::TryInto,
7    io::{Error, ErrorKind},
8};
9
10use crate::{DiscoveryKey, constants::DISCOVERY_NS_BUF};
11
12/// Calculate the discovery key of a key.
13///
14/// The discovery key is a 32 byte namespaced hash of the key.
15pub fn discovery_key(key: &[u8]) -> DiscoveryKey {
16    let mut hasher = Blake2bMac::<U32>::new_with_salt_and_personal(key, &[], &[]).unwrap();
17    hasher.update(DISCOVERY_NS_BUF);
18    hasher.finalize_fixed().as_slice().try_into().unwrap()
19}
20
21pub(crate) fn pretty_hash(key: &[u8]) -> String {
22    pretty_hash::fmt(key).unwrap_or_else(|_| "<invalid>".into())
23}
24
25pub(crate) fn map_channel_err<T>(err: async_channel::SendError<T>) -> Error {
26    Error::new(
27        ErrorKind::BrokenPipe,
28        format!("Cannot forward on channel: {err}"),
29    )
30}