fx-torrent 0.10.3

FX Torrent is a feature rich Bittorrent protocol implementation written in rust supporting Linux, MacOS and Windows.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
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; // = 160
const CRC32: Crc<u32> = Crc::<u32>::new(&CRC_32_ISCSI);

/// The unique DHT node identifier.
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub struct NodeId([u8; NODE_ID_SIZE]);

impl NodeId {
    /// Generate a random node id.
    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)
    }

    /// Create a new node id from the given address.
    /// It uses a random generated byte for hashing the ip address.
    /// See BEP42 for more info.
    ///
    /// If you want to use a fixed byte for hashing, use [Self::from_ip_with_rand] instead.
    pub fn from_ip(addr: &IpAddr) -> Self {
        Self::from_ip_with_rand(addr, rng().random::<u8>())
    }

    /// Create a new node id from the given ip address using a fixed `rand` for hashing.
    /// See BEP42 for more info.
    ///
    /// # Arguments
    ///
    /// * `addr` - The IP address create a new node id for.
    /// * `rand` - The random byte to use for hashing the ip address.
    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; // only low 3 bits are used of the random byte
        ip_bytes[0] |= r << 5; // insert the 3-bits from `r` into the top bits of ip byte 0

        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);

        // set the first 21 bits to the ip hash
        id_bytes[0] = ip_hash[0];
        id_bytes[1] = ip_hash[1];
        id_bytes[2] = (ip_hash[2] & 0xf8) | rng().random_range(0..=0x7);

        // update the last byte to the `random_byte` that was used to generate the hash
        id_bytes[19] = rand;

        Self(id_bytes)
    }

    /// Get the slice value of the node id.
    ///
    /// # Returns
    ///
    /// A 20-byte slice representing the node id.
    pub fn as_slice(&self) -> &[u8] {
        &self.0
    }

    /// Get the fixed node slice value of the node id.
    ///
    /// # Returns
    ///
    /// It returns a fixed 20-byte slice representing the node id.
    pub fn as_node_slice(&self) -> &[u8; NODE_ID_SIZE] {
        &self.0
    }

    /// Get the bitwise XOR result between this node and the target node.
    ///
    /// # Returns
    ///
    /// Returns a new node ID based on the bitwise XOR operation.
    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()
    }

    /// Count the number of leading zeros within the binary representation of this id.
    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
    }

    /// Get the distance between this node and the target node.
    ///
    /// When both nodes are the same, the result will be 0.
    /// When the nodes don't match at all, the result is [MAX_DISTANCE].
    pub fn distance(&self, node: &NodeId) -> u8 {
        let leading_zeros = self.xor(node).leading_zeros();
        MAX_DISTANCE - leading_zeros
    }

    /// Verify if this node matches the given source ip.
    ///
    /// # Returns
    ///
    /// Returns `true` if the source ip is valid, else `false`.
    pub fn verify_id(&self, source_ip: &IpAddr) -> bool {
        self.is_secure_id(&source_ip) || self.is_plausible_legacy_id()
    }

    /// Verify if this node follows the BEP42 verification.
    pub fn is_secure_id(&self, source_ip: &IpAddr) -> bool {
        // no need to verify local IPs, they would be incorrect anyway
        if source_ip.is_local() {
            return true;
        }

        let verification_id = NodeId::from_ip_with_rand(&source_ip, self.0[19]);

        // check if the first 21 bits match
        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];
        // reject all-zeros and single-byte repeats
        !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 {
    /// Verify if the ip address is a local address.
    /// This includes the following IP blocks:
    ///
    /// ```text
    /// 10.0.0.0/8
    ///     reserved for local networks
    /// 172.16.0.0/12
    ///     reserved for local networks
    /// 192.168.0.0/16
    ///     reserved for local networks
    /// 169.254.0.0/16
    ///     reserved for self-assigned IPs
    /// 127.0.0.0/8
    ///     reserved for loopback
    /// ```
    ///
    /// # Returns
    ///
    /// It returns `true` when the address is a local address, else `false`.
    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       // 10.x.x.x
                    || (ip & 0xfff00000) == 0xac100000 // 172.16.x.x
                    || (ip & 0xffff0000) == 0xc0a80000 // 192.168.x.x
                    || (ip & 0xffff0000) == 0xa9fe0000 // 169.254.x.x
                    || (ip & 0xff000000) == 0x7f000000 // 127.x.x.x
                    || (ip & 0xffc00000) == 0x64400000 // 100.64.0.0/10
            }
            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);

            // check if the first 21 bits match when using the same random secret
            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"
            );

            // check if a different node is generated with a new random
            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 {
                    // keep the trailing (8 - bits_remaining) bits as 1
                    *byte &= 0xFFu8 >> bits_remaining;
                    break;
                } else {
                    break;
                }
            }

            NodeId::try_from(bytes.as_slice()).unwrap()
        }
    }
}