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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
//  Copyright (C) 2017  The Duniter Project Developers.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

//! Module defining the format of network endpoints and how to handle them.

use crate::*;
use dup_crypto::hashs::Hash;
use dup_crypto::keys::PubKey;
use hex;
use pest::iterators::Pair;
use pest::Parser;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::str::FromStr;

/// Total size of all fixed size fields of an EndpointV2
pub static ENDPOINTV2_FIXED_SIZE: &'static usize = &9;
/// Maximum number of network features
pub static MAX_NETWORK_FEATURES_COUNT: &'static usize = &2040;
/// Maximum number of api features
pub static MAX_API_FEATURES_COUNT: &'static usize = &2040;

#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
/// ApiFeatures
pub struct ApiFeatures(pub Vec<u8>);

impl ApiFeatures {
    fn is_empty(&self) -> bool {
        for byte in &self.0 {
            if *byte > 0u8 {
                return false;
            }
        }
        true
    }

    fn to_string(&self) -> String {
        if self.is_empty() {
            String::from("")
        } else {
            let hex_str = hex::encode(self.0.clone());
            if hex_str.len() == 2 {
                format!("{} ", &hex_str[1..])
            } else {
                format!("{} ", hex_str)
            }
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
/// Identifies the API of an endpoint
pub struct NetworkEndpointApi(pub String);

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
/// Endpoint v1
pub struct EndpointV1 {
    /// API Name
    pub api: NetworkEndpointApi,
    /// Node unique identifier
    pub node_id: Option<NodeId>,
    /// Public key of the node declaring this endpoint
    pub issuer: PubKey,
    /// NodeFullID hash
    pub hash_full_id: Option<Hash>,
    /// hostname
    pub host: String,
    /// port number
    pub port: usize,
    /// Optional path
    pub path: Option<String>,
    /// Endpoint in raw format (as it appears on the peer card)
    pub raw_endpoint: String,
    /// Accessibility status of this endpoint  (updated regularly)
    pub status: u32,
    /// Timestamp of the last connection attempt to this endpoint
    pub last_check: u64,
}

impl EndpointV1 {
    /// Accessors providing node full identifier
    pub fn node_full_id(&self) -> Option<NodeFullId> {
        match self.node_id {
            Some(node_id) => Some(NodeFullId(node_id, self.issuer)),
            None => None,
        }
    }
    /// Generate endpoint url
    pub fn get_url(&self, get_protocol: bool, _supported_ip_v6: bool) -> Option<String> {
        let protocol = match &self.api.0[..] {
            "WS2P" | "WS2PTOR" => "ws",
            _ => "http",
        };
        let tls = match self.port {
            443 => "s",
            _ => "",
        };
        let path = match self.path {
            Some(ref path_string) => path_string.clone(),
            None => String::new(),
        };
        if get_protocol {
            Some(format!(
                "{}{}://{}:{}/{}",
                protocol, tls, self.host, self.port, path
            ))
        } else {
            Some(format!("{}:{}/{}", self.host, self.port, path))
        }
    }
    /// Generate from pest pair
    fn from_pest_pair(
        pair: Pair<Rule>,
        issuer: PubKey,
        status: u32,
        last_check: u64,
    ) -> EndpointV1 {
        let raw_endpoint = String::from(pair.as_str());
        let mut api_name = "";
        let mut node_id = None;
        let mut hash_full_id = None;
        let mut host_str = "";
        let mut port = 0;
        let mut path = None;

        for ep_pair in pair.into_inner() {
            match ep_pair.as_rule() {
                Rule::api_name => api_name = ep_pair.as_str(),
                Rule::node_id => {
                    node_id = Some(NodeId(u32::from_str_radix(ep_pair.as_str(), 16).unwrap()));
                    hash_full_id = match node_id {
                        Some(node_id_) => Some(NodeFullId(node_id_, issuer).sha256()),
                        None => None,
                    };
                }
                Rule::host => host_str = ep_pair.as_str(),
                Rule::port => port = ep_pair.as_str().parse().unwrap(),
                Rule::path_inner => path = Some(String::from(ep_pair.as_str())),
                _ => panic!("unexpected rule: {:?}", ep_pair.as_rule()), // Grammar ensures that we never reach this line
            }
        }
        EndpointV1 {
            issuer,
            api: NetworkEndpointApi(String::from(api_name)),
            node_id,
            hash_full_id,
            host: String::from(host_str),
            port,
            path,
            raw_endpoint,
            status,
            last_check,
        }
    }

    /// parse from ut8 format
    pub fn parse_from_raw(
        raw_endpoint: &str,
        issuer: PubKey,
        status: u32,
        last_check: u64,
    ) -> Result<EndpointV1, ParseError> {
        match NetworkDocsParser::parse(Rule::endpoint_v1, raw_endpoint) {
            Ok(mut ep_v1_pairs) => Ok(EndpointV1::from_pest_pair(
                ep_v1_pairs.next().unwrap(),
                issuer,
                status,
                last_check,
            )),
            Err(pest_error) => Err(ParseError::PestError(format!("{}", pest_error))),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
/// Network features
pub struct EndpointV2NetworkFeatures(pub Vec<u8>);

impl ToString for EndpointV2NetworkFeatures {
    fn to_string(&self) -> String {
        if self.is_empty() {
            return "".to_owned();
        }
        let mut features_str = Vec::with_capacity(2);
        if self.tls() {
            features_str.push("S");
        }
        if self.tor() {
            features_str.push("TOR");
        }
        format!("{} ", features_str.join(" "))
    }
}

impl EndpointV2NetworkFeatures {
    fn is_empty(&self) -> bool {
        for byte in &self.0 {
            if *byte > 0u8 {
                return false;
            }
        }
        true
    }
    /// Network features size
    pub fn size(&self) -> u8 {
        self.0.len() as u8
    }
    /// Convert Self into bytes
    pub fn to_bytes_slice(&self) -> &[u8] {
        &self.0
    }
    /// TLS feature is enable ?
    pub fn tls(&self) -> bool {
        self.0[0] & 0b0000_0001 == 1u8
    }
    /// TOR feature is enable ?
    pub fn tor(&self) -> bool {
        self.0[0] & 0b0000_0010 == 2u8
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
/// Endpoint v2
pub struct Endpoint {
    /// Endpoint content
    pub content: EndpointEnum,
    /// Accessibility status of this endpoint  (updated regularly)
    pub status: u32,
    /// Timestamp of the last connection attempt to this endpoint
    pub last_check: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
/// Endpoint v2
pub struct EndpointV2 {
    /// API Name
    pub api: NetworkEndpointApi,
    /// API version
    pub api_version: u16,
    /// Network features
    pub network_features: EndpointV2NetworkFeatures,
    /// API features
    pub api_features: ApiFeatures,
    /// IPv4
    pub ip_v4: Option<Ipv4Addr>,
    /// IPv6
    pub ip_v6: Option<Ipv6Addr>,
    /// hostname
    pub host: Option<String>,
    /// port number
    pub port: u16,
    /// Optional path
    pub path: Option<String>,
}

impl ToString for EndpointV2 {
    fn to_string(&self) -> String {
        let host: String = if let Some(ref host) = self.host {
            format!("{} ", host)
        } else {
            String::from("")
        };
        let ip4: String = if let Some(ip4) = self.ip_v4 {
            format!("{} ", ip4.to_string())
        } else {
            String::from("")
        };
        let ip6: String = if let Some(ip6) = self.ip_v6 {
            format!("[{}] ", ip6.to_string())
        } else {
            String::from("")
        };
        let path = if let Some(ref path) = self.path {
            format!(" {}", path)
        } else {
            "".to_owned()
        };
        format!(
            "{api} {version}{nf}{af}{host}{ip4}{ip6}{port}{path}",
            api = self.api.0,
            version = if self.api_version > 0 {
                format!("V{} ", self.api_version)
            } else {
                "".to_owned()
            },
            nf = self.network_features.to_string(),
            af = self.api_features.to_string(),
            port = self.port,
            host = host,
            ip4 = ip4,
            ip6 = ip6,
            path = path,
        )
    }
}

impl EndpointV2 {
    /// Generate endpoint url
    pub fn get_url(&self, get_protocol: bool, supported_ip_v6: bool) -> Option<String> {
        let protocol = match &self.api.0[..] {
            "WS2P" | "WS2PTOR" => "ws",
            _ => "http",
        };

        let tls = match self.port {
            443 => "s",
            _ => "",
        };
        let host = if let Some(ref host) = self.host {
            host.clone()
        } else if supported_ip_v6 && self.ip_v6.is_some() {
            let ip_v6 = self.ip_v6.unwrap();
            format!("{}", ip_v6)
        } else if self.ip_v4.is_some() {
            let ip_v4 = self.ip_v4.unwrap();
            format!("{}", ip_v4)
        } else {
            println!("DEBUG: endpoint_v2={:?}", self);
            // Unreacheable endpoint
            return None;
        };
        let path = match self.path {
            Some(ref path_string) => path_string.clone(),
            None => String::new(),
        };
        if get_protocol {
            Some(format!(
                "{}{}://{}:{}/{}",
                protocol, tls, host, self.port, path
            ))
        } else {
            Some(format!("{}:{}/{}", host, self.port, path))
        }
    }
    /// Generate from pest pair
    pub fn from_pest_pair(pair: Pair<Rule>) -> EndpointV2 {
        let mut api_str = "";
        let mut api_version = 0;
        let mut network_features = EndpointV2NetworkFeatures(vec![0u8]);
        let mut api_features = ApiFeatures(vec![]);
        let mut ip_v4 = None;
        let mut ip_v6 = None;
        let mut host = None;
        let mut port = 0;
        let mut path = None;
        for field in pair.into_inner() {
            match field.as_rule() {
                Rule::api_name => api_str = field.as_str(),
                Rule::api_version_inner => api_version = field.as_str().parse().unwrap(),
                Rule::tls => network_features.0[0] |= 0b_0000_0001,
                Rule::tor => network_features.0[0] |= 0b_0000_0010,
                Rule::api_features_inner => {
                    api_features = if field.as_str().len() == 1 {
                        ApiFeatures(hex::decode(&format!("0{}", field.as_str())).unwrap())
                    } else {
                        ApiFeatures(hex::decode(field.as_str()).unwrap())
                    };
                }
                Rule::port => port = field.as_str().parse().unwrap(),
                Rule::host_v2_inner => host = Some(String::from(field.as_str())),
                Rule::ip4_inner => ip_v4 = Some(Ipv4Addr::from_str(field.as_str()).unwrap()),
                Rule::ip6_inner => ip_v6 = Some(Ipv6Addr::from_str(field.as_str()).unwrap()),
                Rule::path_inner => path = Some(String::from(field.as_str())),
                _ => panic!("unexpected rule: {:?}", field.as_rule()), // Grammar ensures that we never reach this line
            }
        }
        if network_features.is_empty() {
            network_features = EndpointV2NetworkFeatures(vec![]);
        }
        EndpointV2 {
            api: NetworkEndpointApi(String::from(api_str)),
            api_version,
            network_features,
            api_features,
            ip_v4,
            ip_v6,
            host,
            port,
            path,
        }
    }
    /// parse from raw ascii format
    pub fn parse_from_raw(raw_endpoint: &str) -> Result<EndpointEnum, ParseError> {
        match NetworkDocsParser::parse(Rule::endpoint_v2, raw_endpoint) {
            Ok(mut ep_v2_pairs) => Ok(EndpointEnum::V2(EndpointV2::from_pest_pair(
                ep_v2_pairs.next().unwrap(),
            ))),
            Err(pest_error) => Err(ParseError::PestError(format!("{}", pest_error))),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
/// Endpoint
pub enum EndpointEnum {
    /// Endpoint v1
    V1(EndpointV1),
    /// Endpoint v2
    V2(EndpointV2),
}

impl ToString for EndpointEnum {
    fn to_string(&self) -> String {
        match *self {
            EndpointEnum::V1(ref ep) => ep.raw_endpoint.clone(),
            EndpointEnum::V2(ref ep) => ep.to_string(),
        }
    }
}

impl EndpointEnum {
    /// Accessors providing API name
    pub fn api(&self) -> NetworkEndpointApi {
        match *self {
            EndpointEnum::V1(ref ep) => ep.api.clone(),
            EndpointEnum::V2(ref ep) => ep.api.clone(),
        }
    }
    /// Accessors providing node unique identifier
    pub fn node_uuid(&self) -> Option<NodeId> {
        match *self {
            EndpointEnum::V1(ref ep) => ep.node_id,
            EndpointEnum::V2(ref _ep) => unreachable!(),
        }
    }
    /// Accessors providing node public key
    pub fn pubkey(&self) -> PubKey {
        match *self {
            EndpointEnum::V1(ref ep) => ep.issuer,
            EndpointEnum::V2(ref _ep) => unreachable!(),
        }
    }
    /// Accessors providing port number
    pub fn port(&self) -> usize {
        match *self {
            EndpointEnum::V1(ref ep) => ep.port,
            EndpointEnum::V2(ref ep) => ep.port as usize,
        }
    }
    /// Accessors providing raw format
    pub fn raw(&self) -> String {
        match *self {
            EndpointEnum::V1(ref ep) => ep.raw_endpoint.clone(),
            _ => panic!("Endpoint version is not supported !"),
        }
    }
    /// Accessors providing endpoint accessibility status
    pub fn status(&self) -> u32 {
        match *self {
            EndpointEnum::V1(ref ep) => ep.status,
            EndpointEnum::V2(ref _ep) => unreachable!(),
        }
    }
    /// Set status
    pub fn set_status(&mut self, new_status: u32) {
        match *self {
            EndpointEnum::V1(ref mut ep) => ep.status = new_status,
            EndpointEnum::V2(ref _ep) => unreachable!(),
        }
    }
    /// Set last_check
    pub fn set_last_check(&mut self, new_last_check: u64) {
        match *self {
            EndpointEnum::V1(ref mut ep) => ep.last_check = new_last_check,
            EndpointEnum::V2(ref _ep) => unreachable!(),
        }
    }
    /// Generate endpoint url
    pub fn get_url(&self, get_protocol: bool, supported_ip_v6: bool) -> Option<String> {
        match *self {
            EndpointEnum::V1(ref ep) => {
                let protocol = match &ep.api.0[..] {
                    "WS2P" | "WS2PTOR" => "ws",
                    _ => "http",
                };
                let tls = match ep.port {
                    443 => "s",
                    _ => "",
                };
                let path = match ep.path {
                    Some(ref path_string) => path_string.clone(),
                    None => String::new(),
                };
                if get_protocol {
                    Some(format!(
                        "{}{}://{}:{}/{}",
                        protocol, tls, ep.host, ep.port, path
                    ))
                } else {
                    Some(format!("{}:{}/{}", ep.host, ep.port, path))
                }
            }
            EndpointEnum::V2(ref ep_v2) => ep_v2.get_url(get_protocol, supported_ip_v6),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bincode::{deserialize, serialize};

    #[test]
    fn test_network_features() {
        assert_eq!(EndpointV2NetworkFeatures(vec![1u8]).tls(), true);
        assert_eq!(EndpointV2NetworkFeatures(vec![1u8]).tor(), false);
        assert_eq!(EndpointV2NetworkFeatures(vec![2u8]).tls(), false);
        assert_eq!(EndpointV2NetworkFeatures(vec![2u8]).tor(), true);
        assert_eq!(EndpointV2NetworkFeatures(vec![3u8]).tls(), true);
        assert_eq!(EndpointV2NetworkFeatures(vec![3u8]).tor(), true);

        assert_eq!(
            EndpointV2NetworkFeatures(vec![1u8]).to_string().as_str(),
            "S "
        );
        assert_eq!(
            EndpointV2NetworkFeatures(vec![2u8]).to_string().as_str(),
            "TOR "
        );
        assert_eq!(
            EndpointV2NetworkFeatures(vec![3u8]).to_string().as_str(),
            "S TOR "
        );
    }
    fn test_parse_and_read_endpoint(str_endpoint: &str, endpoint: EndpointV2) {
        assert_eq!(
            EndpointV2::parse_from_raw(str_endpoint),
            Ok(EndpointEnum::V2(endpoint.clone())),
        );
        let binary_endpoint = serialize(&endpoint).expect("Fail to serialize endpoint !");
        let endpoint2: EndpointV2 =
            deserialize(&binary_endpoint).expect("Fail to deserialize endpoint !");
        assert_eq!(endpoint, endpoint2,);
        assert_eq!(str_endpoint, endpoint.to_string());
    }

    #[test]
    fn test_parse_and_read_minimal_endpoint() {
        let str_endpoint = "UNKNOWN_API 8080";
        let endpoint = EndpointV2 {
            api: NetworkEndpointApi(String::from("UNKNOWN_API")),
            api_version: 0,
            network_features: EndpointV2NetworkFeatures(vec![]),
            api_features: ApiFeatures(vec![]),
            ip_v4: None,
            ip_v6: None,
            host: None,
            port: 8080u16,
            path: None,
        };
        test_parse_and_read_endpoint(str_endpoint, endpoint);
    }

    #[test]
    fn test_parse_and_read_localhost_endpoint() {
        let str_endpoint = "WS2P localhost 10900";
        let endpoint = EndpointV2 {
            api: NetworkEndpointApi(String::from("WS2P")),
            api_version: 0,
            network_features: EndpointV2NetworkFeatures(vec![]),
            api_features: ApiFeatures(vec![]),
            ip_v4: None,
            ip_v6: None,
            host: Some(String::from("localhost")),
            port: 10900u16,
            path: None,
        };
        test_parse_and_read_endpoint(str_endpoint, endpoint.clone());
        // test get_url()
        assert_eq!(
            endpoint.get_url(true, false),
            Some("ws://localhost:10900/".to_owned())
        );
    }

    #[test]
    fn test_parse_and_read_classic_v1_endpoint() {
        let str_endpoint = "ES_CORE_API g1.data.duniter.fr 443";
        let endpoint = EndpointV2 {
            api: NetworkEndpointApi(String::from("ES_CORE_API")),
            api_version: 0,
            network_features: EndpointV2NetworkFeatures(vec![]),
            api_features: ApiFeatures(vec![]),
            ip_v4: None,
            ip_v6: None,
            host: Some(String::from("g1.data.duniter.fr")),
            port: 443u16,
            path: None,
        };
        test_parse_and_read_endpoint(str_endpoint, endpoint);
    }

    #[test]
    fn test_parse_and_read_endpoint_with_host() {
        let str_endpoint = "WS2P V2 S 7 g1.durs.ifee.fr 443 ws2p";
        let endpoint = EndpointV2 {
            api: NetworkEndpointApi(String::from("WS2P")),
            api_version: 2,
            network_features: EndpointV2NetworkFeatures(vec![1u8]),
            api_features: ApiFeatures(vec![7u8]),
            ip_v4: None,
            ip_v6: None,
            host: Some(String::from("g1.durs.ifee.fr")),
            port: 443u16,
            path: Some(String::from("ws2p")),
        };
        test_parse_and_read_endpoint(str_endpoint, endpoint.clone());
        // test get_url()
        assert_eq!(
            endpoint.get_url(true, false),
            Some("wss://g1.durs.ifee.fr:443/ws2p".to_owned()),
        );
    }

    #[test]
    fn test_parse_and_read_endpoint_with_ipv4() {
        let str_endpoint = "WS2P V2 S 7 84.16.72.210 443 ws2p";
        let endpoint = EndpointV2 {
            api: NetworkEndpointApi(String::from("WS2P")),
            api_version: 2,
            network_features: EndpointV2NetworkFeatures(vec![1u8]),
            api_features: ApiFeatures(vec![7u8]),
            ip_v4: Some(Ipv4Addr::from_str("84.16.72.210").unwrap()),
            ip_v6: None,
            host: None,
            port: 443u16,
            path: Some(String::from("ws2p")),
        };
        test_parse_and_read_endpoint(str_endpoint, endpoint);
    }

    #[test]
    fn test_parse_and_read_endpoint_with_ipv6() {
        let str_endpoint = "WS2P V2 S 7 [2001:41d0:8:c5aa::1] 443 ws2p";
        let endpoint = EndpointV2 {
            api: NetworkEndpointApi(String::from("WS2P")),
            api_version: 2,
            network_features: EndpointV2NetworkFeatures(vec![1u8]),
            api_features: ApiFeatures(vec![7u8]),
            ip_v4: None,
            ip_v6: Some(Ipv6Addr::from_str("2001:41d0:8:c5aa::1").unwrap()),
            host: None,
            port: 443u16,
            path: Some(String::from("ws2p")),
        };
        test_parse_and_read_endpoint(str_endpoint, endpoint);
    }

    #[test]
    fn test_parse_and_read_endpoint_with_ipv4_and_ip_v6() {
        let str_endpoint = "WS2P V2 S 7 5.135.188.170 [2001:41d0:8:c5aa::1] 443 ws2p";
        let endpoint = EndpointV2 {
            api: NetworkEndpointApi(String::from("WS2P")),
            api_version: 2,
            network_features: EndpointV2NetworkFeatures(vec![1u8]),
            api_features: ApiFeatures(vec![7u8]),
            ip_v4: Some(Ipv4Addr::from_str("5.135.188.170").unwrap()),
            ip_v6: Some(Ipv6Addr::from_str("2001:41d0:8:c5aa::1").unwrap()),
            host: None,
            port: 443u16,
            path: Some(String::from("ws2p")),
        };
        test_parse_and_read_endpoint(str_endpoint, endpoint);
    }

    #[test]
    fn test_parse_and_read_endpoint_with_all_fields() {
        let str_endpoint = "WS2P V2 S 7 g1.durs.info 5.135.188.170 [2001:41d0:8:c5aa::1] 443 ws2p";
        let endpoint = EndpointV2 {
            api: NetworkEndpointApi(String::from("WS2P")),
            api_version: 2,
            network_features: EndpointV2NetworkFeatures(vec![1u8]),
            api_features: ApiFeatures(vec![7u8]),
            ip_v4: Some(Ipv4Addr::from_str("5.135.188.170").unwrap()),
            ip_v6: Some(Ipv6Addr::from_str("2001:41d0:8:c5aa::1").unwrap()),
            host: Some(String::from("g1.durs.info")),
            port: 443u16,
            path: Some(String::from("ws2p")),
        };
        test_parse_and_read_endpoint(str_endpoint, endpoint);
    }
}