-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
p2p_service.rs
1696 lines (1491 loc) · 64.5 KB
/
p2p_service.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
use crate::{
behavior::{
FuelBehaviour,
FuelBehaviourEvent,
},
codecs::{
postcard::PostcardCodec,
GossipsubCodec,
},
config::{
build_transport_function,
Config,
},
gossipsub::{
messages::{
GossipsubBroadcastRequest,
GossipsubMessage as FuelGossipsubMessage,
},
topics::GossipsubTopics,
},
heartbeat,
peer_manager::{
PeerManager,
Punisher,
},
peer_report::PeerReportEvent,
request_response::messages::{
RequestError,
RequestMessage,
ResponseChannelItem,
ResponseMessage,
ResponseSendError,
},
TryPeerId,
};
use fuel_core_metrics::p2p_metrics::p2p_metrics;
use fuel_core_types::{
fuel_types::BlockHeight,
services::p2p::peer_reputation::AppScore,
};
use futures::prelude::*;
use libp2p::{
gossipsub::{
self,
MessageAcceptance,
MessageId,
PublishError,
TopicHash,
},
identify,
multiaddr::Protocol,
request_response::{
self,
InboundRequestId,
OutboundRequestId,
ResponseChannel,
},
swarm::SwarmEvent,
Multiaddr,
PeerId,
Swarm,
SwarmBuilder,
};
use rand::seq::IteratorRandom;
use std::{
collections::HashMap,
time::Duration,
};
use tracing::{
debug,
warn,
};
/// Maximum amount of peer's addresses that we are ready to store per peer
const MAX_IDENTIFY_ADDRESSES: usize = 10;
impl Punisher for Swarm<FuelBehaviour> {
fn ban_peer(&mut self, peer_id: PeerId) {
self.behaviour_mut().block_peer(peer_id)
}
}
/// Listens to the events on the p2p network
/// And forwards them to the Orchestrator
pub struct FuelP2PService {
/// Store the local peer id
pub local_peer_id: PeerId,
/// IP address for Swarm to listen on
local_address: std::net::IpAddr,
/// The TCP port that Swarm listens on
tcp_port: u16,
/// Swarm handler for FuelBehaviour
swarm: Swarm<FuelBehaviour>,
/// Holds the Sender(s) part of the Oneshot Channel from the NetworkOrchestrator
/// Once the ResponseMessage is received from the p2p Network
/// It will send it to the NetworkOrchestrator via its unique Sender
outbound_requests_table: HashMap<OutboundRequestId, ResponseChannelItem>,
/// Holds the ResponseChannel(s) for the inbound requests from the p2p Network
/// Once the Response is prepared by the NetworkOrchestrator
/// It will send it to the specified Peer via its unique ResponseChannel
inbound_requests_table: HashMap<InboundRequestId, ResponseChannel<ResponseMessage>>,
/// NetworkCodec used as `<GossipsubCodec>` for encoding and decoding of Gossipsub messages
network_codec: PostcardCodec,
/// Stores additional p2p network info
network_metadata: NetworkMetadata,
/// Whether or not metrics collection is enabled
metrics: bool,
/// Holds peers' information, and manages existing connections
peer_manager: PeerManager,
}
#[derive(Debug)]
struct GossipsubData {
topics: GossipsubTopics,
}
impl GossipsubData {
pub fn with_topics(topics: GossipsubTopics) -> Self {
Self { topics }
}
}
/// Holds additional Network data for FuelBehavior
#[derive(Debug)]
struct NetworkMetadata {
gossipsub_data: GossipsubData,
}
#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum FuelP2PEvent {
GossipsubMessage {
peer_id: PeerId,
message_id: MessageId,
topic_hash: TopicHash,
message: FuelGossipsubMessage,
},
InboundRequestMessage {
request_id: InboundRequestId,
request_message: RequestMessage,
},
PeerConnected(PeerId),
PeerDisconnected(PeerId),
PeerInfoUpdated {
peer_id: PeerId,
block_height: BlockHeight,
},
}
impl FuelP2PService {
pub fn new(config: Config, codec: PostcardCodec) -> Self {
let gossipsub_data =
GossipsubData::with_topics(GossipsubTopics::new(&config.network_name));
let network_metadata = NetworkMetadata { gossipsub_data };
// configure and build P2P Service
let (transport_function, connection_state) = build_transport_function(&config);
let behaviour = FuelBehaviour::new(&config, codec.clone());
let mut swarm = SwarmBuilder::with_existing_identity(config.keypair.clone())
.with_tokio()
.with_other_transport(transport_function)
.unwrap()
.with_behaviour(|_| behaviour)
.unwrap()
.with_swarm_config(|cfg| {
if let Some(timeout) = config.connection_idle_timeout {
cfg.with_idle_connection_timeout(timeout)
} else {
cfg
}
})
.build();
let local_peer_id = swarm.local_peer_id().to_owned();
let metrics = config.metrics;
if let Some(public_address) = config.public_address.clone() {
swarm.add_external_address(public_address);
}
let reserved_peers = config
.reserved_nodes
.iter()
.filter_map(|m| m.try_to_peer_id())
.collect();
Self {
local_peer_id,
local_address: config.address,
tcp_port: config.tcp_port,
swarm,
network_codec: codec,
outbound_requests_table: HashMap::default(),
inbound_requests_table: HashMap::default(),
network_metadata,
metrics,
peer_manager: PeerManager::new(
reserved_peers,
connection_state,
config.max_peers_connected as usize,
),
}
}
pub async fn start(&mut self) -> anyhow::Result<()> {
// set up node's address to listen on
let listen_multiaddr = {
let mut m = Multiaddr::from(self.local_address);
m.push(Protocol::Tcp(self.tcp_port));
m
};
let peer_id = self.local_peer_id;
tracing::info!(
"The p2p service starts on the `{listen_multiaddr}` with `{peer_id}`"
);
// start listening at the given address
self.swarm.listen_on(listen_multiaddr)?;
// Wait for listener addresses.
tokio::time::timeout(Duration::from_secs(5), self.await_listeners_address())
.await
.map_err(|_| {
anyhow::anyhow!("P2PService should get a new address within 5 seconds")
})?;
Ok(())
}
async fn await_listeners_address(&mut self) {
loop {
if let SwarmEvent::NewListenAddr { .. } = self.swarm.select_next_some().await
{
break
}
}
}
#[cfg(feature = "test-helpers")]
pub fn multiaddrs(&self) -> Vec<Multiaddr> {
let local_peer = self.local_peer_id;
self.swarm
.listeners()
.map(|addr| {
format!("{addr}/p2p/{local_peer}")
.parse()
.expect("The format is always valid")
})
.collect()
}
pub fn get_peers_ids_iter(&self) -> impl Iterator<Item = &PeerId> {
self.peer_manager.get_peers_ids()
}
pub fn publish_message(
&mut self,
message: GossipsubBroadcastRequest,
) -> Result<MessageId, PublishError> {
let topic = self
.network_metadata
.gossipsub_data
.topics
.get_gossipsub_topic(&message);
match self.network_codec.encode(message) {
Ok(encoded_data) => self
.swarm
.behaviour_mut()
.publish_message(topic, encoded_data),
Err(e) => Err(PublishError::TransformFailed(e)),
}
}
/// Sends RequestMessage to a peer
/// If the peer is not defined it will pick one at random
/// Only returns error if no peers are connected
pub fn send_request_msg(
&mut self,
peer_id: Option<PeerId>,
message_request: RequestMessage,
channel_item: ResponseChannelItem,
) -> Result<OutboundRequestId, RequestError> {
let peer_id = match peer_id {
Some(peer_id) => peer_id,
_ => {
let peers = self.get_peers_ids_iter();
let peers_count = self.peer_manager.total_peers_connected();
if peers_count == 0 {
return Err(RequestError::NoPeersConnected)
}
let mut range = rand::thread_rng();
*peers.choose(&mut range).unwrap()
}
};
let request_id = self
.swarm
.behaviour_mut()
.send_request_msg(message_request, &peer_id);
self.outbound_requests_table
.insert(request_id, channel_item);
Ok(request_id)
}
/// Sends ResponseMessage to a peer that requested the data
pub fn send_response_msg(
&mut self,
request_id: InboundRequestId,
message: ResponseMessage,
) -> Result<(), ResponseSendError> {
let Some(channel) = self.inbound_requests_table.remove(&request_id) else {
debug!("ResponseChannel for {:?} does not exist!", request_id);
return Err(ResponseSendError::ResponseChannelDoesNotExist)
};
if self
.swarm
.behaviour_mut()
.send_response_msg(channel, message)
.is_err()
{
debug!("Failed to send ResponseMessage for {:?}", request_id);
return Err(ResponseSendError::SendingResponseFailed)
}
Ok(())
}
pub fn update_block_height(&mut self, block_height: BlockHeight) {
self.swarm.behaviour_mut().update_block_height(block_height)
}
/// The report is forwarded to gossipsub behaviour
/// If acceptance is "Rejected" the gossipsub peer score is calculated
/// And if it's below allowed threshold the peer is banned
pub fn report_message_validation_result(
&mut self,
msg_id: &MessageId,
propagation_source: PeerId,
mut acceptance: MessageAcceptance,
) {
// Even invalid transactions shouldn't affect reserved peer reputation.
if let MessageAcceptance::Reject = acceptance {
if self.peer_manager.is_reserved(&propagation_source) {
acceptance = MessageAcceptance::Ignore;
}
}
if let Some(gossip_score) = self
.swarm
.behaviour_mut()
.report_message_validation_result(msg_id, &propagation_source, acceptance)
{
self.peer_manager.handle_gossip_score_update(
propagation_source,
gossip_score,
&mut self.swarm,
);
}
}
#[cfg(test)]
pub fn get_peer_score(&self, peer_id: &PeerId) -> Option<f64> {
self.swarm.behaviour().get_peer_score(peer_id)
}
/// Report application score
/// If application peer score is below allowed threshold
/// the peer is banned
pub fn report_peer(
&mut self,
peer_id: PeerId,
app_score: AppScore,
reporting_service: &str,
) {
self.peer_manager.update_app_score(
peer_id,
app_score,
reporting_service,
&mut self.swarm,
);
}
#[tracing::instrument(skip_all,
level = "debug",
fields(
local_peer_id = %self.local_peer_id,
local_address = %self.local_address
),
ret
)]
/// Handles P2P Events.
/// Returns only events that are of interest to the Network Orchestrator.
pub async fn next_event(&mut self) -> Option<FuelP2PEvent> {
// TODO: add handling for when the stream closes and return None only when there are no
// more events to consume
let event = self.swarm.select_next_some().await;
tracing::debug!(?event);
match event {
SwarmEvent::Behaviour(fuel_behaviour) => {
self.handle_behaviour_event(fuel_behaviour)
}
SwarmEvent::NewListenAddr { address, .. } => {
tracing::info!("Listening for p2p traffic on `{address}`");
None
}
SwarmEvent::ListenerClosed {
addresses, reason, ..
} => {
tracing::info!(
"p2p listener(s) `{addresses:?}` closed with `{reason:?}`"
);
None
}
_ => None,
}
}
pub fn peer_manager(&self) -> &PeerManager {
&self.peer_manager
}
fn handle_behaviour_event(
&mut self,
event: FuelBehaviourEvent,
) -> Option<FuelP2PEvent> {
match event {
FuelBehaviourEvent::Gossipsub(event) => self.handle_gossipsub_event(event),
FuelBehaviourEvent::PeerReport(event) => self.handle_peer_report_event(event),
FuelBehaviourEvent::RequestResponse(event) => {
self.handle_request_response_event(event)
}
FuelBehaviourEvent::Identify(event) => self.handle_identify_event(event),
FuelBehaviourEvent::Heartbeat(event) => self.handle_heartbeat_event(event),
_ => None,
}
}
fn handle_gossipsub_event(
&mut self,
event: gossipsub::Event,
) -> Option<FuelP2PEvent> {
if let gossipsub::Event::Message {
propagation_source,
message,
message_id,
} = event
{
if let Some(correct_topic) = self
.network_metadata
.gossipsub_data
.topics
.get_gossipsub_tag(&message.topic)
{
match self.network_codec.decode(&message.data, correct_topic) {
Ok(decoded_message) => {
return Some(FuelP2PEvent::GossipsubMessage {
peer_id: propagation_source,
message_id,
topic_hash: message.topic,
message: decoded_message,
})
}
Err(err) => {
warn!(target: "fuel-p2p", "Failed to decode a message. ID: {}, Message: {:?} with error: {:?}", message_id, &message.data, err);
self.report_message_validation_result(
&message_id,
propagation_source,
MessageAcceptance::Reject,
);
}
}
} else {
warn!(target: "fuel-p2p", "GossipTopicTag does not exist for {:?}", &message.topic);
}
}
None
}
fn handle_peer_report_event(
&mut self,
event: PeerReportEvent,
) -> Option<FuelP2PEvent> {
match event {
PeerReportEvent::PerformDecay => {
self.peer_manager.batch_update_score_with_decay()
}
PeerReportEvent::CheckReservedNodesHealth => {
let disconnected_peers: Vec<_> = self
.peer_manager
.get_disconnected_reserved_peers()
.copied()
.collect();
for peer_id in disconnected_peers {
debug!(target: "fuel-p2p", "Trying to reconnect to reserved peer {:?}", peer_id);
let _ = self.swarm.dial(peer_id);
}
}
PeerReportEvent::PeerConnected {
peer_id,
initial_connection,
} => {
if self
.peer_manager
.handle_peer_connected(&peer_id, initial_connection)
{
let _ = self.swarm.disconnect_peer_id(peer_id);
} else if initial_connection {
return Some(FuelP2PEvent::PeerConnected(peer_id))
}
}
PeerReportEvent::PeerDisconnected { peer_id } => {
if self.peer_manager.handle_peer_disconnect(peer_id) {
let _ = self.swarm.dial(peer_id);
}
return Some(FuelP2PEvent::PeerDisconnected(peer_id))
}
}
None
}
fn handle_request_response_event(
&mut self,
event: request_response::Event<RequestMessage, ResponseMessage>,
) -> Option<FuelP2PEvent> {
match event {
request_response::Event::Message { peer, message } => match message {
request_response::Message::Request {
request,
channel,
request_id,
} => {
self.inbound_requests_table.insert(request_id, channel);
return Some(FuelP2PEvent::InboundRequestMessage {
request_id,
request_message: request,
})
}
request_response::Message::Response {
request_id,
response,
} => {
let Some(channel) = self.outbound_requests_table.remove(&request_id)
else {
debug!("Send channel not found for {:?}", request_id);
return None;
};
let send_ok = match (channel, response) {
(
ResponseChannelItem::Block(channel),
ResponseMessage::Block(block),
) => channel.send(block).is_ok(),
(
ResponseChannelItem::Transactions(channel),
ResponseMessage::Transactions(transactions),
) => channel.send(transactions).is_ok(),
(
ResponseChannelItem::SealedHeaders(channel),
ResponseMessage::SealedHeaders(headers),
) => channel.send((peer, headers)).is_ok(),
(_, _) => {
tracing::error!(
"Mismatching request and response channel types"
);
return None;
}
};
if !send_ok {
debug!("Failed to send through the channel for {:?}", request_id);
}
}
},
request_response::Event::InboundFailure {
peer,
error,
request_id,
} => {
tracing::error!("RequestResponse inbound error for peer: {:?} with id: {:?} and error: {:?}", peer, request_id, error);
}
request_response::Event::OutboundFailure {
peer,
error,
request_id,
} => {
tracing::error!("RequestResponse outbound error for peer: {:?} with id: {:?} and error: {:?}", peer, request_id, error);
let _ = self.outbound_requests_table.remove(&request_id);
}
_ => {}
}
None
}
fn handle_identify_event(&mut self, event: identify::Event) -> Option<FuelP2PEvent> {
match event {
identify::Event::Received { peer_id, info } => {
if self.metrics {
p2p_metrics().unique_peers.inc();
}
let mut addresses = info.listen_addrs;
let agent_version = info.agent_version;
if addresses.len() > MAX_IDENTIFY_ADDRESSES {
let protocol_version = info.protocol_version;
debug!(
target: "fuel-p2p",
"Node {:?} has reported more than {} addresses; it is identified by {:?} and {:?}",
peer_id, MAX_IDENTIFY_ADDRESSES, protocol_version, agent_version
);
addresses.truncate(MAX_IDENTIFY_ADDRESSES);
}
self.peer_manager.handle_peer_identified(
&peer_id,
addresses.clone(),
agent_version,
);
self.swarm
.behaviour_mut()
.add_addresses_to_discovery(&peer_id, addresses);
}
identify::Event::Sent { .. } => {}
identify::Event::Pushed { .. } => {}
identify::Event::Error { peer_id, error } => {
debug!(target: "fuel-p2p", "Identification with peer {:?} failed => {}", peer_id, error);
}
}
None
}
fn handle_heartbeat_event(
&mut self,
event: heartbeat::Event,
) -> Option<FuelP2PEvent> {
let heartbeat::Event {
peer_id,
latest_block_height,
} = event;
self.peer_manager
.handle_peer_info_updated(&peer_id, latest_block_height);
Some(FuelP2PEvent::PeerInfoUpdated {
peer_id,
block_height: latest_block_height,
})
}
}
#[allow(clippy::cast_possible_truncation)]
#[cfg(test)]
mod tests {
use super::{
FuelP2PService,
PublishError,
};
use crate::{
codecs::postcard::PostcardCodec,
config::Config,
gossipsub::{
messages::{
GossipsubBroadcastRequest,
GossipsubMessage,
},
topics::{
GossipTopic,
NEW_TX_GOSSIP_TOPIC,
},
},
p2p_service::FuelP2PEvent,
peer_manager::PeerInfo,
request_response::messages::{
RequestMessage,
ResponseChannelItem,
ResponseMessage,
},
service::to_message_acceptance,
};
use fuel_core_types::{
blockchain::{
block::Block,
consensus::{
poa::PoAConsensus,
Consensus,
},
header::{
BlockHeader,
PartialBlockHeader,
},
SealedBlock,
SealedBlockHeader,
},
fuel_tx::{
Transaction,
TransactionBuilder,
},
services::p2p::{
GossipsubMessageAcceptance,
Transactions,
},
};
use futures::{
future::join_all,
StreamExt,
};
use libp2p::{
gossipsub::Topic,
identity::Keypair,
swarm::{
ListenError,
SwarmEvent,
},
Multiaddr,
PeerId,
};
use rand::Rng;
use std::{
collections::HashSet,
ops::Range,
sync::Arc,
time::Duration,
};
use tokio::sync::{
mpsc,
oneshot,
watch,
};
use tracing_attributes::instrument;
type P2PService = FuelP2PService;
/// helper function for building FuelP2PService
async fn build_service_from_config(mut p2p_config: Config) -> P2PService {
p2p_config.keypair = Keypair::generate_secp256k1(); // change keypair for each Node
let max_block_size = p2p_config.max_block_size;
let mut service =
FuelP2PService::new(p2p_config, PostcardCodec::new(max_block_size));
service.start().await.unwrap();
service
}
async fn setup_bootstrap_nodes(
p2p_config: &Config,
bootstrap_nodes_count: usize,
) -> (Vec<P2PService>, Vec<Multiaddr>) {
let nodes = join_all(
(0..bootstrap_nodes_count)
.map(|_| build_service_from_config(p2p_config.clone())),
)
.await;
let bootstrap_multiaddrs = nodes
.iter()
.flat_map(|b| b.multiaddrs())
.collect::<Vec<_>>();
(nodes, bootstrap_multiaddrs)
}
fn spawn(stop: &watch::Sender<()>, mut node: P2PService) {
let mut stop = stop.subscribe();
tokio::spawn(async move {
loop {
tokio::select! {
_ = node.next_event() => {}
_ = stop.changed() => {
break;
}
}
}
});
}
#[tokio::test]
#[instrument]
async fn p2p_service_works() {
build_service_from_config(Config::default_initialized("p2p_service_works")).await;
}
// Single sentry node connects to multiple reserved nodes and `max_peers_allowed` amount of non-reserved nodes.
// It also tries to dial extra non-reserved nodes to establish the connection.
// A single reserved node is not started immediately with the rest of the nodes.
// Once sentry node establishes the connection with the allowed number of nodes
// we start the reserved node, and await for it to establish the connection.
// This test proves that there is always an available slot for the reserved node to connect to.
#[tokio::test(flavor = "multi_thread")]
#[instrument]
async fn reserved_nodes_reconnect_works() {
let p2p_config = Config::default_initialized("reserved_nodes_reconnect_works");
// total amount will be `max_peers_allowed` + `reserved_nodes.len()`
let max_peers_allowed: usize = 3;
let (bootstrap_nodes, bootstrap_multiaddrs) =
setup_bootstrap_nodes(&p2p_config, max_peers_allowed.saturating_mul(5)).await;
let (mut reserved_nodes, reserved_multiaddrs) =
setup_bootstrap_nodes(&p2p_config, max_peers_allowed).await;
let mut sentry_node = {
let mut p2p_config = p2p_config.clone();
p2p_config.max_peers_connected = max_peers_allowed as u32;
p2p_config.bootstrap_nodes = bootstrap_multiaddrs;
p2p_config.reserved_nodes = reserved_multiaddrs;
build_service_from_config(p2p_config).await
};
// pop() a single reserved node, so it's not run with the rest of the nodes
let mut reserved_node = reserved_nodes.pop();
let reserved_node_peer_id = reserved_node.as_ref().unwrap().local_peer_id;
let all_node_services: Vec<_> = bootstrap_nodes
.into_iter()
.chain(reserved_nodes.into_iter())
.collect();
let mut all_nodes_ids: Vec<PeerId> = all_node_services
.iter()
.map(|service| service.local_peer_id)
.collect();
let (stop_sender, _) = watch::channel(());
all_node_services.into_iter().for_each(|node| {
spawn(&stop_sender, node);
});
loop {
tokio::select! {
sentry_node_event = sentry_node.next_event() => {
// we've connected to all other peers
if sentry_node.peer_manager.total_peers_connected() > max_peers_allowed {
// if the `reserved_node` is not included,
// create and insert it, to be polled with rest of the nodes
if !all_nodes_ids
.iter()
.any(|local_peer_id| local_peer_id == &reserved_node_peer_id) {
if let Some(node) = reserved_node {
all_nodes_ids.push(node.local_peer_id);
spawn(&stop_sender, node);
reserved_node = None;
}
}
}
if let Some(FuelP2PEvent::PeerConnected(peer_id)) = sentry_node_event {
// we connected to the desired reserved node
if peer_id == reserved_node_peer_id {
break
}
}
},
}
}
stop_sender.send(()).unwrap();
}
// We start with two nodes, node_a and node_b, bootstrapped with `bootstrap_nodes_count` other nodes.
// Yet node_a and node_b are only allowed to connect to specified amount of nodes.
#[tokio::test]
#[instrument]
async fn max_peers_connected_works() {
let p2p_config = Config::default_initialized("max_peers_connected_works");
let bootstrap_nodes_count = 20;
let node_a_max_peers_allowed: usize = 3;
let node_b_max_peers_allowed: usize = 5;
let (mut nodes, nodes_multiaddrs) =
setup_bootstrap_nodes(&p2p_config, bootstrap_nodes_count).await;
// this node is allowed to only connect to `node_a_max_peers_allowed` other nodes
let mut node_a = {
let mut p2p_config = p2p_config.clone();
p2p_config.max_peers_connected = node_a_max_peers_allowed as u32;
// it still tries to dial all nodes!
p2p_config.bootstrap_nodes = nodes_multiaddrs.clone();
build_service_from_config(p2p_config).await
};
// this node is allowed to only connect to `node_b_max_peers_allowed` other nodes
let mut node_b = {
let mut p2p_config = p2p_config.clone();
p2p_config.max_peers_connected = node_b_max_peers_allowed as u32;
// it still tries to dial all nodes!
p2p_config.bootstrap_nodes = nodes_multiaddrs.clone();
build_service_from_config(p2p_config).await
};
let (tx, mut rx) = tokio::sync::oneshot::channel::<()>();
let jh = tokio::spawn(async move {
while rx.try_recv().is_err() {
futures::stream::iter(nodes.iter_mut())
.for_each_concurrent(4, |node| async move {
node.next_event().await;
})
.await;
}
});
let mut node_a_hit_limit = false;
let mut node_b_hit_limit = false;
let mut instance = tokio::time::Instant::now();
// After we hit limit for node_a and node_b start timer.
// If we don't exceed the limit during 5 seconds, finish the test successfully.
while instance.elapsed().as_secs() < 5 {
tokio::select! {
event_from_node_a = node_a.next_event() => {
if let Some(FuelP2PEvent::PeerConnected(_)) = event_from_node_a {
if node_a.peer_manager().total_peers_connected() > node_a_max_peers_allowed {
panic!("The node should only connect to max {node_a_max_peers_allowed} peers");
}
node_a_hit_limit |= node_a.peer_manager().total_peers_connected() == node_a_max_peers_allowed;
}
tracing::info!("Event from the node_a: {:?}", event_from_node_a);
},
event_from_node_b = node_b.next_event() => {
if let Some(FuelP2PEvent::PeerConnected(_)) = event_from_node_b {
if node_b.peer_manager().total_peers_connected() > node_b_max_peers_allowed {
panic!("The node should only connect to max {node_b_max_peers_allowed} peers");
}
node_b_hit_limit |= node_b.peer_manager().total_peers_connected() == node_b_max_peers_allowed;
}
tracing::info!("Event from the node_b: {:?}", event_from_node_b);
},
}
if !(node_a_hit_limit && node_b_hit_limit) {
instance = tokio::time::Instant::now();
}
}
tx.send(()).unwrap();
jh.await.unwrap()
}
// Simulate 2 Sets of Sentry nodes.
// In both Sets, a single Guarded Node should only be connected to their sentry nodes.
// While other nodes can and should connect to nodes outside of the Sentry Set.
#[tokio::test(flavor = "multi_thread")]
#[instrument]
async fn sentry_nodes_working() {
const RESERVED_NODE_SIZE: usize = 4;
let mut p2p_config = Config::default_initialized("sentry_nodes_working");
async fn build_sentry_nodes(p2p_config: Config) -> (P2PService, Vec<P2PService>) {
let (reserved_nodes, reserved_multiaddrs) =
setup_bootstrap_nodes(&p2p_config, RESERVED_NODE_SIZE).await;
// set up the guraded node service with `reserved_nodes_only_mode`
let guarded_node_service = {
let mut p2p_config = p2p_config.clone();
p2p_config.reserved_nodes = reserved_multiaddrs;
p2p_config.reserved_nodes_only_mode = true;
build_service_from_config(p2p_config).await
};
let sentry_nodes = reserved_nodes;
(guarded_node_service, sentry_nodes)
}
let (mut first_guarded_node, mut first_sentry_nodes) =
build_sentry_nodes(p2p_config.clone()).await;
p2p_config.bootstrap_nodes = first_sentry_nodes
.iter()
.flat_map(|n| n.multiaddrs())
.collect();
let (mut second_guarded_node, second_sentry_nodes) =
build_sentry_nodes(p2p_config).await;
let mut first_sentry_set: HashSet<_> = first_sentry_nodes