Skip to content

Commit 8d4b6f8

Browse files
committed
dev: use aquatic_udp_protocol InfoHash inside our type
1 parent f71ca54 commit 8d4b6f8

File tree

9 files changed

+74
-35
lines changed

9 files changed

+74
-35
lines changed

Cargo.lock

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

packages/primitives/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,11 @@ rust-version.workspace = true
1515
version.workspace = true
1616

1717
[dependencies]
18+
aquatic_udp_protocol = "0"
1819
binascii = "0"
1920
derive_more = "0"
2021
serde = { version = "1", features = ["derive"] }
2122
tdyne-peer-id = "1"
2223
tdyne-peer-id-registry = "0"
2324
thiserror = "1"
25+
zerocopy = "0"

packages/primitives/src/info_hash.rs

Lines changed: 50 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
11
use std::hash::{DefaultHasher, Hash, Hasher};
2+
use std::ops::{Deref, DerefMut};
23
use std::panic::Location;
34

45
use thiserror::Error;
6+
use zerocopy::FromBytes;
57

68
/// `BitTorrent` Info Hash v1
7-
#[derive(PartialEq, Eq, Hash, Clone, Copy, Default, Debug)]
8-
pub struct InfoHash(pub [u8; 20]);
9+
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
10+
pub struct InfoHash {
11+
data: aquatic_udp_protocol::InfoHash,
12+
}
913

1014
pub const INFO_HASH_BYTES_LEN: usize = 20;
1115

@@ -17,10 +21,9 @@ impl InfoHash {
1721
/// Will panic if byte slice does not contains the exact amount of bytes need for the `InfoHash`.
1822
#[must_use]
1923
pub fn from_bytes(bytes: &[u8]) -> Self {
20-
assert_eq!(bytes.len(), INFO_HASH_BYTES_LEN);
21-
let mut ret = Self([0u8; INFO_HASH_BYTES_LEN]);
22-
ret.0.clone_from_slice(bytes);
23-
ret
24+
let data = aquatic_udp_protocol::InfoHash::read_from(bytes).expect("it should have the exact amount of bytes");
25+
26+
Self { data }
2427
}
2528

2629
/// Returns the `InfoHash` internal byte array.
@@ -36,6 +39,34 @@ impl InfoHash {
3639
}
3740
}
3841

42+
impl Default for InfoHash {
43+
fn default() -> Self {
44+
Self {
45+
data: aquatic_udp_protocol::InfoHash(Default::default()),
46+
}
47+
}
48+
}
49+
50+
impl From<aquatic_udp_protocol::InfoHash> for InfoHash {
51+
fn from(data: aquatic_udp_protocol::InfoHash) -> Self {
52+
Self { data }
53+
}
54+
}
55+
56+
impl Deref for InfoHash {
57+
type Target = aquatic_udp_protocol::InfoHash;
58+
59+
fn deref(&self) -> &Self::Target {
60+
&self.data
61+
}
62+
}
63+
64+
impl DerefMut for InfoHash {
65+
fn deref_mut(&mut self) -> &mut Self::Target {
66+
&mut self.data
67+
}
68+
}
69+
3970
impl Ord for InfoHash {
4071
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
4172
self.0.cmp(&other.0)
@@ -60,7 +91,7 @@ impl std::str::FromStr for InfoHash {
6091
type Err = binascii::ConvertError;
6192

6293
fn from_str(s: &str) -> Result<Self, Self::Err> {
63-
let mut i = Self([0u8; 20]);
94+
let mut i = Self::default();
6495
if s.len() != 40 {
6596
return Err(binascii::ConvertError::InvalidInputLength);
6697
}
@@ -72,7 +103,7 @@ impl std::str::FromStr for InfoHash {
72103
impl std::convert::From<&[u8]> for InfoHash {
73104
fn from(data: &[u8]) -> InfoHash {
74105
assert_eq!(data.len(), 20);
75-
let mut ret = InfoHash([0u8; 20]);
106+
let mut ret = Self::default();
76107
ret.0.clone_from_slice(data);
77108
ret
78109
}
@@ -82,23 +113,28 @@ impl std::convert::From<&[u8]> for InfoHash {
82113
impl std::convert::From<&DefaultHasher> for InfoHash {
83114
fn from(data: &DefaultHasher) -> InfoHash {
84115
let n = data.finish().to_le_bytes();
85-
InfoHash([
116+
let bytes = [
86117
n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7], n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7], n[0], n[1], n[2],
87118
n[3],
88-
])
119+
];
120+
let data = aquatic_udp_protocol::InfoHash(bytes);
121+
Self { data }
89122
}
90123
}
91124

92125
impl std::convert::From<&i32> for InfoHash {
93126
fn from(n: &i32) -> InfoHash {
94127
let n = n.to_le_bytes();
95-
InfoHash([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, n[0], n[1], n[2], n[3]])
128+
let bytes = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, n[0], n[1], n[2], n[3]];
129+
let data = aquatic_udp_protocol::InfoHash(bytes);
130+
Self { data }
96131
}
97132
}
98133

99134
impl std::convert::From<[u8; 20]> for InfoHash {
100-
fn from(val: [u8; 20]) -> Self {
101-
InfoHash(val)
135+
fn from(bytes: [u8; 20]) -> Self {
136+
let data = aquatic_udp_protocol::InfoHash(bytes);
137+
Self { data }
102138
}
103139
}
104140

@@ -171,7 +207,7 @@ impl<'v> serde::de::Visitor<'v> for InfoHashVisitor {
171207
));
172208
}
173209

174-
let mut res = InfoHash([0u8; 20]);
210+
let mut res = InfoHash::default();
175211

176212
if binascii::hex2bin(v.as_bytes(), &mut res.0).is_err() {
177213
return Err(serde::de::Error::invalid_value(

packages/torrent-repository/benches/helpers/asyn.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ where
1616
for _ in 0..samples {
1717
let torrent_repository = V::default();
1818

19-
let info_hash = InfoHash([0; 20]);
19+
let info_hash = InfoHash::default();
2020

2121
torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER).await;
2222

@@ -33,23 +33,23 @@ where
3333
Arc<V>: Clone + Send + Sync + 'static,
3434
{
3535
let torrent_repository = Arc::<V>::default();
36-
let info_hash: &'static InfoHash = &InfoHash([0; 20]);
36+
let info_hash = InfoHash::default();
3737
let handles = FuturesUnordered::new();
3838

3939
// Add the torrent/peer to the torrent repository
40-
torrent_repository.upsert_peer(info_hash, &DEFAULT_PEER).await;
40+
torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER).await;
4141

42-
torrent_repository.get_swarm_metadata(info_hash).await;
42+
torrent_repository.get_swarm_metadata(&info_hash).await;
4343

4444
let start = Instant::now();
4545

4646
for _ in 0..samples {
4747
let torrent_repository_clone = torrent_repository.clone();
4848

4949
let handle = runtime.spawn(async move {
50-
torrent_repository_clone.upsert_peer(info_hash, &DEFAULT_PEER).await;
50+
torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER).await;
5151

52-
torrent_repository_clone.get_swarm_metadata(info_hash).await;
52+
torrent_repository_clone.get_swarm_metadata(&info_hash).await;
5353

5454
if let Some(sleep_time) = sleep {
5555
let start_time = std::time::Instant::now();

packages/torrent-repository/benches/helpers/sync.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ where
1818
for _ in 0..samples {
1919
let torrent_repository = V::default();
2020

21-
let info_hash = InfoHash([0; 20]);
21+
let info_hash = InfoHash::default();
2222

2323
torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER);
2424

@@ -35,23 +35,23 @@ where
3535
Arc<V>: Clone + Send + Sync + 'static,
3636
{
3737
let torrent_repository = Arc::<V>::default();
38-
let info_hash: &'static InfoHash = &InfoHash([0; 20]);
38+
let info_hash = InfoHash::default();
3939
let handles = FuturesUnordered::new();
4040

4141
// Add the torrent/peer to the torrent repository
42-
torrent_repository.upsert_peer(info_hash, &DEFAULT_PEER);
42+
torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER);
4343

44-
torrent_repository.get_swarm_metadata(info_hash);
44+
torrent_repository.get_swarm_metadata(&info_hash);
4545

4646
let start = Instant::now();
4747

4848
for _ in 0..samples {
4949
let torrent_repository_clone = torrent_repository.clone();
5050

5151
let handle = runtime.spawn(async move {
52-
torrent_repository_clone.upsert_peer(info_hash, &DEFAULT_PEER);
52+
torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER);
5353

54-
torrent_repository_clone.get_swarm_metadata(info_hash);
54+
torrent_repository_clone.get_swarm_metadata(&info_hash);
5555

5656
if let Some(sleep_time) = sleep {
5757
let start_time = std::time::Instant::now();

packages/torrent-repository/benches/helpers/utils.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ pub fn generate_unique_info_hashes(size: usize) -> Vec<InfoHash> {
3030
bytes[2] = ((i >> 16) & 0xFF) as u8;
3131
bytes[3] = ((i >> 24) & 0xFF) as u8;
3232

33-
let info_hash = InfoHash(bytes);
33+
let info_hash = InfoHash::from_bytes(&bytes);
3434
result.insert(info_hash);
3535
}
3636

src/console/clients/checker/checks/udp.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ use std::time::Duration;
44
use aquatic_udp_protocol::TransactionId;
55
use hex_literal::hex;
66
use serde::Serialize;
7-
use torrust_tracker_primitives::info_hash::InfoHash;
87

98
use crate::console::clients::udp::checker::Client;
109
use crate::console::clients::udp::Error;
@@ -29,7 +28,7 @@ pub async fn run(udp_trackers: Vec<SocketAddr>, timeout: Duration) -> Vec<Result
2928

3029
tracing::debug!("UDP trackers ...");
3130

32-
let info_hash = InfoHash(hex!("9c38422213e30bff212b30c360d26f9a02136422")); // # DevSkim: ignore DS173237
31+
let info_hash = aquatic_udp_protocol::InfoHash(hex!("9c38422213e30bff212b30c360d26f9a02136422")); // # DevSkim: ignore DS173237
3332

3433
for remote_addr in udp_trackers {
3534
let mut checks = Checks {
@@ -70,7 +69,7 @@ pub async fn run(udp_trackers: Vec<SocketAddr>, timeout: Duration) -> Vec<Result
7069
// Announce
7170
{
7271
let check = client
73-
.send_announce_request(transaction_id, connection_id, info_hash)
72+
.send_announce_request(transaction_id, connection_id, info_hash.into())
7473
.await
7574
.map(|_| ());
7675

@@ -80,7 +79,7 @@ pub async fn run(udp_trackers: Vec<SocketAddr>, timeout: Duration) -> Vec<Result
8079
// Scrape
8180
{
8281
let check = client
83-
.send_scrape_request(connection_id, transaction_id, &[info_hash])
82+
.send_scrape_request(connection_id, transaction_id, &[info_hash.into()])
8483
.await
8584
.map(|_| ());
8685

src/servers/http/v1/responses/scrape.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ mod tests {
9999
use crate::servers::http::v1::responses::scrape::Bencoded;
100100

101101
fn sample_scrape_data() -> ScrapeData {
102-
let info_hash = InfoHash([0x69; 20]);
102+
let info_hash = InfoHash::from_bytes(&[0x69; 20]);
103103
let mut scrape_data = ScrapeData::empty();
104104
scrape_data.add_file(
105105
&info_hash,

src/servers/udp/handlers.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ pub async fn handle_announce(
151151

152152
check(&remote_addr, &from_connection_id(&announce_request.connection_id))?;
153153

154-
let info_hash = InfoHash(announce_request.info_hash.0);
154+
let info_hash = announce_request.info_hash.into();
155155
let remote_client_ip = remote_addr.ip();
156156

157157
// Authorization
@@ -240,9 +240,9 @@ pub async fn handle_scrape(remote_addr: SocketAddr, request: &ScrapeRequest, tra
240240
debug!("udp scrape request: {:#?}", request);
241241

242242
// Convert from aquatic infohashes
243-
let mut info_hashes = vec![];
243+
let mut info_hashes: Vec<InfoHash> = vec![];
244244
for info_hash in &request.info_hashes {
245-
info_hashes.push(InfoHash(info_hash.0));
245+
info_hashes.push((*info_hash).into());
246246
}
247247

248248
let scrape_data = if tracker.requires_authentication() {

0 commit comments

Comments
 (0)