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
use std::sync::{
    atomic::{AtomicUsize, Ordering},
    Arc,
};

use async_trait::async_trait;

use xstack::{
    multiaddr::{Multiaddr, Protocol},
    transport_syscall::DriverTransport,
    P2pConn, Switch, TransportListener,
};
use xstack_tls::TlsConn;

use crate::{CircuitV2Rpc, Error, PROTOCOL_CIRCUIT_RELAY_HOP};

/// The implementation of transport [**circuit_v2**].
///
/// The below codes show how to enable this.
///
/// ```no_run
/// use xstack::Switch;
/// use xstack_circuit::CircuitTransport;
///
/// # async fn boostrap() {
/// Switch::new("test")
///       .transport(CircuitTransport::default())
///       // if the node want to enable sub-protocol '/libp2p/circuit/relay/0.2.0/stop'
///       .transport_bind(["/p2p-circuit"])
///       .create()
///       .await
///       .unwrap()
///       // register to global context.
///       .into_global();
///
/// # }
/// ```
///
/// Note: **the multiaddr '/p2p-circuit' can't be bound twice for same `Switch`.**
///
/// [**circuit_v2**]: https://github.com/libp2p/specs/blob/master/relay/circuit-v2.md#hop-protocol
///
#[derive(Default)]
pub struct CircuitTransport {
    activities: Arc<AtomicUsize>,
}

#[allow(unused)]
#[async_trait]
impl DriverTransport for CircuitTransport {
    fn name(&self) -> &str {
        "circuit"
    }
    fn activities(&self) -> usize {
        self.activities.load(Ordering::Relaxed)
    }
    /// Create a server-side socket with provided [`laddr`](Multiaddr).
    async fn bind(&self, switch: &Switch, laddr: &Multiaddr) -> std::io::Result<TransportListener> {
        panic!("Check multiaddr_hit fn.");
    }

    /// Connect to peer with remote peer [`raddr`](Multiaddr).
    async fn connect(&self, switch: &Switch, raddr: &Multiaddr) -> std::io::Result<P2pConn> {
        let peer_addr = raddr.clone();
        let mut raddr = raddr.clone();

        let circuit_addr = Multiaddr::empty().with(Protocol::P2pCircuit);

        let (raddr, peer_id) = if let Some(Protocol::P2p(id)) = raddr.pop() {
            if let Some(Protocol::P2pCircuit) = raddr.pop() {
                (raddr, id)
            } else {
                return Err(Error::ConnectAddr.into());
            }
        } else {
            return Err(Error::ConnectAddr.into());
        };

        log::trace!("circuit_v2, connect to hop={:?}", raddr);

        let mut stream = match switch.connect(&raddr, [PROTOCOL_CIRCUIT_RELAY_HOP]).await {
            Ok((stream, _)) => stream,
            Err(err) => {
                log::error!("circuit_v2, connect to hop={:?} with error: {}", raddr, err);
                return Err(err.into());
            }
        };

        let limits = match CircuitV2Rpc::circuit_v2_hop_connect(
            &mut stream,
            &peer_id,
            switch.max_packet_size,
        )
        .await
        {
            Ok(limits) => limits,
            Err(err) => {
                log::error!(
                    "circuit_v2, connect to hop={:?} handshake with error: {}",
                    raddr,
                    err
                );
                return Err(err.into());
            }
        };

        log::trace!("circuit_v2, connection limits={:?}", limits);

        let local_addr = stream.local_addr().clone();

        let conn = match TlsConn::connect(
            &switch,
            stream,
            local_addr,
            peer_addr,
            self.activities.clone(),
        )
        .await
        {
            Ok(conn) => conn,
            Err(err) => {
                log::trace!("circuit_v2, connection handshaked with error: {}", err);
                return Err(err.into());
            }
        };

        log::trace!("circuit_v2, connection handshaked");

        Ok(conn.into())
    }

    /// Check if this transport support the protocol stack represented by the `addr`.
    fn multiaddr_hint(&self, addr: &Multiaddr) -> bool {
        let circuit_addr = Multiaddr::empty().with(Protocol::P2pCircuit);

        // // for bind function.
        // if *addr == circuit_addr {
        //     return true;
        // }

        // below codes for connect function

        let mut addr = addr.clone();

        if let Some(Protocol::P2p(_)) = addr.pop() {
            if addr.ends_with(&circuit_addr) {
                return true;
            }
        }

        return false;
    }
}