Use FNV-1a hash instead of SHA2 for relay ID generation

This commit is contained in:
Marcin Kulik
2025-05-11 20:24:24 +02:00
parent 299242550d
commit 71fc63d164
6 changed files with 39 additions and 20 deletions

1
Cargo.lock generated
View File

@@ -104,7 +104,6 @@ dependencies = [
"scraper",
"serde",
"serde_json",
"sha2",
"signal-hook",
"tempfile",
"termion",

View File

@@ -42,7 +42,6 @@ rgb = "0.8.37"
url = "2.5.0"
tokio-tungstenite = { version = "0.26.2", features = ["rustls-tls-native-roots"] }
rustls = { version = "0.23.26", default-features = false, features = ["aws_lc_rs"] }
sha2 = "0.10.8"
tokio-util = "0.7.10"
[build-dependencies]

View File

@@ -22,6 +22,7 @@ use crate::config::{self, Config};
use crate::encoder::{AsciicastV2Encoder, AsciicastV3Encoder, RawEncoder, TextEncoder};
use crate::file_writer::{FileWriterStarter, Metadata};
use crate::forwarder;
use crate::hash;
use crate::locale;
use crate::notifier::{self, Notifier, NullNotifier};
use crate::pty;
@@ -30,7 +31,6 @@ use crate::session::{self, KeyBindings, SessionStarter};
use crate::status;
use crate::stream::Stream;
use crate::tty::{DevTty, FixedSizeTty, NullTty, Tty};
use crate::util;
impl cli::Session {
pub fn run(mut self, config: &Config) -> Result<()> {
@@ -375,7 +375,7 @@ struct Relay {
impl Relay {
fn id(&self) -> String {
util::sha2_digest(self.ws_producer_url.as_ref())
format!("{:x}", hash::fnv1a_128(self.ws_producer_url.as_ref()))
}
}

36
src/hash.rs Normal file
View File

@@ -0,0 +1,36 @@
// This module implements FNV-1a hashing algorithm
// http://www.isthe.com/chongo/tech/comp/fnv/
const FNV_128_PRIME: u128 = 309485009821345068724781371; // 2^88 + 2^8 + 0x3b
const FNV_128_OFFSET_BASIS: u128 = 144066263297769815596495629667062367629;
pub fn fnv1a_128<D: AsRef<[u8]>>(data: D) -> u128 {
let mut hash = FNV_128_OFFSET_BASIS;
for byte in data.as_ref() {
hash ^= *byte as u128;
hash = hash.wrapping_mul(FNV_128_PRIME);
}
hash
}
#[cfg(test)]
mod tests {
use super::fnv1a_128;
#[test]
fn digest() {
assert_eq!(
fnv1a_128("Hello World!"),
0xd2d42892ede872031d2593366229c2d2
);
assert_eq!(
fnv1a_128("Hello world!"),
0x3c94fff9ede872031d95566a45770eb2
);
assert_eq!(fnv1a_128("🦄🌈"), 0xa25841ae4659905b36cb0d359fad39f);
}
}

View File

@@ -7,6 +7,7 @@ mod config;
mod encoder;
mod file_writer;
mod forwarder;
mod hash;
mod io;
mod leb128;
mod locale;

View File

@@ -1,10 +1,8 @@
use std::fmt::Write;
use std::path::{Path, PathBuf};
use std::{io, thread};
use anyhow::{anyhow, bail, Result};
use reqwest::Url;
use sha2::Digest;
use tempfile::NamedTempFile;
pub fn get_local_path(filename: &str) -> Result<Box<dyn AsRef<Path>>> {
@@ -118,20 +116,6 @@ impl Utf8Decoder {
}
}
pub fn sha2_digest(s: &str) -> String {
let mut hasher = sha2::Sha224::new();
hasher.update(s.as_bytes());
hasher
.finalize()
.as_slice()
.iter()
.fold(String::new(), |mut out, byte| {
let _ = write!(out, "{byte:02X}");
out
})
}
#[cfg(test)]
mod tests {
use super::Utf8Decoder;