-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathpeers.rs
2170 lines (1952 loc) · 90.2 KB
/
peers.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
// Smoldot
// Copyright (C) 2019-2022 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//! Network of peers.
//!
//! The [`Peers`] state machine builds on top of the [`libp2p`] module and provides an
//! abstraction over the network based on network identities (i.e. [`PeerId`]s). One can set the
//! list of peers to be connected to and through which notification protocols, and the [`Peers`]
//! struct will try to open or re-open connections with these peers. Once connected, one can use
//! the [`Peers`] to send request or notifications with these peers.
//!
//! # Detailed usage
//!
//! The [`Peers`] struct contains six different collections:
//!
//! - A list, decided by the API user, of peers that are marked as "desired".
//! - A list, decided by the API user, of `(peer_id, notification_protocol)` tuples that are
//! marked as "desired".
//! - A list of connections identified by [`ConnectionId`]s.
//! - A list of requests for inbound substreams, identified by a [`SubstreamId`]. When a peer
//! desires to open a notification substream with the local node, a [`SubstreamId`] is generated.
//! The API user must answer by either accepting or refusing the request.
//! - A list of requests that have been received, identified by a [`InRequestId`]. The API user
//! must answer by calling [`Peers::respond_in_request`]. Requests can automatically become
//! obsolete if the remote decides to withdraw their request or the connection closes. A request
//! becoming obsolete does *not* invalidate its [`InRequestId`].
//!
use crate::libp2p::{self, collection, PeerId};
use crate::util::SipHasherBuild;
use alloc::{
collections::{btree_map, BTreeMap, BTreeSet},
string::String,
vec::Vec,
};
use core::{
hash::Hash,
iter,
num::NonZeroU32,
ops::{self, Add, Sub},
time::Duration,
};
use rand::{Rng as _, SeedableRng as _};
pub use collection::{
ConfigRequestResponse, ConfigRequestResponseIn, ConnectionId, ConnectionToCoordinator,
CoordinatorToConnection, MultiStreamConnectionTask, MultiStreamHandshakeKind,
NotificationProtocolConfig, NotificationsInClosedErr, NotificationsOutErr, ReadWrite,
RequestError, SingleStreamConnectionTask, SingleStreamHandshakeKind, SubstreamId,
};
/// Configuration for a [`Peers`].
pub struct Config {
/// Seed for the randomness within the networking state machine.
pub randomness_seed: [u8; 32],
/// Capacity to initially reserve to the list of connections.
pub connections_capacity: usize,
/// Capacity to initially reserve to the list of peers.
pub peers_capacity: usize,
/// Maximum number of substreams that each remote can have simultaneously opened on each
/// connection.
///
/// If there exists multiple connections with the same remote, the limit is enforced for
/// each connection separately.
///
/// > **Note**: This limit is necessary in order to avoid DoS attacks where a remote opens too
/// > many substreams.
pub max_inbound_substreams: usize,
pub notification_protocols: Vec<NotificationProtocolConfig>,
pub request_response_protocols: Vec<ConfigRequestResponse>,
/// Name of the ping protocol on the network.
pub ping_protocol: String,
/// Amount of time after which a connection handshake is considered to have taken too long
/// and must be aborted.
pub handshake_timeout: Duration,
/// Key used for the encryption layer.
/// This is a Noise static key, according to the Noise specification.
/// Signed using the actual libp2p key.
pub noise_key: libp2p::connection::NoiseKey,
}
pub struct Peers<TConn, TNow> {
/// Underlying state machine that manages connections.
inner: collection::Network<Connection<TConn>, TNow>,
/// List of all peer identities known to the state machine.
peers: slab::Slab<Peer>,
/// For each known peer, the corresponding index within [`Peers::peers`].
///
/// We split the list of peers in two in order to avoid doing extensive hash map lookups when
/// it's not necessary.
peer_indices: hashbrown::HashMap<PeerId, usize, SipHasherBuild>,
/// List of all peers (as indices within [`Peers::peers`]) that are desired or have a substream
/// marked as desired but for which no non-shutting-down established or handshaking connection
/// exists.
unfulfilled_desired_peers: hashbrown::HashSet<usize, fnv::FnvBuildHasher>,
/// List of all established connections, as a tuple of `(peer_index, connection_id)`.
/// `peer_index` is the index in [`Peers::peers`]. Includes all connections even if they are
/// still handshaking or shutting down.
///
/// Note that incoming handshaking connections are never in this list, as their expected
/// peer id isn't known before the end of the handshake.
connections_by_peer: BTreeSet<(usize, collection::ConnectionId)>,
/// Keys are combinations of `(peer_index, notifications_protocol_index)`. Contains all the
/// inbound notification substreams that are either pending or accepted. Used in order to
/// prevent a peer from opening multiple inbound substreams.
peers_notifications_in: BTreeSet<(usize, usize)>,
/// For each inner notification protocol substream, the connection id and the
/// `notifications_protocol_index`.
///
/// This applies to both inbound and outbound notification substreams, both pending and
/// established.
// TODO: this could be a user data in `collection`
inner_notification_substreams: hashbrown::HashMap<
collection::SubstreamId,
(collection::ConnectionId, usize),
fnv::FnvBuildHasher,
>,
/// Keys are combinations of `(peer_index, notifications_protocol_index)`. Values are the
/// state of the corresponding outbound notifications substream.
peers_notifications_out: BTreeMap<(usize, usize), NotificationsOutState>,
/// Subset of [`Peers::peers_notifications_out`]. Only contains entries that are desired
/// and not open, and for which there exists a non-shutting down established connection with
/// the peer.
/// Keys are combinations of `(peer_index, notifications_protocol_index)`. Values indicate
/// whether the substream is in the `ClosedByRemote` state.
unfulfilled_desired_outbound_substreams:
hashbrown::HashMap<(usize, usize), bool, fnv::FnvBuildHasher>,
/// Subset of [`Peers::peers_notifications_out`]. Only contains entries that are not desired
/// and open or pending.
/// Keys are combinations of `(peer_index, notifications_protocol_index)`. Values are the
/// state of the corresponding outbound notifications substream.
fulfilled_undesired_outbound_substreams:
hashbrown::HashMap<(usize, usize), OpenOrPending, fnv::FnvBuildHasher>,
}
/// See [`Peers::peers_notifications_out`].
///
/// Note that the state where `desired` is `true` and `open` is `Closed` means that the remote
/// has refused or has closed the substream.
struct NotificationsOutState {
desired: bool,
open: NotificationsOutOpenState,
}
enum NotificationsOutOpenState {
NotOpen,
ClosedByRemote,
Opening(collection::SubstreamId),
Open(collection::SubstreamId),
}
/// See [`Peers::peers`]
struct Peer {
peer_id: PeerId,
desired: bool,
}
struct Connection<TConn> {
/// Index in [`Peers::peers`] of the peer this connection is connected to.
///
/// - If the handshake is finished, contains the actual peer.
/// - If the handshake is in progress and the connection is outbound, contains the *expected*
/// peer, which might not be the same as the actual.
/// - If the handshake is in progress and the connection is inbound, contains `None`.
peer_index: Option<usize>,
/// `true` if the connection is outgoing.
outbound: bool,
/// Opaque data decided by the API user.
user_data: TConn,
}
impl<TConn, TNow> Peers<TConn, TNow>
where
TConn: Clone,
TNow: Clone + Add<Duration, Output = TNow> + Sub<TNow, Output = Duration> + Ord,
{
/// Creates a new [`Peers`].
pub fn new(config: Config) -> Self {
let mut randomness = rand_chacha::ChaCha20Rng::from_seed(config.randomness_seed);
Peers {
inner_notification_substreams: hashbrown::HashMap::with_capacity_and_hasher(
config.notification_protocols.len() * config.peers_capacity,
Default::default(),
),
inner: collection::Network::new(collection::Config {
capacity: config.connections_capacity,
noise_key: config.noise_key,
max_inbound_substreams: config.max_inbound_substreams,
notification_protocols: config.notification_protocols,
request_response_protocols: config.request_response_protocols,
ping_protocol: config.ping_protocol,
handshake_timeout: config.handshake_timeout,
randomness_seed: randomness.sample(rand::distributions::Standard),
}),
connections_by_peer: BTreeSet::new(),
peer_indices: hashbrown::HashMap::with_capacity_and_hasher(
config.peers_capacity,
SipHasherBuild::new(randomness.sample(rand::distributions::Standard)),
),
peers: slab::Slab::with_capacity(config.peers_capacity),
unfulfilled_desired_peers: hashbrown::HashSet::with_capacity_and_hasher(
config.peers_capacity,
Default::default(),
),
peers_notifications_out: BTreeMap::new(),
unfulfilled_desired_outbound_substreams: hashbrown::HashMap::with_capacity_and_hasher(
config.peers_capacity,
Default::default(),
),
fulfilled_undesired_outbound_substreams: hashbrown::HashMap::with_capacity_and_hasher(
config.peers_capacity,
Default::default(),
),
peers_notifications_in: BTreeSet::new(),
}
}
/// Returns the list the overlay networks originally passed as
/// [`Config::notification_protocols`].
pub fn notification_protocols(
&self,
) -> impl ExactSizeIterator<Item = &NotificationProtocolConfig> {
self.inner.notification_protocols()
}
/// Returns the list the request-response protocols originally passed as
/// [`Config::request_response_protocols`].
pub fn request_response_protocols(
&self,
) -> impl ExactSizeIterator<Item = &ConfigRequestResponse> {
self.inner.request_response_protocols()
}
/// Returns the Noise key originally passed as [`Config::noise_key`].
pub fn noise_key(&self) -> &libp2p::connection::NoiseKey {
self.inner.noise_key()
}
/// Pulls a message that must be sent to a connection.
///
/// The message must be passed to [`SingleStreamConnectionTask::inject_coordinator_message`]
/// or [`MultiStreamConnectionTask::inject_coordinator_message`] in the appropriate connection.
///
/// This function guarantees that the [`ConnectionId`] always refers to a connection that
/// is still alive, in the sense that [`SingleStreamConnectionTask::inject_coordinator_message`]
/// or [`MultiStreamConnectionTask::inject_coordinator_message`] has never returned `None`.
pub fn pull_message_to_connection(
&mut self,
) -> Option<(ConnectionId, CoordinatorToConnection<TNow>)> {
self.inner.pull_message_to_connection()
}
/// Injects into the state machine a message generated by
/// [`SingleStreamConnectionTask::pull_message_to_coordinator`] or
/// [`MultiStreamConnectionTask::pull_message_to_coordinator`].
///
/// This message is queued and is later processed in [`Peers::next_event`]. This means that
/// it is [`Peers::next_event`] and not [`Peers::inject_connection_message`] that updates
/// the internals of the state machine according to the content of the message. For example,
/// if a [`SingleStreamConnectionTask`] sends a message to the coordinator indicating that a
/// notifications substream has been closed, the coordinator will still believe that it is
/// open until [`Peers::next_event`] processes this message and at the same time returns a
/// corresponding [`Event`]. Processing messages directly in
/// [`Peers::inject_connection_message`] would introduce "race conditions" where the API user
/// can't be sure in which state a connection or a substream is.
pub fn inject_connection_message(
&mut self,
connection_id: ConnectionId,
message: ConnectionToCoordinator,
) {
self.inner.inject_connection_message(connection_id, message)
}
/// Returns the next event produced by the service.
pub fn next_event(&mut self) -> Option<Event<TConn>> {
loop {
let event = match self.inner.next_event() {
Some(ev) => ev,
None => return None,
};
match event {
collection::Event::HandshakeFinished {
id: connection_id,
peer_id,
} => {
let actual_peer_index = self.peer_index_or_insert(&peer_id);
let peer_id = self.peers[actual_peer_index].peer_id.clone();
let expected_peer_id = if let Some(expected_peer_index) =
self.inner[connection_id].peer_index
{
debug_assert!(!self
.unfulfilled_desired_peers
.contains(&expected_peer_index));
if expected_peer_index != actual_peer_index {
let _was_in = self
.connections_by_peer
.remove(&(expected_peer_index, connection_id));
debug_assert!(_was_in);
let _inserted = self
.connections_by_peer
.insert((actual_peer_index, connection_id));
debug_assert!(_inserted);
self.inner[connection_id].peer_index = Some(actual_peer_index);
self.unfulfilled_desired_peers.remove(&actual_peer_index);
// We might have to insert the expected peer back in
// `unfulfilled_desired_peers` if it is desired.
if (self.peers[expected_peer_index].desired
|| self
.peers_notifications_out
.range(
(expected_peer_index, usize::min_value())
..=(expected_peer_index, usize::max_value()),
)
.any(|(_, state)| state.desired))
&& !self
.connections_by_peer
.range(
(expected_peer_index, ConnectionId::min_value())
..=(expected_peer_index, ConnectionId::max_value()),
)
.map(|(_, connection_id)| *connection_id)
.any(|connection_id| {
!self.inner.connection_state(connection_id).shutting_down
})
{
self.unfulfilled_desired_peers.insert(expected_peer_index);
}
}
Some(self.peers[actual_peer_index].peer_id.clone())
} else {
let _inserted = self
.connections_by_peer
.insert((actual_peer_index, connection_id));
debug_assert!(_inserted);
self.inner[connection_id].peer_index = Some(actual_peer_index);
self.unfulfilled_desired_peers.remove(&actual_peer_index);
None
};
for ((_, notifications_protocol_index), state) in self
.peers_notifications_out
.range(
(actual_peer_index, usize::min_value())
..=(actual_peer_index, usize::max_value()),
)
.filter(|(_, state)| {
state.desired
&& matches!(
state.open,
NotificationsOutOpenState::NotOpen
| NotificationsOutOpenState::ClosedByRemote
)
})
{
let _prev_value = self.unfulfilled_desired_outbound_substreams.insert(
(actual_peer_index, *notifications_protocol_index),
match state.open {
NotificationsOutOpenState::NotOpen => false,
NotificationsOutOpenState::ClosedByRemote => true,
_ => unreachable!(),
},
);
debug_assert!(_prev_value.is_none());
}
let num_healthy_peer_connections = {
let num = self
.connections_by_peer
.range(
(actual_peer_index, collection::ConnectionId::min_value())
..=(actual_peer_index, collection::ConnectionId::max_value()),
)
.filter(|(_, connection_id)| {
let state = self.inner.connection_state(*connection_id);
state.established && !state.shutting_down
})
.count();
NonZeroU32::new(u32::try_from(num).unwrap()).unwrap()
};
return Some(Event::HandshakeFinished {
connection_id,
num_healthy_peer_connections,
peer_id,
expected_peer_id,
});
}
collection::Event::StartShutdown { id, .. }
| collection::Event::PingOutFailed { id } => {
// We react to ougoing ping failures by shutting down the connection. For this
// reason, a shutdown initiated by the remote and an outgoing ping failure
// share almost the same code.
let reason = match event {
collection::Event::StartShutdown { reason, .. } => {
ShutdownCause::Connection(reason)
}
collection::Event::PingOutFailed { .. } => {
// A `PingOutFailed` doesn't by itself cause a disconnect. The reason
// why it's handled the same way as `StartShutdown` is because we
// voluntarily call `start_shutdown` here.
self.inner.start_shutdown(id);
ShutdownCause::OutPingTimeout
}
_ => unreachable!(),
};
let connection_state = self.inner.connection_state(id);
debug_assert!(connection_state.shutting_down);
let peer = if let Some(peer_index) = self.inner[id].peer_index {
let peer_id = self.peers[peer_index].peer_id.clone();
// We might have to insert the peer back in `unfulfilled_desired_peers` if
// it is desired.
if (self.peers[peer_index].desired
|| self
.peers_notifications_out
.range(
(peer_index, usize::min_value())
..=(peer_index, usize::max_value()),
)
.any(|(_, state)| state.desired))
&& !self
.connections_by_peer
.range(
(peer_index, ConnectionId::min_value())
..=(peer_index, ConnectionId::max_value()),
)
.map(|(_, connection_id)| *connection_id)
.any(|connection_id| {
!self.inner.connection_state(connection_id).shutting_down
})
{
self.unfulfilled_desired_peers.insert(peer_index);
}
if connection_state.established {
let num_healthy_peer_connections = {
let num = self
.connections_by_peer
.range(
(peer_index, collection::ConnectionId::min_value())
..=(peer_index, collection::ConnectionId::max_value()),
)
.filter(|(_, connection_id)| {
let state = self.inner.connection_state(*connection_id);
state.established && !state.shutting_down
})
.count();
u32::try_from(num).unwrap()
};
if num_healthy_peer_connections == 0 {
for ((_, notifications_protocol_index), _) in self
.peers_notifications_out
.range(
(peer_index, usize::min_value())
..=(peer_index, usize::max_value()),
)
.filter(|(_, state)| {
state.desired
&& matches!(
state.open,
NotificationsOutOpenState::NotOpen
| NotificationsOutOpenState::ClosedByRemote
)
})
{
let _was_in = self
.unfulfilled_desired_outbound_substreams
.remove(&(peer_index, *notifications_protocol_index));
debug_assert!(_was_in.is_some());
}
}
ShutdownPeer::Established {
peer_id,
num_healthy_peer_connections,
}
} else {
ShutdownPeer::OutgoingHandshake {
expected_peer_id: peer_id,
}
}
} else {
debug_assert!(!connection_state.established);
ShutdownPeer::IngoingHandshake
};
return Some(Event::StartShutdown {
connection_id: id,
peer,
reason,
});
}
collection::Event::Shutdown {
id: connection_id,
was_established,
user_data:
Connection {
peer_index: Some(expected_peer_index),
user_data,
..
},
} => {
// `expected_peer_index` is `None` iff the connection was an incoming
// connection whose handshake isn't finished yet.
let _was_in = self
.connections_by_peer
.remove(&(expected_peer_index, connection_id));
debug_assert!(_was_in);
let peer_id = self.peers[expected_peer_index].peer_id.clone();
let num_healthy_peer_connections = {
let num = self
.connections_by_peer
.range(
(expected_peer_index, collection::ConnectionId::min_value())
..=(expected_peer_index, collection::ConnectionId::max_value()),
)
.filter(|(_, connection_id)| {
let state = self.inner.connection_state(*connection_id);
state.established && !state.shutting_down
})
.count();
u32::try_from(num).unwrap()
};
self.try_clean_up_peer(expected_peer_index);
return Some(Event::Shutdown {
connection_id,
peer: if was_established {
ShutdownPeer::Established {
num_healthy_peer_connections,
peer_id,
}
} else {
ShutdownPeer::OutgoingHandshake {
expected_peer_id: peer_id,
}
},
user_data,
});
}
collection::Event::Shutdown {
id: connection_id,
user_data:
Connection {
peer_index: None,
user_data,
outbound,
..
},
..
} => {
// Connection was incoming but its handshake wasn't finished yet.
debug_assert!(!outbound);
return Some(Event::Shutdown {
connection_id,
peer: ShutdownPeer::IngoingHandshake,
user_data,
});
}
collection::Event::InboundError {
id: connection_id,
error,
} => {
let peer_id = {
let peer_index = self.inner[connection_id].peer_index.unwrap();
self.peers[peer_index].peer_id.clone()
};
return Some(Event::InboundError {
peer_id,
connection_id,
error: InboundError::Connection(error),
});
}
collection::Event::Response {
substream_id,
response,
} => {
return Some(Event::Response {
request_id: OutRequestId(substream_id),
response,
});
}
collection::Event::RequestIn {
id: connection_id,
substream_id,
protocol_index,
request_payload,
} => {
let peer_id = {
// Incoming requests can only happen if the connection is no longer
// handshaking, in which case `peer_index` is guaranteed to be `Some`.
let peer_index = self.inner[connection_id].peer_index.unwrap();
self.peers[peer_index].peer_id.clone()
};
return Some(Event::RequestIn {
peer_id,
connection_id,
protocol_index,
request_id: InRequestId(substream_id),
request_payload,
});
}
collection::Event::RequestInCancel { substream_id } => {
return Some(Event::RequestInCancel {
id: InRequestId(substream_id),
})
}
collection::Event::NotificationsOutResult {
substream_id,
result,
} => {
let (connection_id, notifications_protocol_index) = *self
.inner_notification_substreams
.get(&substream_id)
.unwrap();
let peer_index = self.inner[connection_id].peer_index.unwrap();
let notification_out = self
.peers_notifications_out
.get_mut(&(peer_index, notifications_protocol_index))
.unwrap();
let desired = notification_out.desired;
debug_assert!(matches!(
notification_out.open,
NotificationsOutOpenState::Opening(_)
));
if result.is_ok() {
notification_out.open = NotificationsOutOpenState::Open(substream_id);
} else {
notification_out.open = NotificationsOutOpenState::ClosedByRemote;
self.inner_notification_substreams
.remove(&substream_id)
.unwrap();
// Update the map entries.
if !desired {
self.peers_notifications_out
.remove(&(peer_index, notifications_protocol_index));
debug_assert!(!self
.unfulfilled_desired_outbound_substreams
.contains_key(&(peer_index, notifications_protocol_index)));
let _was_in = self
.fulfilled_undesired_outbound_substreams
.remove(&(peer_index, notifications_protocol_index));
debug_assert!(matches!(_was_in, Some(OpenOrPending::Pending)));
} else {
if self
.connections_by_peer
.range(
(peer_index, ConnectionId::min_value())
..=(peer_index, ConnectionId::max_value()),
)
.any(|(_, connection_id)| {
let state = self.inner.connection_state(*connection_id);
state.established && !state.shutting_down
})
{
let _prev_value = self
.unfulfilled_desired_outbound_substreams
.insert((peer_index, notifications_protocol_index), true);
debug_assert!(_prev_value.is_none());
}
debug_assert!(!self
.fulfilled_undesired_outbound_substreams
.contains_key(&(peer_index, notifications_protocol_index)));
}
}
return Some(Event::NotificationsOutResult {
peer_id: self.peers[peer_index].peer_id.clone(),
notifications_protocol_index,
result,
});
}
collection::Event::NotificationsOutCloseDemanded { substream_id }
| collection::Event::NotificationsOutReset { substream_id } => {
// If the remote asks the substream to be closed, we immediately respond
// accordingly without asking the higher level user. This is an opinionated
// decision that could be changed in the future.
if let collection::Event::NotificationsOutCloseDemanded { .. } = event {
self.inner.close_out_notifications(substream_id);
}
let (connection_id, notifications_protocol_index) = self
.inner_notification_substreams
.remove(&substream_id)
.unwrap();
let peer_index = self.inner[connection_id].peer_index.unwrap();
let notification_out = self
.peers_notifications_out
.get_mut(&(peer_index, notifications_protocol_index))
.unwrap();
debug_assert!(matches!(
notification_out.open,
NotificationsOutOpenState::Open(_)
));
notification_out.open = NotificationsOutOpenState::ClosedByRemote;
// Update the maps.
if !notification_out.desired {
self.peers_notifications_out
.remove(&(peer_index, notifications_protocol_index));
debug_assert!(!self
.unfulfilled_desired_outbound_substreams
.contains_key(&(peer_index, notifications_protocol_index)));
let _was_in = self
.fulfilled_undesired_outbound_substreams
.remove(&(peer_index, notifications_protocol_index));
debug_assert!(matches!(_was_in, Some(OpenOrPending::Open)));
} else {
if self
.connections_by_peer
.range(
(peer_index, ConnectionId::min_value())
..=(peer_index, ConnectionId::max_value()),
)
.any(|(_, connection_id)| {
let state = self.inner.connection_state(*connection_id);
state.established && !state.shutting_down
})
{
let _prev_value = self
.unfulfilled_desired_outbound_substreams
.insert((peer_index, notifications_protocol_index), true);
debug_assert!(_prev_value.is_none());
}
debug_assert!(!self
.fulfilled_undesired_outbound_substreams
.contains_key(&(peer_index, notifications_protocol_index)));
}
return Some(Event::NotificationsOutClose {
peer_id: self.peers[peer_index].peer_id.clone(),
notifications_protocol_index,
});
}
collection::Event::NotificationsInOpen {
id: connection_id,
substream_id,
notifications_protocol_index,
remote_handshake: handshake,
..
} => {
// Incoming substreams can only happen if the connection is no longer
// handshaking, in which case `peer_index` is guaranteed to be `Some`.
let peer_index = self.inner[connection_id].peer_index.unwrap();
// If this peer has already opened an inbound notifications substream in the
// past, forbid any additional one.
if !self
.peers_notifications_in
.insert((peer_index, notifications_protocol_index))
{
self.inner.reject_in_notifications(substream_id);
return Some(Event::InboundError {
connection_id,
peer_id: self.peers[peer_index].peer_id.clone(),
error: InboundError::DuplicateNotificationsSubstream {
notifications_protocol_index,
},
});
}
let _was_in = self
.inner_notification_substreams
.insert(substream_id, (connection_id, notifications_protocol_index));
debug_assert!(_was_in.is_none());
return Some(Event::NotificationsInOpen {
id: substream_id,
peer_id: self.peers[peer_index].peer_id.clone(),
notifications_protocol_index,
handshake,
});
}
collection::Event::NotificationsIn {
substream_id,
notification,
} => {
let (connection_id, notifications_protocol_index) = *self
.inner_notification_substreams
.get(&substream_id)
.unwrap();
let peer_id = {
// Incoming notifications can only happen if the connection is no longer
// handshaking, in which case `peer_index` is guaranteed to be `Some`.
let peer_index = self.inner[connection_id].peer_index.unwrap();
self.peers[peer_index].peer_id.clone()
};
return Some(Event::NotificationsIn {
peer_id,
notifications_protocol_index,
notification,
});
}
collection::Event::NotificationsInOpenCancel { substream_id } => {
let (connection_id, notifications_protocol_index) = self
.inner_notification_substreams
.remove(&substream_id)
.unwrap();
let peer_index = {
// Incoming substreams can only happen if the connection is no longer
// handshaking, in which case `peer_index` is guaranteed to be `Some`.
self.inner[connection_id].peer_index.unwrap()
};
let _was_in = self
.peers_notifications_in
.remove(&(peer_index, notifications_protocol_index));
assert!(_was_in);
return Some(Event::NotificationsInOpenCancel { id: substream_id });
}
collection::Event::NotificationsInClose {
substream_id,
outcome,
} => {
let (connection_id, notifications_protocol_index) = self
.inner_notification_substreams
.remove(&substream_id)
.unwrap();
let peer_index = {
// Incoming substreams can only happen if the connection is no longer
// handshaking, in which case `peer_index` is guaranteed to be `Some`.
self.inner[connection_id].peer_index.unwrap()
};
let _was_in = self
.peers_notifications_in
.remove(&(peer_index, notifications_protocol_index));
assert!(_was_in);
return Some(Event::NotificationsInClose {
peer_id: self.peers[peer_index].peer_id.clone(),
notifications_protocol_index,
outcome,
});
}
collection::Event::PingOutSuccess { .. } => {
// We don't care about or report successful pings at the moment.
}
}
}
}
/// Inserts a single-stream incoming connection in the state machine.
///
/// This connection hasn't finished handshaking and the [`PeerId`] of the remote isn't known
/// yet.
///
/// Must be passed the moment (as a `TNow`) when the connection as been established, in order
/// to determine when the handshake timeout expires.
pub fn add_single_stream_incoming_connection(
&mut self,
when_connected: TNow,
handshake_kind: SingleStreamHandshakeKind,
user_data: TConn,
) -> (ConnectionId, SingleStreamConnectionTask<TNow>) {
self.inner.insert_single_stream(
when_connected,
handshake_kind,
false,
Connection {
peer_index: None,
user_data,
outbound: false,
},
)
}
/// Inserts a single-stream outgoing connection in the state machine.
///
/// This connection hasn't finished handshaking, and the [`PeerId`] of the remote isn't known
/// yet, but it is expected to be in `unfulfilled_desired_peers`. After this function has been
/// called, the provided `expected_peer_id` will no longer be part of the return value of
/// [`Peers::unfulfilled_desired_peers`].
///
/// Must be passed the moment (as a `TNow`) when the connection as been established, in order
/// to determine when the handshake timeout expires.
pub fn add_single_stream_outgoing_connection(
&mut self,
when_connected: TNow,
handshake_kind: SingleStreamHandshakeKind,
expected_peer_id: &PeerId,
user_data: TConn,
) -> (ConnectionId, SingleStreamConnectionTask<TNow>) {
let peer_index = self.peer_index_or_insert(expected_peer_id);
self.unfulfilled_desired_peers.remove(&peer_index);
let (connection_id, connection_task) = self.inner.insert_single_stream(
when_connected,
handshake_kind,
true,
Connection {
peer_index: Some(peer_index),
user_data,
outbound: true,
},
);
let _inserted = self.connections_by_peer.insert((peer_index, connection_id));
debug_assert!(_inserted);
(connection_id, connection_task)
}
/// Inserts a multi-stream outgoing connection in the state machine.
///
/// This connection hasn't finished handshaking, and the [`PeerId`] of the remote isn't known
/// yet, but it is expected to be in `unfulfilled_desired_peers`. After this function has been
/// called, the provided `expected_peer_id` will no longer be part of the return value of
/// [`Peers::unfulfilled_desired_peers`].
///
/// Must be passed the moment (as a `TNow`) when the connection as been established, in order
/// to determine when the handshake timeout expires.
pub fn add_multi_stream_outgoing_connection<TSubId>(
&mut self,
when_connected: TNow,
handshake_kind: MultiStreamHandshakeKind,
expected_peer_id: &PeerId,
user_data: TConn,
) -> (ConnectionId, MultiStreamConnectionTask<TNow, TSubId>)
where
TSubId: Clone + PartialEq + Eq + Hash,
{
let peer_index = self.peer_index_or_insert(expected_peer_id);