-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathmod.rs
1822 lines (1664 loc) · 76 KB
/
mod.rs
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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.
//! Notification protocol implementation.
use crate::{
error::{Error, SubstreamError},
executor::Executor,
protocol::{
self,
notification::{
connection::Connection,
handle::NotificationEventHandle,
negotiation::{HandshakeEvent, HandshakeService},
types::NotificationCommand,
},
TransportEvent, TransportService,
},
substream::Substream,
types::{protocol::ProtocolName, SubstreamId},
PeerId, DEFAULT_CHANNEL_SIZE,
};
use bytes::BytesMut;
use futures::{future::BoxFuture, stream::FuturesUnordered, StreamExt};
use multiaddr::Multiaddr;
use tokio::sync::{
mpsc::{channel, Receiver, Sender},
oneshot,
};
use std::{collections::HashMap, sync::Arc, time::Duration};
pub use config::{Config, ConfigBuilder};
pub use handle::{NotificationHandle, NotificationSink};
pub use types::{Direction, NotificationError, NotificationEvent, ValidationResult};
mod config;
mod connection;
mod handle;
mod negotiation;
mod types;
#[cfg(test)]
mod tests;
/// Logging target for the file.
const LOG_TARGET: &str = "litep2p::notification";
/// Connection state.
///
/// Used to track transport level connectivity state when there is a pending validation.
/// See [`PeerState::PendingValidation.`] for more details.
#[derive(Debug, PartialEq, Eq)]
enum ConnectionState {
/// There is a active, transport-level connection open to the peer.
Open,
/// There is no transport-level connection open to the peer.
Closed,
}
/// Inbound substream state.
#[derive(Debug)]
enum InboundState {
/// Substream is closed.
Closed,
/// Handshake is being read from the remote node.
ReadingHandshake,
/// Substream and its handshake are being validated by the user protocol.
Validating {
/// Inbound substream.
inbound: Substream,
},
/// Handshake is being sent to the remote node.
SendingHandshake,
/// Substream is open.
Open {
/// Inbound substream.
inbound: Substream,
},
}
/// Outbound substream state.
#[derive(Debug)]
enum OutboundState {
/// Substream is closed.
Closed,
/// Outbound substream initiated.
OutboundInitiated {
/// Substream ID.
substream: SubstreamId,
},
/// Substream is in the state of being negotiated.
///
/// This process entails sending local node's handshake and reading back the remote node's
/// handshake if they've accepted the substream or detecting that the substream was closed
/// in case the substream was rejected.
Negotiating,
/// Substream is open.
Open {
/// Received handshake.
handshake: Vec<u8>,
/// Outbound substream.
outbound: Substream,
},
}
impl OutboundState {
/// Get pending outboud substream ID, if it exists.
fn pending_open(&self) -> Option<SubstreamId> {
match &self {
OutboundState::OutboundInitiated { substream } => Some(*substream),
_ => None,
}
}
}
#[derive(Debug)]
enum PeerState {
/// Peer state is poisoned due to invalid state transition.
Poisoned,
/// Validation for an inbound substream is still pending.
///
/// In order to enforce valid state transitions, `NotificationProtocol` keeps track of pending
/// validations across connectivity events (open/closed) and enforces that no activity happens
/// for any peer that is still awaiting validation for their inbound substream.
///
/// If connection closes while the substream is being validated, instead of removing peer from
/// `peers`, the peer state is set as `ValidationPending` which indicates to the state machine
/// that a response for a inbound substream is pending validation. The substream itself will be
/// dead by the time validation is received if the peer state is `ValidationPending` since the
/// substream was part of a previous, now-closed substream but this state allows
/// `NotificationProtocol` to enforce correct state transitions by, e.g., rejecting new inbound
/// substream while a previous substream is still being validated or rejecting outbound
/// substreams on new connections if that same condition holds.
ValidationPending {
/// What is current connectivity state of the peer.
///
/// If `state` is `ConnectionState::Closed` when the validation is finally received, peer
/// is removed from `peer` and if the `state` is `ConnectionState::Open`, peer is moved to
/// state `PeerState::Closed` and user is allowed to retry opening an outbound substream.
state: ConnectionState,
},
/// Connection to peer is closed.
Closed {
/// Connection might have been closed while there was an outbound substream still pending.
///
/// To handle this state transition correctly in case the substream opens after the
/// connection is considered closed, store the `SubstreamId` to that it can be verified in
/// case the substream ever opens.
pending_open: Option<SubstreamId>,
},
/// Peer is being dialed in order to open an outbound substream to them.
Dialing,
/// Outbound substream initiated.
OutboundInitiated {
/// Substream ID.
substream: SubstreamId,
},
/// Substream is being validated.
Validating {
/// Protocol.
protocol: ProtocolName,
/// Fallback protocol, if the substream was negotiated using a fallback name.
fallback: Option<ProtocolName>,
/// Outbound protocol state.
outbound: OutboundState,
/// Inbound protocol state.
inbound: InboundState,
/// Direction.
direction: Direction,
},
/// Notification stream has been opened.
Open {
/// `Oneshot::Sender` for shutting down the connection.
shutdown: oneshot::Sender<()>,
},
}
/// Peer context.
#[derive(Debug)]
struct PeerContext {
/// Peer state.
state: PeerState,
}
impl PeerContext {
/// Create new [`PeerContext`].
fn new() -> Self {
Self {
state: PeerState::Closed { pending_open: None },
}
}
}
pub(crate) struct NotificationProtocol {
/// Transport service.
service: TransportService,
/// Protocol.
protocol: ProtocolName,
/// Auto accept inbound substream if the outbound substream was initiated by the local node.
auto_accept: bool,
/// TX channel passed to the protocol used for sending events.
event_handle: NotificationEventHandle,
/// TX channel for sending shut down notifications from connection handlers to
/// [`NotificationProtocol`].
shutdown_tx: Sender<PeerId>,
/// RX channel for receiving shutdown notifications from the connection handlers.
shutdown_rx: Receiver<PeerId>,
/// RX channel passed to the protocol used for receiving commands.
command_rx: Receiver<NotificationCommand>,
/// TX channel given to connection handlers for sending notifications.
notif_tx: Sender<(PeerId, BytesMut)>,
/// Connected peers.
peers: HashMap<PeerId, PeerContext>,
/// Pending outboudn substreams.
pending_outbound: HashMap<SubstreamId, PeerId>,
/// Handshaking service which reads and writes the handshakes to inbound
/// and outbound substreams asynchronously.
negotiation: HandshakeService,
/// Synchronous channel size.
sync_channel_size: usize,
/// Asynchronous channel size.
async_channel_size: usize,
/// Executor for connection handlers.
executor: Arc<dyn Executor>,
/// Pending substream validations.
pending_validations: FuturesUnordered<BoxFuture<'static, (PeerId, ValidationResult)>>,
/// Timers for pending outbound substreams.
timers: FuturesUnordered<BoxFuture<'static, PeerId>>,
/// Should `NotificationProtocol` attempt to dial the peer.
should_dial: bool,
}
impl NotificationProtocol {
pub(crate) fn new(
service: TransportService,
config: Config,
executor: Arc<dyn Executor>,
) -> Self {
let (shutdown_tx, shutdown_rx) = channel(DEFAULT_CHANNEL_SIZE);
Self {
service,
shutdown_tx,
shutdown_rx,
executor,
peers: HashMap::new(),
protocol: config.protocol_name,
auto_accept: config.auto_accept,
pending_validations: FuturesUnordered::new(),
timers: FuturesUnordered::new(),
event_handle: NotificationEventHandle::new(config.event_tx),
notif_tx: config.notif_tx,
command_rx: config.command_rx,
pending_outbound: HashMap::new(),
negotiation: HandshakeService::new(config.handshake),
sync_channel_size: config.sync_channel_size,
async_channel_size: config.async_channel_size,
should_dial: config.should_dial,
}
}
/// Connection established to remote node.
///
/// If the peer already exists, the only valid state for it is `Dialing` as it indicates that
/// the user tried to open a substream to a peer who was not connected to local node.
///
/// Any other state indicates that there's an error in the state transition logic.
async fn on_connection_established(&mut self, peer: PeerId) -> crate::Result<()> {
tracing::trace!(target: LOG_TARGET, ?peer, protocol = %self.protocol, "connection established");
let Some(context) = self.peers.get_mut(&peer) else {
self.peers.insert(peer, PeerContext::new());
return Ok(());
};
match std::mem::replace(&mut context.state, PeerState::Poisoned) {
PeerState::Dialing => {
tracing::trace!(
target: LOG_TARGET,
?peer,
protocol = %self.protocol,
"dial succeeded, open substream to peer",
);
context.state = PeerState::Closed { pending_open: None };
self.on_open_substream(peer).await
}
// connection established but validation is still pending
//
// update the connection state so that `NotificationProtocol` can proceed
// to correct state after the validation result has beern received
PeerState::ValidationPending { state } => {
debug_assert_eq!(state, ConnectionState::Closed);
tracing::debug!(
target: LOG_TARGET,
?peer,
protocol = %self.protocol,
"new connection established while validation still pending",
);
context.state = PeerState::ValidationPending {
state: ConnectionState::Open,
};
Ok(())
}
state => {
tracing::error!(
target: LOG_TARGET,
?peer,
protocol = %self.protocol,
?state,
"state mismatch: peer already exists",
);
debug_assert!(false);
Err(Error::PeerAlreadyExists(peer))
}
}
}
/// Connection closed to remote node.
///
/// If the connection was considered open (both substreams were open), user is notified that
/// the notification stream was closed.
///
/// If the connection was still in progress (either substream was not fully open), the user is
/// reported about it only if they had opened an outbound substream (outbound is either fully
/// open, it had been initiated or the substream was under negotiation).
async fn on_connection_closed(&mut self, peer: PeerId) -> crate::Result<()> {
tracing::trace!(target: LOG_TARGET, ?peer, protocol = %self.protocol, "connection closed");
let Some(context) = self.peers.remove(&peer) else {
tracing::error!(
target: LOG_TARGET,
?peer,
protocol = %self.protocol,
"state mismatch: peer doesn't exist",
);
debug_assert!(false);
return Err(Error::PeerDoesntExist(peer));
};
// clean up all pending state for the peer
self.negotiation.remove_outbound(&peer);
self.negotiation.remove_inbound(&peer);
match context.state {
// outbound initiated, report open failure to peer
PeerState::OutboundInitiated { .. } => {
self.event_handle
.report_notification_stream_open_failure(peer, NotificationError::Rejected)
.await;
}
// substream fully open, report that the notification stream is closed
PeerState::Open { shutdown } => {
let _ = shutdown.send(());
}
// if the substream was being validated, user must be notified that the substream is
// now considered rejected if they had been made aware of the existence of the pending
// connection
PeerState::Validating {
outbound, inbound, ..
} => {
match (outbound, inbound) {
// substream was being validated by the protocol when the connection was closed
(OutboundState::Closed, InboundState::Validating { .. }) => {
tracing::debug!(
target: LOG_TARGET,
?peer,
protocol = %self.protocol,
"connection closed while validation pending",
);
self.peers.insert(
peer,
PeerContext {
state: PeerState::ValidationPending {
state: ConnectionState::Closed,
},
},
);
}
// user either initiated an outbound substream or an outbound substream was
// opened/being opened as a result of an accepted inbound substream but was not
// yet fully open
//
// to have consistent state tracking in the user protocol, substream rejection
// must be reported to the user
(
OutboundState::OutboundInitiated { .. }
| OutboundState::Negotiating
| OutboundState::Open { .. },
_,
) => {
tracing::debug!(
target: LOG_TARGET,
?peer,
protocol = %self.protocol,
"connection closed outbound substream under negotiation",
);
self.event_handle
.report_notification_stream_open_failure(
peer,
NotificationError::Rejected,
)
.await;
}
(_, _) => {}
}
}
// pending validations must be tracked across connection open/close events
PeerState::ValidationPending { .. } => {
tracing::debug!(
target: LOG_TARGET,
?peer,
protocol = %self.protocol,
"validation pending while connection closed",
);
self.peers.insert(
peer,
PeerContext {
state: PeerState::ValidationPending {
state: ConnectionState::Closed,
},
},
);
}
_ => {}
}
Ok(())
}
/// Local node opened a substream to remote node.
///
/// The connection can be in three different states:
/// - this is the first substream that was opened and thus the connection was initiated by the
/// local node
/// - this is a response to a previously received inbound substream which the local node
/// accepted and as a result, opened its own substream
/// - local and remote nodes opened substreams at the same time
///
/// In the first case, the local node's handshake is sent to remote node and the substream is
/// polled in the background until they either send their handshake or close the substream.
///
/// For the second case, the connection was initiated by the remote node and the substream was
/// accepted by the local node which initiated an outbound substream to the remote node.
/// The only valid states for this case are [`InboundState::Open`],
/// and [`InboundState::SendingHandshake`] as they imply
/// that the inbound substream have been accepted by the local node and this opened outbound
/// substream is a result of a valid state transition.
///
/// For the third case, if the nodes have opened substreams at the same time, the outbound state
/// must be [`OutboundState::OutboundInitiated`] to ascertain that the an outbound substream was
/// actually opened. Any other state would be a state mismatch and would mean that the
/// connection is opening substreams without the permission of the protocol handler.
async fn on_outbound_substream(
&mut self,
protocol: ProtocolName,
fallback: Option<ProtocolName>,
peer: PeerId,
substream_id: SubstreamId,
outbound: Substream,
) -> crate::Result<()> {
tracing::debug!(
target: LOG_TARGET,
?peer,
?protocol,
?substream_id,
"handle outbound substream",
);
// peer must exist since an outbound substream was received from them
let Some(context) = self.peers.get_mut(&peer) else {
tracing::error!(target: LOG_TARGET, ?peer, "peer doesn't exist for outbound substream");
debug_assert!(false);
return Err(Error::PeerDoesntExist(peer));
};
let pending_peer = self.pending_outbound.remove(&substream_id);
match std::mem::replace(&mut context.state, PeerState::Poisoned) {
// the connection was initiated by the local node, send handshake to remote and wait to
// receive their handshake back
PeerState::OutboundInitiated { substream } => {
debug_assert!(substream == substream_id);
debug_assert!(pending_peer == Some(peer));
tracing::trace!(
target: LOG_TARGET,
?peer,
protocol = %self.protocol,
?fallback,
?substream_id,
"negotiate outbound protocol",
);
self.negotiation.negotiate_outbound(peer, outbound);
context.state = PeerState::Validating {
protocol,
fallback,
inbound: InboundState::Closed,
outbound: OutboundState::Negotiating,
direction: Direction::Outbound,
};
}
PeerState::Validating {
protocol,
fallback,
inbound,
direction,
outbound: outbound_state,
} => {
// the inbound substream has been accepted by the local node since the handshake has
// been read and the local handshake has either already been sent or
// it's in the process of being sent.
match inbound {
InboundState::SendingHandshake | InboundState::Open { .. } => {
context.state = PeerState::Validating {
protocol,
fallback,
inbound,
direction,
outbound: OutboundState::Negotiating,
};
self.negotiation.negotiate_outbound(peer, outbound);
}
// nodes have opened substreams at the same time
inbound_state => match outbound_state {
OutboundState::OutboundInitiated { substream } => {
debug_assert!(substream == substream_id);
context.state = PeerState::Validating {
protocol,
fallback,
direction,
inbound: inbound_state,
outbound: OutboundState::Negotiating,
};
self.negotiation.negotiate_outbound(peer, outbound);
}
// invalid state: more than one outbound substream has been opened
inner_state => {
tracing::error!(
target: LOG_TARGET,
?peer,
%protocol,
?substream_id,
?inbound_state,
?inner_state,
"invalid state, expected `OutboundInitiated`",
);
let _ = outbound.close().await;
debug_assert!(false);
}
},
}
}
// the connection may have been closed while an outbound substream was pending
// if the outbound substream was initiated successfully, close it and reset
// `pending_open`
PeerState::Closed { pending_open } if pending_open == Some(substream_id) => {
let _ = outbound.close().await;
context.state = PeerState::Closed { pending_open: None };
}
state => {
tracing::error!(
target: LOG_TARGET,
?peer,
%protocol,
?substream_id,
?state,
"invalid state: more than one outbound substream opened",
);
let _ = outbound.close().await;
debug_assert!(false);
}
}
Ok(())
}
/// Remote opened a substream to local node.
///
/// The peer can be in four different states for the inbound substream to be considered valid:
/// - the connection is closed
/// - conneection is open but substream validation from a previous connection is still pending
/// - outbound substream has been opened but not yet acknowledged by the remote peer
/// - outbound substream has been opened and acknowledged by the remote peer and it's being
/// negotiated
///
/// If remote opened more than one substream, the new substream is simply discarded.
async fn on_inbound_substream(
&mut self,
protocol: ProtocolName,
fallback: Option<ProtocolName>,
peer: PeerId,
substream: Substream,
) -> crate::Result<()> {
// peer must exist since an inbound substream was received from them
let Some(context) = self.peers.get_mut(&peer) else {
tracing::error!(target: LOG_TARGET, ?peer, "peer doesn't exist for inbound substream");
debug_assert!(false);
return Err(Error::PeerDoesntExist(peer));
};
tracing::debug!(
target: LOG_TARGET,
?peer,
%protocol,
?fallback,
state = ?context.state,
"handle inbound substream",
);
match std::mem::replace(&mut context.state, PeerState::Poisoned) {
// inbound substream of a previous connection is still pending validation,
// reject any new inbound substreams until an answer is heard from the user
state @ PeerState::ValidationPending { .. } => {
tracing::debug!(
target: LOG_TARGET,
?peer,
%protocol,
?fallback,
?state,
"validation for previous substream still pending",
);
let _ = substream.close().await;
context.state = state;
}
// outbound substream for previous connection still pending, reject inbound substream
// and wait for the outbound substream state to conclude as either succeeded or failed
// before accepting any inbound substreams.
PeerState::Closed {
pending_open: Some(substream_id),
} => {
tracing::debug!(
target: LOG_TARGET,
?peer,
protocol = %self.protocol,
"received inbound substream while outbound substream opening, rejecting",
);
let _ = substream.close().await;
context.state = PeerState::Closed {
pending_open: Some(substream_id),
};
}
// the peer state is closed so this is a fresh inbound substream.
PeerState::Closed { pending_open: None } => {
self.negotiation.read_handshake(peer, substream);
context.state = PeerState::Validating {
protocol,
fallback,
direction: Direction::Inbound,
inbound: InboundState::ReadingHandshake,
outbound: OutboundState::Closed,
};
}
// if the connection is under validation (so an outbound substream has been opened and
// it's still pending or under negotiation), the only valid state for the
// inbound state is closed as it indicates that there isn't an inbound substream yet for
// the remote node duplicate substreams are prohibited.
PeerState::Validating {
protocol,
fallback,
outbound,
direction,
inbound: InboundState::Closed,
} => {
self.negotiation.read_handshake(peer, substream);
context.state = PeerState::Validating {
protocol,
fallback,
outbound,
direction,
inbound: InboundState::ReadingHandshake,
};
}
// outbound substream may have been initiated by the local node while a remote node also
// opened a substream roughly at the same time
PeerState::OutboundInitiated {
substream: outbound,
} => {
self.negotiation.read_handshake(peer, substream);
context.state = PeerState::Validating {
protocol,
fallback,
direction: Direction::Outbound,
outbound: OutboundState::OutboundInitiated {
substream: outbound,
},
inbound: InboundState::ReadingHandshake,
};
}
// new inbound substream opend while validation for the previous substream was still
// pending
//
// the old substream can be considered dead because remote wouldn't open a new substream
// to us unless they had discarded the previous substream.
//
// set peer state to `ValidationPending` to indicate that the peer is "blocked" until a
// validation for the substream is heard, blocking any further activity for
// the connection and once the validation is received and in case the
// substream is accepted, it will be reported as open failure to to the peer
// because the states have gone out of sync.
PeerState::Validating {
outbound: OutboundState::Closed,
inbound:
InboundState::Validating {
inbound: pending_substream,
},
..
} => {
tracing::debug!(
target: LOG_TARGET,
?peer,
protocol = %self.protocol,
"remote opened substream while previous was still pending, connection failed",
);
let _ = substream.close().await;
let _ = pending_substream.close().await;
context.state = PeerState::ValidationPending {
state: ConnectionState::Open,
};
}
// remote opened another inbound substream, close it and otherwise ignore the event
// as this is a non-serious protocol violation.
state => {
tracing::debug!(
target: LOG_TARGET,
?peer,
%protocol,
?fallback,
?state,
"remote opened more than one inbound substreams, discarding",
);
let _ = substream.close().await;
context.state = state;
}
}
Ok(())
}
/// Failed to open substream to remote node.
///
/// If the substream was initiated by the local node, it must be reported that the substream
/// failed to open. Otherwise the peer state can silently be converted to `Closed`.
async fn on_substream_open_failure(
&mut self,
substream_id: SubstreamId,
error: SubstreamError,
) {
tracing::debug!(
target: LOG_TARGET,
protocol = %self.protocol,
?substream_id,
?error,
"failed to open substream"
);
let Some(peer) = self.pending_outbound.remove(&substream_id) else {
tracing::warn!(
target: LOG_TARGET,
protocol = %self.protocol,
?substream_id,
"pending outbound substream doesn't exist",
);
debug_assert!(false);
return;
};
// peer must exist since an outbound substream failure was received from them
let Some(context) = self.peers.get_mut(&peer) else {
tracing::warn!(target: LOG_TARGET, ?peer, "peer doesn't exist");
debug_assert!(false);
return;
};
match &mut context.state {
PeerState::OutboundInitiated { .. } => {
context.state = PeerState::Closed { pending_open: None };
self.event_handle
.report_notification_stream_open_failure(peer, NotificationError::Rejected)
.await;
}
// if the substream was accepted by the local node and as a result, an outbound
// substream was accepted as a result this should not be reported to local node
PeerState::Validating { outbound, .. } => {
self.negotiation.remove_inbound(&peer);
self.negotiation.remove_outbound(&peer);
let pending_open = match outbound {
OutboundState::Closed => None,
OutboundState::OutboundInitiated { substream } => {
self.event_handle
.report_notification_stream_open_failure(
peer,
NotificationError::Rejected,
)
.await;
Some(*substream)
}
OutboundState::Negotiating | OutboundState::Open { .. } => {
self.event_handle
.report_notification_stream_open_failure(
peer,
NotificationError::Rejected,
)
.await;
None
}
};
context.state = PeerState::Closed { pending_open };
}
PeerState::Closed { pending_open } => {
tracing::debug!(
target: LOG_TARGET,
protocol = %self.protocol,
?substream_id,
"substream open failure for a closed connection",
);
debug_assert_eq!(pending_open, &Some(substream_id));
context.state = PeerState::Closed { pending_open: None };
}
state => {
tracing::warn!(
target: LOG_TARGET,
protocol = %self.protocol,
?substream_id,
?state,
"invalid state for outbound substream open failure",
);
context.state = PeerState::Closed { pending_open: None };
debug_assert!(false);
}
}
}
/// Open substream to remote `peer`.
///
/// Outbound substream can opened only if the `PeerState` is `Closed`.
/// By forcing the substream to be opened only if the state is currently closed,
/// `NotificationProtocol` can enfore more predictable state transitions.
///
/// Other states either imply an invalid state transition ([`PeerState::Open`]) or that an
/// inbound substream has already been received and its currently being validated by the user.
async fn on_open_substream(&mut self, peer: PeerId) -> crate::Result<()> {
tracing::trace!(target: LOG_TARGET, ?peer, protocol = %self.protocol, "open substream");
let Some(context) = self.peers.get_mut(&peer) else {
if !self.should_dial {
tracing::debug!(
target: LOG_TARGET,
?peer,
protocol = %self.protocol,
"connection to peer not open and dialing disabled",
);
self.event_handle
.report_notification_stream_open_failure(peer, NotificationError::DialFailure)
.await;
return Ok(());
}
match self.service.dial(&peer) {
Err(error) => {
tracing::debug!(
target: LOG_TARGET,
?peer,
protocol = %self.protocol,
?error,
"failed to dial peer",
);
self.event_handle
.report_notification_stream_open_failure(
peer,
NotificationError::DialFailure,
)
.await;
return Err(error.into());
}
Ok(()) => {
tracing::trace!(
target: LOG_TARGET,
?peer,
protocol = %self.protocol,
"started to dial peer",
);
self.peers.insert(
peer,
PeerContext {
state: PeerState::Dialing,
},
);
return Ok(());
}
}
};
match context.state {
// protocol can only request a new outbound substream to be opened if the state is
// `Closed` other states imply that it's already open
PeerState::Closed {
pending_open: Some(substream_id),
} => {
tracing::trace!(
target: LOG_TARGET,
?peer,
protocol = %self.protocol,
?substream_id,
"outbound substream opening, reusing pending open substream",
);
self.pending_outbound.insert(substream_id, peer);
context.state = PeerState::OutboundInitiated {
substream: substream_id,
};
}
PeerState::Closed { .. } => match self.service.open_substream(peer) {
Ok(substream_id) => {
tracing::trace!(
target: LOG_TARGET,
?peer,
protocol = %self.protocol,
?substream_id,