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
// Copyright 2023 litep2p developers
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

//! Implementation of the notification handshaking.

use crate::{substream::Substream, PeerId};

use futures::{FutureExt, Sink, Stream};
use futures_timer::Delay;
use parking_lot::RwLock;

use std::{
    collections::{HashMap, VecDeque},
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
    time::Duration,
};

/// Logging target for the file.
const LOG_TARGET: &str = "litep2p::notification::negotiation";

/// Maximum timeout wait before for handshake before operation is considered failed.
const NEGOTIATION_TIMEOUT: Duration = Duration::from_secs(10);

/// Substream direction.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum Direction {
    /// Outbound substream, opened by local node.
    Outbound,

    /// Inbound substream, opened by remote node.
    Inbound,
}

/// Events emitted by [`HandshakeService`].
#[derive(Debug)]
pub enum HandshakeEvent {
    /// Substream has been negotiated.
    Negotiated {
        /// Peer ID.
        peer: PeerId,

        /// Handshake.
        handshake: Vec<u8>,

        /// Substream.
        substream: Substream,

        /// Direction.
        direction: Direction,
    },

    /// Outbound substream has been negotiated.
    NegotiationError {
        /// Peer ID.
        peer: PeerId,

        /// Direction.
        direction: Direction,
    },
}

/// Outbound substream's handshake state
enum HandshakeState {
    /// Send handshake to remote peer.
    SendHandshake,

    /// Sink is ready for the handshake to be sent.
    SinkReady,

    /// Handshake has been sent.
    HandshakeSent,

    /// Read handshake from remote peer.
    ReadHandshake,
}

/// Handshake service.
pub(crate) struct HandshakeService {
    /// Handshake.
    handshake: Arc<RwLock<Vec<u8>>>,

    /// Pending outbound substreams.
    /// Substreams:
    substreams: HashMap<(PeerId, Direction), (Substream, Delay, HandshakeState)>,

    /// Ready substreams.
    ready: VecDeque<(PeerId, Direction, Vec<u8>)>,
}

impl HandshakeService {
    /// Create new [`HandshakeService`].
    pub fn new(handshake: Arc<RwLock<Vec<u8>>>) -> Self {
        Self {
            handshake,
            ready: VecDeque::new(),
            substreams: HashMap::new(),
        }
    }

    /// Remove outbound substream from [`HandshakeService`].
    pub fn remove_outbound(&mut self, peer: &PeerId) -> Option<Substream> {
        self.substreams
            .remove(&(*peer, Direction::Outbound))
            .map(|(substream, _, _)| substream)
    }

    /// Remove inbound substream from [`HandshakeService`].
    pub fn remove_inbound(&mut self, peer: &PeerId) -> Option<Substream> {
        self.substreams
            .remove(&(*peer, Direction::Inbound))
            .map(|(substream, _, _)| substream)
    }

    /// Negotiate outbound handshake.
    pub fn negotiate_outbound(&mut self, peer: PeerId, substream: Substream) {
        tracing::trace!(target: LOG_TARGET, ?peer, "negotiate outbound");

        self.substreams.insert(
            (peer, Direction::Outbound),
            (
                substream,
                Delay::new(NEGOTIATION_TIMEOUT),
                HandshakeState::SendHandshake,
            ),
        );
    }

    /// Read handshake from remote peer.
    pub fn read_handshake(&mut self, peer: PeerId, substream: Substream) {
        tracing::trace!(target: LOG_TARGET, ?peer, "read handshake");

        self.substreams.insert(
            (peer, Direction::Inbound),
            (
                substream,
                Delay::new(NEGOTIATION_TIMEOUT),
                HandshakeState::ReadHandshake,
            ),
        );
    }

    /// Write handshake to remote peer.
    pub fn send_handshake(&mut self, peer: PeerId, substream: Substream) {
        tracing::trace!(target: LOG_TARGET, ?peer, "send handshake");

        self.substreams.insert(
            (peer, Direction::Inbound),
            (
                substream,
                Delay::new(NEGOTIATION_TIMEOUT),
                HandshakeState::SendHandshake,
            ),
        );
    }

    /// Returns `true` if [`HandshakeService`] contains no elements.
    pub fn is_empty(&self) -> bool {
        self.substreams.is_empty()
    }

    /// Pop event from the event queue.
    ///
    /// The substream may not exist in the queue anymore as it may have been removed
    /// by `NotificationProtocol` if either one of the substreams failed to negotiate.
    fn pop_event(&mut self) -> Option<(PeerId, HandshakeEvent)> {
        while let Some((peer, direction, handshake)) = self.ready.pop_front() {
            if let Some((substream, _, _)) = self.substreams.remove(&(peer, direction)) {
                return Some((
                    peer,
                    HandshakeEvent::Negotiated {
                        peer,
                        handshake,
                        substream,
                        direction,
                    },
                ));
            }
        }

        None
    }
}

impl Stream for HandshakeService {
    type Item = (PeerId, HandshakeEvent);

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let inner = Pin::into_inner(self);

        if let Some(event) = inner.pop_event() {
            return Poll::Ready(Some(event));
        }

        if inner.substreams.is_empty() {
            return Poll::Pending;
        }

        'outer: for ((peer, direction), (ref mut substream, ref mut timer, state)) in
            inner.substreams.iter_mut()
        {
            if let Poll::Ready(()) = timer.poll_unpin(cx) {
                return Poll::Ready(Some((
                    *peer,
                    HandshakeEvent::NegotiationError {
                        peer: *peer,
                        direction: *direction,
                    },
                )));
            }

            loop {
                let pinned = Pin::new(&mut *substream);

                match state {
                    HandshakeState::SendHandshake => match pinned.poll_ready(cx) {
                        Poll::Ready(Ok(())) => {
                            *state = HandshakeState::SinkReady;
                            continue;
                        }
                        Poll::Ready(Err(_)) =>
                            return Poll::Ready(Some((
                                *peer,
                                HandshakeEvent::NegotiationError {
                                    peer: *peer,
                                    direction: *direction,
                                },
                            ))),
                        Poll::Pending => continue 'outer,
                    },
                    HandshakeState::SinkReady => {
                        match pinned.start_send((*inner.handshake.read()).clone().into()) {
                            Ok(()) => {
                                *state = HandshakeState::HandshakeSent;
                                continue;
                            }
                            Err(_) =>
                                return Poll::Ready(Some((
                                    *peer,
                                    HandshakeEvent::NegotiationError {
                                        peer: *peer,
                                        direction: *direction,
                                    },
                                ))),
                        }
                    }
                    HandshakeState::HandshakeSent => match pinned.poll_flush(cx) {
                        Poll::Ready(Ok(())) => match direction {
                            Direction::Outbound => {
                                *state = HandshakeState::ReadHandshake;
                                continue;
                            }
                            Direction::Inbound => {
                                inner.ready.push_back((*peer, *direction, vec![]));
                                continue 'outer;
                            }
                        },
                        Poll::Ready(Err(_)) =>
                            return Poll::Ready(Some((
                                *peer,
                                HandshakeEvent::NegotiationError {
                                    peer: *peer,
                                    direction: *direction,
                                },
                            ))),
                        Poll::Pending => continue 'outer,
                    },
                    HandshakeState::ReadHandshake => match pinned.poll_next(cx) {
                        Poll::Ready(Some(Ok(handshake))) => {
                            inner.ready.push_back((*peer, *direction, handshake.freeze().into()));
                            continue 'outer;
                        }
                        Poll::Ready(Some(Err(_))) | Poll::Ready(None) => {
                            return Poll::Ready(Some((
                                *peer,
                                HandshakeEvent::NegotiationError {
                                    peer: *peer,
                                    direction: *direction,
                                },
                            )));
                        }
                        Poll::Pending => continue 'outer,
                    },
                }
            }
        }

        if let Some((peer, direction, handshake)) = inner.ready.pop_front() {
            let (substream, _, _) =
                inner.substreams.remove(&(peer, direction)).expect("peer to exist");

            return Poll::Ready(Some((
                peer,
                HandshakeEvent::Negotiated {
                    peer,
                    handshake,
                    substream,
                    direction,
                },
            )));
        }

        Poll::Pending
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        mock::substream::{DummySubstream, MockSubstream},
        types::SubstreamId,
    };
    use futures::StreamExt;

    #[tokio::test]
    async fn substream_error_when_sending_handshake() {
        let mut service = HandshakeService::new(Arc::new(RwLock::new(vec![1, 2, 3, 4])));

        futures::future::poll_fn(|cx| match service.poll_next_unpin(cx) {
            Poll::Pending => Poll::Ready(()),
            _ => panic!("invalid event received"),
        })
        .await;

        let mut substream = MockSubstream::new();
        substream.expect_poll_ready().times(1).return_once(|_| Poll::Ready(Ok(())));
        substream
            .expect_start_send()
            .times(1)
            .return_once(|_| Err(crate::error::SubstreamError::ConnectionClosed));

        let peer = PeerId::random();
        let substream = Substream::new_mock(peer, SubstreamId::from(0usize), Box::new(substream));

        service.send_handshake(peer, substream);
        match service.next().await {
            Some((
                failed_peer,
                HandshakeEvent::NegotiationError {
                    peer: event_peer,
                    direction,
                },
            )) => {
                assert_eq!(failed_peer, peer);
                assert_eq!(event_peer, peer);
                assert_eq!(direction, Direction::Inbound);
            }
            _ => panic!("invalid event received"),
        }
    }

    #[tokio::test]
    async fn substream_error_when_flushing_substream() {
        let mut service = HandshakeService::new(Arc::new(RwLock::new(vec![1, 2, 3, 4])));

        futures::future::poll_fn(|cx| match service.poll_next_unpin(cx) {
            Poll::Pending => Poll::Ready(()),
            _ => panic!("invalid event received"),
        })
        .await;

        let mut substream = MockSubstream::new();
        substream.expect_poll_ready().times(1).return_once(|_| Poll::Ready(Ok(())));
        substream.expect_start_send().times(1).return_once(|_| Ok(()));
        substream
            .expect_poll_flush()
            .times(1)
            .return_once(|_| Poll::Ready(Err(crate::error::SubstreamError::ConnectionClosed)));

        let peer = PeerId::random();
        let substream = Substream::new_mock(peer, SubstreamId::from(0usize), Box::new(substream));

        service.send_handshake(peer, substream);
        match service.next().await {
            Some((
                failed_peer,
                HandshakeEvent::NegotiationError {
                    peer: event_peer,
                    direction,
                },
            )) => {
                assert_eq!(failed_peer, peer);
                assert_eq!(event_peer, peer);
                assert_eq!(direction, Direction::Inbound);
            }
            _ => panic!("invalid event received"),
        }
    }

    // inbound substream is negotiated and it pushed into `inner` but outbound substream fails to
    // negotiate
    #[tokio::test]
    async fn pop_event_but_substream_doesnt_exist() {
        let mut service = HandshakeService::new(Arc::new(RwLock::new(vec![1, 2, 3, 4])));
        let peer = PeerId::random();

        // inbound substream has finished
        service.ready.push_front((peer, Direction::Inbound, vec![]));
        service.substreams.insert(
            (peer, Direction::Inbound),
            (
                Substream::new_mock(
                    peer,
                    SubstreamId::from(1337usize),
                    Box::new(DummySubstream::new()),
                ),
                Delay::new(NEGOTIATION_TIMEOUT),
                HandshakeState::HandshakeSent,
            ),
        );
        service.substreams.insert(
            (peer, Direction::Outbound),
            (
                Substream::new_mock(
                    peer,
                    SubstreamId::from(1337usize),
                    Box::new(DummySubstream::new()),
                ),
                Delay::new(NEGOTIATION_TIMEOUT),
                HandshakeState::SendHandshake,
            ),
        );

        // outbound substream failed and `NotificationProtocol` removes
        // both substreams from `HandshakeService`
        assert!(service.remove_outbound(&peer).is_some());
        assert!(service.remove_inbound(&peer).is_some());

        futures::future::poll_fn(|cx| match service.poll_next_unpin(cx) {
            Poll::Pending => Poll::Ready(()),
            _ => panic!("invalid event received"),
        })
        .await
    }
}