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
use std::{
    fmt::Display,
    future::Future,
    time::{Duration, SystemTime},
    usize,
};

use futures::{AsyncRead, AsyncWrite};
use protobuf::{EnumOrUnknown, MessageField};

use crate::{
    proto::{
        circuit::{self, hop_message, stop_message, HopMessage, Status, StopMessage},
        DCUtR,
    },
    Error, Result,
};

use xstack::{identity::PeerId, multiaddr::Multiaddr, XStackRpc};

/// Result of [`circuit_v2_hop_reserve`](CircuitV2Rpc::circuit_v2_hop_reserve) function
#[derive(Debug, Clone)]
pub struct Reservation {
    /// expiration time of the voucher
    pub expire: SystemTime,
    /// the public relay addrs, including the peer ID of the relay node but not the trailing p2p-circuit part;
    pub addrs: Vec<Multiaddr>,
    /// When omitted, it indicates that the relay does not apply any limits.
    pub limit: Option<Limit>,
}

/// provides information about the limits applied by the relay in relayed connection
#[derive(Debug, Clone)]
pub struct Limit {
    /// the maximum duration of a relayed connection in seconds; if None, there is no limit applied
    pub duration: Option<Duration>,
    /// the maximum number of bytes allowed to be transmitted in each direction; if None there is no limit applied
    pub data: Option<usize>,
}

impl Display for Limit {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "duration={:?}, data={:?}", self.duration, self.data)
    }
}

impl From<circuit::Limit> for Limit {
    fn from(limit: circuit::Limit) -> Self {
        Limit {
            duration: limit.duration.map(|dur| Duration::from_secs(dur as u64)),
            data: limit.data.map(|data| data as usize),
        }
    }
}

impl From<Limit> for circuit::Limit {
    fn from(limit: Limit) -> Self {
        circuit::Limit {
            duration: limit.duration.map(|dur| dur.as_secs() as u32),
            data: limit.data.map(|data| data as u64),
            ..Default::default()
        }
    }
}

/// An extension trait for circuit v2 protocol.
pub trait CircuitV2Rpc: AsyncRead + AsyncWrite + Unpin {
    /// make a reservation to relayer via this stream.
    fn circuit_v2_hop_reserve(
        self,
        max_recv_len: usize,
    ) -> impl Future<Output = Result<Reservation>>
    where
        Self: Sized,
    {
        let mut message = HopMessage::new();

        message.type_ = Some(circuit::hop_message::Type::RESERVE.into());

        async move {
            let message = self.xstack_call(&message, max_recv_len).await?;

            if message.type_ != Some(hop_message::Type::STATUS.into()) {
                return Err(crate::Error::HotReject(
                    "Invalid response, expect status".to_owned(),
                ));
            }

            match message.status {
                Some(status) => {
                    if EnumOrUnknown::from(Status::OK) != status {
                        return Err(crate::Error::HotReject(format!("{:?}", status)));
                    }
                }
                _ => return Err(crate::Error::HotReject("status field is null".to_owned())),
            }

            if let Some(reservation) = message.reservation.into_option() {
                return Ok(Reservation {
                    expire: reservation
                        .expire
                        .map(|value| SystemTime::UNIX_EPOCH + Duration::from_secs(value))
                        .ok_or(Error::ReservationExpire)?,
                    addrs: reservation
                        .addrs
                        .into_iter()
                        .map(|buf| Multiaddr::try_from(buf).map_err(Into::into))
                        .collect::<Result<Vec<_>>>()?,

                    limit: message.limit.into_option().map(|limit| limit.into()),
                });
            }

            return Err(crate::Error::HotReject(
                "reservation field is null".to_owned(),
            ));
        }
    }

    /// make a connect to relayer via this stream.
    fn circuit_v2_hop_connect(
        self,
        id: &PeerId,
        max_recv_len: usize,
    ) -> impl Future<Output = Result<Option<Limit>>>
    where
        Self: Sized,
    {
        let mut message = HopMessage::new();

        message.type_ = Some(circuit::hop_message::Type::CONNECT.into());

        message.peer = MessageField::some(circuit::Peer {
            id: Some(id.to_bytes()),
            // we don't support `Active relay functionality`
            ..Default::default()
        });

        async move {
            let message = self.xstack_call(&message, max_recv_len).await?;

            if message.type_ != Some(hop_message::Type::STATUS.into()) {
                return Err(crate::Error::HotReject(
                    "Invalid response, expect status".to_owned(),
                ));
            }

            match message.status {
                Some(status) => {
                    if EnumOrUnknown::from(Status::OK) != status {
                        return Err(crate::Error::HotReject(format!("{:?}", status)));
                    }
                }
                _ => return Err(crate::Error::HotReject("status field is null".to_owned())),
            }

            Ok(message.limit.into_option().map(|limit| limit.into()))
        }
    }

    /// make a connect to terminator via this stream.
    fn circuit_v2_stop_connect(
        self,
        id: PeerId,
        max_recv_len: usize,
    ) -> impl Future<Output = Result<()>>
    where
        Self: Sized,
    {
        let mut message = StopMessage::new();

        message.type_ = Some(circuit::stop_message::Type::CONNECT.into());

        message.peer = MessageField::some(circuit::Peer {
            id: Some(id.to_bytes()),
            // we don't support `Active relay functionality`
            ..Default::default()
        });

        async move {
            let message = self.xstack_call(&message, max_recv_len).await?;

            if message.type_ != Some(stop_message::Type::STATUS.into()) {
                return Err(crate::Error::HotReject(
                    "Invalid response, expect status".to_owned(),
                ));
            }

            match message.status {
                Some(status) => {
                    if EnumOrUnknown::from(Status::OK) != status {
                        return Err(crate::Error::HotReject(format!("{:?}", status)));
                    }
                }
                _ => return Err(crate::Error::HotReject("status field is null".to_owned())),
            }

            Ok(())
        }
    }

    /// make a connect to relayer via this stream.
    fn circuit_v2_stop_connect_accept(
        mut self,
        max_recv_len: usize,
    ) -> impl Future<Output = Result<Option<Limit>>>
    where
        Self: Sized,
    {
        async move {
            let stop_message =
                XStackRpc::xstack_recv::<StopMessage>(&mut self, max_recv_len).await?;

            if stop_message.type_ != Some(stop_message::Type::CONNECT.into()) {
                return Err(Error::CircuitStop("expect CONNECT".to_owned()).into());
            }

            let mut response = StopMessage::new();

            response.type_ = Some(stop_message::Type::STATUS.into());

            response.status = Some(Status::OK.into());
            XStackRpc::xstack_send(&mut self, &response).await?;

            Ok(stop_message.limit.into_option().map(|limits| limits.into()))
        }
    }
}

impl<S> CircuitV2Rpc for S where S: AsyncRead + AsyncWrite + Unpin {}

/// An extension trait for [`DCUtR`] protocol.
///
/// [`DCUtR`]: https://github.com/libp2p/specs/blob/master/relay/DCUtR.md
pub trait DCUtRRpc: AsyncRead + AsyncWrite + Unpin {
    /// Send a `DCUtR Connect` message via this stream.
    fn dcutr_send_connect(self, observed_addrs: &[Multiaddr]) -> impl Future<Output = Result<()>>
    where
        Self: Sized,
    {
        let mut message = DCUtR::HolePunch::new();

        message.type_ = Some(DCUtR::hole_punch::Type::CONNECT.into());
        message.ObsAddrs = observed_addrs.iter().map(|addr| addr.to_vec()).collect();

        async move { Ok(XStackRpc::xstack_send(self, &message).await?) }
    }

    /// Recv a `DCUtR Connect` message via this stream.
    fn dcutr_recv_connect(self, max_recv_len: usize) -> impl Future<Output = Result<Vec<Multiaddr>>>
    where
        Self: Sized,
    {
        async move {
            let message = XStackRpc::xstack_recv::<DCUtR::HolePunch>(self, max_recv_len).await?;

            if message.type_ != Some(DCUtR::hole_punch::Type::CONNECT.into()) {
                return Err(Error::DCUtRConnect);
            }

            let addrs = message
                .ObsAddrs
                .into_iter()
                .map(|addr| Multiaddr::try_from(addr).map_err(|err| err.into()))
                .collect::<Result<Vec<_>>>()?;

            Ok(addrs)
        }
    }

    /// Send a `DCUtR Sync` message via this stream.
    fn dcutr_send_sync(self) -> impl Future<Output = Result<()>>
    where
        Self: Sized,
    {
        let mut message = DCUtR::HolePunch::new();

        message.type_ = Some(DCUtR::hole_punch::Type::SYNC.into());

        async move { Ok(XStackRpc::xstack_send(self, &message).await?) }
    }

    /// Recv a `DCUtR Sync` message via this stream.
    fn dcutr_recv_sync(self, max_recv_len: usize) -> impl Future<Output = Result<()>>
    where
        Self: Sized,
    {
        async move {
            let message = XStackRpc::xstack_recv::<DCUtR::HolePunch>(self, max_recv_len).await?;

            if message.type_ != Some(DCUtR::hole_punch::Type::SYNC.into()) {
                return Err(Error::DCUtRSync);
            }

            Ok(())
        }
    }
}

impl<S> DCUtRRpc for S where S: AsyncRead + AsyncWrite + Unpin {}