use crate::dht::{Error, Result};
use crc::{Crc, CRC_32_ISCSI};
use rand::{rng, Rng, RngExt};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use sha1::{Digest, Sha1};
use std::fmt::{Debug, Display, Formatter};
use std::net::{IpAddr, SocketAddr};
use std::result;
const NODE_ID_SIZE: usize = 20;
const MAX_DISTANCE: u8 = NODE_ID_SIZE as u8 * 8; const CRC32: Crc<u32> = Crc::<u32>::new(&CRC_32_ISCSI);
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub struct NodeId([u8; NODE_ID_SIZE]);
impl NodeId {
pub fn new() -> Self {
let mut random_bytes = [0u8; NODE_ID_SIZE];
rand::rng().fill_bytes(&mut random_bytes);
let hash = Sha1::digest(&random_bytes);
let mut node_id = [0u8; NODE_ID_SIZE];
node_id.copy_from_slice(hash.as_ref());
Self(node_id)
}
pub fn from_ip(addr: &IpAddr) -> Self {
Self::from_ip_with_rand(addr, rng().random::<u8>())
}
pub fn from_ip_with_rand(ip: &IpAddr, rand: u8) -> Self {
const IPV4_MASK: [u8; 4] = [0x03, 0x0f, 0x3f, 0xff];
const IPV6_MASK: [u8; 8] = [0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff];
let (mut ip_bytes, mask): (Vec<u8>, &[u8]) = match ip {
IpAddr::V4(ipv4) => (ipv4.octets().to_vec(), &IPV4_MASK),
IpAddr::V6(ipv6) => (ipv6.octets()[..8].to_vec(), &IPV6_MASK),
};
for (i, m) in mask.iter().enumerate() {
ip_bytes[i] &= m;
}
let r: u8 = rand & 0x7; ip_bytes[0] |= r << 5;
let ip_hash = CRC32.checksum(&ip_bytes).to_be_bytes();
let mut id_bytes = [0u8; NODE_ID_SIZE];
rand::rng().fill_bytes(&mut id_bytes);
id_bytes[0] = ip_hash[0];
id_bytes[1] = ip_hash[1];
id_bytes[2] = (ip_hash[2] & 0xf8) | rng().random_range(0..=0x7);
id_bytes[19] = rand;
Self(id_bytes)
}
pub fn as_slice(&self) -> &[u8] {
&self.0
}
pub fn as_node_slice(&self) -> &[u8; NODE_ID_SIZE] {
&self.0
}
pub fn xor(&self, node: &NodeId) -> NodeId {
let mut result = [0u8; NODE_ID_SIZE];
for (i, (a, b)) in self.0.iter().zip(node.0).enumerate() {
result[i] = a ^ b;
}
result.into()
}
pub fn leading_zeros(&self) -> u8 {
for (i, byte) in self.0.iter().enumerate() {
if *byte != 0 {
return (i as u32 * 8 + byte.leading_zeros()) as u8;
}
}
160
}
pub fn distance(&self, node: &NodeId) -> u8 {
let leading_zeros = self.xor(node).leading_zeros();
MAX_DISTANCE - leading_zeros
}
pub fn verify_id(&self, source_ip: &IpAddr) -> bool {
self.is_secure_id(&source_ip) || self.is_plausible_legacy_id()
}
pub fn is_secure_id(&self, source_ip: &IpAddr) -> bool {
if source_ip.is_local() {
return true;
}
let verification_id = NodeId::from_ip_with_rand(&source_ip, self.0[19]);
self.0[0] == verification_id.0[0]
&& self.0[1] == verification_id.0[1]
&& (self.0[2] & 0xf8) == (verification_id.0[2] & 0xf8)
}
fn is_plausible_legacy_id(&self) -> bool {
let first = self.0[0];
!self.0.iter().all(|&b| b == 0) && !self.0.iter().all(|&b| b == first)
}
}
impl Display for NodeId {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{:x?}", self.0)
}
}
impl Debug for NodeId {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{:x?}", self.0)
}
}
impl From<[u8; 20]> for NodeId {
fn from(value: [u8; 20]) -> Self {
Self { 0: value }
}
}
impl From<&[u8; 20]> for NodeId {
fn from(value: &[u8; 20]) -> Self {
Self::from(*value)
}
}
impl TryFrom<&[u8]> for NodeId {
type Error = Error;
fn try_from(value: &[u8]) -> Result<Self> {
let bytes: [u8; 20] = value.try_into().map_err(|_| Error::InvalidNodeId)?;
Ok(Self { 0: bytes })
}
}
impl From<&SocketAddr> for NodeId {
fn from(value: &SocketAddr) -> Self {
Self::from_ip(&value.ip())
}
}
impl Serialize for NodeId {
fn serialize<S>(&self, serializer: S) -> result::Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_bytes(&self.0)
}
}
impl<'de> Deserialize<'de> for NodeId {
fn deserialize<D>(deserializer: D) -> result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Ok(Self::from(&serde_bytes::deserialize::<[u8; 20], D>(
deserializer,
)?))
}
}
pub trait IsLocal {
fn is_local(&self) -> bool;
}
impl IsLocal for IpAddr {
fn is_local(&self) -> bool {
match self {
IpAddr::V4(ipv4) => {
let ip = u32::from_be_bytes(ipv4.octets());
(ip & 0xff000000) == 0x0a000000 || (ip & 0xfff00000) == 0xac100000 || (ip & 0xffff0000) == 0xc0a80000 || (ip & 0xffff0000) == 0xa9fe0000 || (ip & 0xff000000) == 0x7f000000 || (ip & 0xffc00000) == 0x64400000 }
IpAddr::V6(ipv6) => {
let ipv6_bytes = ipv6.octets();
ipv6.is_loopback()
|| ipv6.is_unicast_link_local()
|| ipv6.is_unique_local()
|| (ipv6_bytes[0] & 0xfe) == 0xfc
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_node_id_new() {
let result = NodeId::new();
assert_ne!(
[0u8; 20], result.0,
"expected a random node id to have been generated"
);
}
#[test]
fn test_node_id_as_slice() {
let mut node_id = [0u8; 20];
node_id[1] = 10;
node_id[2] = 20;
let result = NodeId::from(&node_id);
assert_eq!(&node_id, result.as_slice());
}
#[test]
fn test_try_from_byte_slice() {
let node_id = "abcdefghij0123456789";
let result = NodeId::try_from(node_id.as_bytes()).expect("expected a valid node id");
assert_eq!(node_id.as_bytes(), result.as_slice());
}
mod from_ip {
use super::*;
#[test]
fn test_from_ip() {
let ip: IpAddr = [10, 0, 0, 100].into();
let node = NodeId::from_ip(&ip);
let left_bits =
((node.0[0] as u32) << 16 | (node.0[1] as u32) << 8 | node.0[2] as u32) >> 3;
let result = NodeId::from_ip_with_rand(&ip, node.0[19]);
let right_bits =
((result.0[0] as u32) << 16 | (result.0[1] as u32) << 8 | result.0[2] as u32) >> 3;
assert_eq!(
left_bits, right_bits,
"expected a unique part to have been generated"
);
let result = NodeId::from_ip(&ip);
assert_ne!(
node, result,
"expected different nodes to have been generated"
)
}
#[test]
fn test_from_ip_rand_1() {
let ip = [124, 31, 75, 21].into();
let rand = 1;
let result = NodeId::from_ip_with_rand(&ip, rand);
assert_id_prefix(&[0x5f, 0xbf, 0xbf], result.as_slice());
assert_eq!(
rand,
result.as_slice()[19],
"expected the last byte to match the rand"
);
}
#[test]
fn test_from_ip_rand_86() {
let ip = [21, 75, 31, 124].into();
let rand = 86;
let result = NodeId::from_ip_with_rand(&ip, rand);
assert_id_prefix(&[0x5a, 0x3c, 0xe9], result.as_slice());
assert_eq!(
rand,
result.as_slice()[19],
"expected the last byte to match the rand"
);
}
fn assert_id_prefix(expected_prefix: &[u8], node_id: &[u8]) {
assert_eq!(
expected_prefix[0], node_id[0],
"expected the first byte to match"
);
assert_eq!(
expected_prefix[1], node_id[1],
"expected the second byte to match"
);
assert_eq!(
expected_prefix[2] & 0xf8,
node_id[2] & 0xf8,
"expected the first 5 bits to match from the 3th byte"
);
}
}
mod distance {
use super::*;
#[test]
fn test_same_node_closest_distance() {
let node1 = NodeId::try_from(
Sha1::digest("ffff740985723049587230495872304958703294").as_slice(),
)
.unwrap();
let node2 = NodeId::try_from(
Sha1::digest("ffff740985723049587230495872304958703294").as_slice(),
)
.unwrap();
let result = node1.distance(&node2);
assert_eq!(0, result, "expected the node result to be the same");
}
#[test]
fn test_random_node() {
let node1 = NodeId::try_from(
Sha1::digest("ffff740985723049587230495872304958703294").as_slice(),
)
.unwrap();
let node2 = NodeId::new();
let result = node1.distance(&node2);
assert_ne!(0, result, "expected the nodes to not match");
}
#[test]
fn test_closest_distance() {
let node1 = NodeId::try_from(
Sha1::digest("ffffffffffffffffffffffffffffffffffffffff").as_slice(),
)
.unwrap();
let node2 = NodeId::try_from(
Sha1::digest("ffffffffffffffffffffffffffffffffffffffff").as_slice(),
)
.unwrap();
let result = node1.distance(&node2);
assert_eq!(0, result, "expected the nodes to not match");
}
#[test]
fn test_fartest_distance() {
let node1 = NodeId::try_from([0xff; 20]).unwrap();
let node2 = NodeId::try_from([0x00; 20]).unwrap();
let result = node1.distance(&node2);
assert_eq!(MAX_DISTANCE, result, "expected the nodes to not match");
}
#[test]
fn test_almost_fartest_distance() {
let node1 = create_with_leading_zeros(1);
let node2 = NodeId::try_from([0x00; 20]).unwrap();
let result = node1.distance(&node2);
assert_eq!(159, result);
}
#[test]
fn test_near_fartest_distance() {
let node1 = create_with_leading_zeros(2);
let node2 = NodeId::try_from([0x00; 20]).unwrap();
let result = node1.distance(&node2);
assert_eq!(158, result);
}
fn create_with_leading_zeros(leading_zeros: usize) -> NodeId {
let mut bytes = vec![0xffu8; 20];
let mut bits_remaining = leading_zeros;
for byte in &mut bytes {
if bits_remaining >= 8 {
*byte = 0;
bits_remaining -= 8;
} else if bits_remaining > 0 {
*byte &= 0xFFu8 >> bits_remaining;
break;
} else {
break;
}
}
NodeId::try_from(bytes.as_slice()).unwrap()
}
}
}