cuprate_test_utils/
test_netzone.rs

1//! Test net zone.
2//!
3//! This module contains a test network zone, this network zone use channels as the network layer to simulate p2p
4//! communication.
5//!
6use std::{
7    fmt::Formatter,
8    net::{Ipv4Addr, SocketAddr},
9};
10
11use borsh::{BorshDeserialize, BorshSerialize};
12
13use cuprate_p2p_core::{NetZoneAddress, NetworkZone};
14use cuprate_wire::network_address::{NetworkAddress, NetworkAddressIncorrectZone};
15
16/// An address on the test network
17#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq, BorshSerialize, BorshDeserialize)]
18pub struct TestNetZoneAddr(pub u32);
19
20impl NetZoneAddress for TestNetZoneAddr {
21    type BanID = Self;
22
23    fn set_port(&mut self, _: u16) {}
24
25    fn make_canonical(&mut self) {}
26
27    fn ban_id(&self) -> Self::BanID {
28        *self
29    }
30
31    fn should_add_to_peer_list(&self) -> bool {
32        true
33    }
34}
35
36impl std::fmt::Display for TestNetZoneAddr {
37    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
38        f.write_str(format!("test client, id: {}", self.0).as_str())
39    }
40}
41
42impl From<TestNetZoneAddr> for NetworkAddress {
43    fn from(value: TestNetZoneAddr) -> Self {
44        Self::Clear(SocketAddr::new(Ipv4Addr::from(value.0).into(), 18080))
45    }
46}
47
48impl TryFrom<NetworkAddress> for TestNetZoneAddr {
49    type Error = NetworkAddressIncorrectZone;
50
51    fn try_from(value: NetworkAddress) -> Result<Self, Self::Error> {
52        match value {
53            NetworkAddress::Clear(soc) => match soc {
54                SocketAddr::V4(v4) => Ok(Self(u32::from_be_bytes(v4.ip().octets()))),
55                SocketAddr::V6(_) => panic!("None v4 address in test code"),
56            },
57        }
58    }
59}
60
61/// TODO
62#[derive(Debug, Clone, Copy, Eq, PartialEq)]
63pub struct TestNetZone<const CHECK_NODE_ID: bool>;
64
65#[async_trait::async_trait]
66impl<const CHECK_NODE_ID: bool> NetworkZone for TestNetZone<CHECK_NODE_ID> {
67    const NAME: &'static str = "Testing";
68    const CHECK_NODE_ID: bool = CHECK_NODE_ID;
69    const BROADCAST_OWN_ADDR: bool = false;
70
71    type Addr = TestNetZoneAddr;
72}