Skip to content

Commit

Permalink
Use a random alphanumeric string for mDNS peer name
Browse files Browse the repository at this point in the history
  • Loading branch information
jochasinga committed Oct 25, 2021
1 parent 9750951 commit 27b2ecc
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion protocols/mdns/src/dns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
use crate::{META_QUERY_SERVICE, SERVICE_NAME};
use libp2p_core::{Multiaddr, PeerId};
use std::{borrow::Cow, cmp, error, fmt, str, time::Duration};
use rand::{thread_rng, Rng};
use rand::distributions::Alphanumeric;

/// Maximum size of a DNS label as per RFC1035.
const MAX_LABEL_LENGTH: usize = 63;
Expand Down Expand Up @@ -280,14 +282,22 @@ fn segment_peer_id(peer_id: String) -> String {
out
}

fn random_string(length: usize) -> String {
thread_rng()
.sample_iter(&Alphanumeric)
.take(length)
.map(char::from)
.collect()
}

/// Combines and encodes a `PeerId` and service name for a DNS query.
fn encode_peer_id(peer_id: &PeerId) -> Vec<u8> {
// DNS-safe encoding for the Peer ID
let raw_peer_id = data_encoding::BASE32_DNSCURVE.encode(&peer_id.to_bytes());
// ensure we don't have any labels over 63 bytes long
let encoded_peer_id = segment_peer_id(raw_peer_id);
let service_name = str::from_utf8(SERVICE_NAME).expect("SERVICE_NAME is always ASCII");
let peer_name = [&encoded_peer_id, service_name].join(".");
let peer_name = random_string(32 + thread_rng().gen_range(0..32));

// allocate with a little extra padding for QNAME encoding
let mut peer_id_bytes = Vec::with_capacity(peer_name.len() + 32);
Expand Down Expand Up @@ -456,5 +466,13 @@ mod tests {
assert_eq!(segment_peer_id(str_127), [&str_63, &str_63, "x"].join("."));
}

#[test]
fn test_random_string() {
let varsize = thread_rng().gen_range(0..32);
let size = 32 + varsize;
let name = random_string(size);
assert_eq!(name.len(), size);
}

// TODO: test limits and errors
}

0 comments on commit 27b2ecc

Please sign in to comment.