-
Notifications
You must be signed in to change notification settings - Fork 878
/
tests.rs
5341 lines (4643 loc) · 182 KB
/
tests.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 2020 Sigma Prime Pty Ltd.
//
// 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.
// Collection of tests for the gossipsub network behaviour
mod tests {
use byteorder::{BigEndian, ByteOrder};
use std::thread::sleep;
use std::time::Duration;
use async_std::net::Ipv4Addr;
use rand::Rng;
use crate::{
GossipsubConfig, GossipsubConfigBuilder, GossipsubMessage, IdentTopic as Topic,
TopicScoreParams,
};
use super::super::*;
use crate::error::ValidationError;
use crate::subscription_filter::WhitelistSubscriptionFilter;
use crate::transform::{DataTransform, IdentityTransform};
use crate::types::FastMessageId;
use libp2p_core::Endpoint;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
#[derive(Default, Builder, Debug)]
#[builder(default)]
struct InjectNodes<D, F>
// TODO: remove trait bound Default when this issue is fixed:
// https://github.com/colin-kiegel/rust-derive-builder/issues/93
where
D: DataTransform + Default + Clone + Send + 'static,
F: TopicSubscriptionFilter + Clone + Default + Send + 'static,
{
peer_no: usize,
topics: Vec<String>,
to_subscribe: bool,
gs_config: GossipsubConfig,
explicit: usize,
outbound: usize,
scoring: Option<(PeerScoreParams, PeerScoreThresholds)>,
data_transform: D,
subscription_filter: F,
}
impl<D, F> InjectNodes<D, F>
where
D: DataTransform + Default + Clone + Send + 'static,
F: TopicSubscriptionFilter + Clone + Default + Send + 'static,
{
pub fn create_network(self) -> (Gossipsub<D, F>, Vec<PeerId>, Vec<TopicHash>) {
let keypair = libp2p_core::identity::Keypair::generate_ed25519();
// create a gossipsub struct
let mut gs: Gossipsub<D, F> = Gossipsub::new_with_subscription_filter_and_transform(
MessageAuthenticity::Signed(keypair),
self.gs_config,
None,
self.subscription_filter,
self.data_transform,
)
.unwrap();
if let Some((scoring_params, scoring_thresholds)) = self.scoring {
gs.with_peer_score(scoring_params, scoring_thresholds)
.unwrap();
}
let mut topic_hashes = vec![];
// subscribe to the topics
for t in self.topics {
let topic = Topic::new(t);
gs.subscribe(&topic).unwrap();
topic_hashes.push(topic.hash().clone());
}
// build and connect peer_no random peers
let mut peers = vec![];
let empty = vec![];
for i in 0..self.peer_no {
peers.push(add_peer(
&mut gs,
if self.to_subscribe {
&topic_hashes
} else {
&empty
},
i < self.outbound,
i < self.explicit,
));
}
(gs, peers, topic_hashes)
}
}
impl<D, F> InjectNodesBuilder<D, F>
where
D: DataTransform + Default + Clone + Send + 'static,
F: TopicSubscriptionFilter + Clone + Default + Send + 'static,
{
pub fn create_network(&self) -> (Gossipsub<D, F>, Vec<PeerId>, Vec<TopicHash>) {
self.build().unwrap().create_network()
}
}
fn inject_nodes<D, F>() -> InjectNodesBuilder<D, F>
where
D: DataTransform + Default + Clone + Send + 'static,
F: TopicSubscriptionFilter + Clone + Default + Send + 'static,
{
InjectNodesBuilder::default()
}
fn inject_nodes1() -> InjectNodesBuilder<IdentityTransform, AllowAllSubscriptionFilter> {
inject_nodes()
}
// helper functions for testing
fn add_peer<D, F>(
gs: &mut Gossipsub<D, F>,
topic_hashes: &Vec<TopicHash>,
outbound: bool,
explicit: bool,
) -> PeerId
where
D: DataTransform + Default + Clone + Send + 'static,
F: TopicSubscriptionFilter + Clone + Default + Send + 'static,
{
add_peer_with_addr(gs, topic_hashes, outbound, explicit, Multiaddr::empty())
}
fn add_peer_with_addr<D, F>(
gs: &mut Gossipsub<D, F>,
topic_hashes: &Vec<TopicHash>,
outbound: bool,
explicit: bool,
address: Multiaddr,
) -> PeerId
where
D: DataTransform + Default + Clone + Send + 'static,
F: TopicSubscriptionFilter + Clone + Default + Send + 'static,
{
add_peer_with_addr_and_kind(
gs,
topic_hashes,
outbound,
explicit,
address,
Some(PeerKind::Gossipsubv1_1),
)
}
fn add_peer_with_addr_and_kind<D, F>(
gs: &mut Gossipsub<D, F>,
topic_hashes: &Vec<TopicHash>,
outbound: bool,
explicit: bool,
address: Multiaddr,
kind: Option<PeerKind>,
) -> PeerId
where
D: DataTransform + Default + Clone + Send + 'static,
F: TopicSubscriptionFilter + Clone + Default + Send + 'static,
{
let peer = PeerId::random();
//peers.push(peer.clone());
gs.inject_connection_established(
&peer,
&ConnectionId::new(0),
&if outbound {
ConnectedPoint::Dialer {
address,
role_override: Endpoint::Dialer,
}
} else {
ConnectedPoint::Listener {
local_addr: Multiaddr::empty(),
send_back_addr: address,
}
},
None,
);
<Gossipsub<D, F> as NetworkBehaviour>::inject_connected(gs, &peer);
if let Some(kind) = kind {
gs.inject_event(
peer.clone(),
ConnectionId::new(1),
HandlerEvent::PeerKind(kind),
);
}
if explicit {
gs.add_explicit_peer(&peer);
}
if !topic_hashes.is_empty() {
gs.handle_received_subscriptions(
&topic_hashes
.iter()
.cloned()
.map(|t| GossipsubSubscription {
action: GossipsubSubscriptionAction::Subscribe,
topic_hash: t,
})
.collect::<Vec<_>>(),
&peer,
);
}
peer
}
// Converts a protobuf message into a gossipsub message for reading the Gossipsub event queue.
fn proto_to_message(rpc: &crate::rpc_proto::Rpc) -> GossipsubRpc {
// Store valid messages.
let mut messages = Vec::with_capacity(rpc.publish.len());
let rpc = rpc.clone();
for message in rpc.publish.into_iter() {
messages.push(RawGossipsubMessage {
source: message.from.map(|x| PeerId::from_bytes(&x).unwrap()),
data: message.data.unwrap_or_default(),
sequence_number: message.seqno.map(|x| BigEndian::read_u64(&x)), // don't inform the application
topic: TopicHash::from_raw(message.topic),
signature: message.signature, // don't inform the application
key: None,
validated: false,
});
}
let mut control_msgs = Vec::new();
if let Some(rpc_control) = rpc.control {
// Collect the gossipsub control messages
let ihave_msgs: Vec<GossipsubControlAction> = rpc_control
.ihave
.into_iter()
.map(|ihave| GossipsubControlAction::IHave {
topic_hash: TopicHash::from_raw(ihave.topic_id.unwrap_or_default()),
message_ids: ihave
.message_ids
.into_iter()
.map(MessageId::from)
.collect::<Vec<_>>(),
})
.collect();
let iwant_msgs: Vec<GossipsubControlAction> = rpc_control
.iwant
.into_iter()
.map(|iwant| GossipsubControlAction::IWant {
message_ids: iwant
.message_ids
.into_iter()
.map(MessageId::from)
.collect::<Vec<_>>(),
})
.collect();
let graft_msgs: Vec<GossipsubControlAction> = rpc_control
.graft
.into_iter()
.map(|graft| GossipsubControlAction::Graft {
topic_hash: TopicHash::from_raw(graft.topic_id.unwrap_or_default()),
})
.collect();
let mut prune_msgs = Vec::new();
for prune in rpc_control.prune {
// filter out invalid peers
let peers = prune
.peers
.into_iter()
.filter_map(|info| {
info.peer_id
.and_then(|id| PeerId::from_bytes(&id).ok())
.map(|peer_id|
//TODO signedPeerRecord, see https://github.com/libp2p/specs/pull/217
PeerInfo {
peer_id: Some(peer_id),
})
})
.collect::<Vec<PeerInfo>>();
let topic_hash = TopicHash::from_raw(prune.topic_id.unwrap_or_default());
prune_msgs.push(GossipsubControlAction::Prune {
topic_hash,
peers,
backoff: prune.backoff,
});
}
control_msgs.extend(ihave_msgs);
control_msgs.extend(iwant_msgs);
control_msgs.extend(graft_msgs);
control_msgs.extend(prune_msgs);
}
GossipsubRpc {
messages,
subscriptions: rpc
.subscriptions
.into_iter()
.map(|sub| GossipsubSubscription {
action: if Some(true) == sub.subscribe {
GossipsubSubscriptionAction::Subscribe
} else {
GossipsubSubscriptionAction::Unsubscribe
},
topic_hash: TopicHash::from_raw(sub.topic_id.unwrap_or_default()),
})
.collect(),
control_msgs,
}
}
#[test]
/// Test local node subscribing to a topic
fn test_subscribe() {
// The node should:
// - Create an empty vector in mesh[topic]
// - Send subscription request to all peers
// - run JOIN(topic)
let subscribe_topic = vec![String::from("test_subscribe")];
let (gs, _, topic_hashes) = inject_nodes1()
.peer_no(20)
.topics(subscribe_topic)
.to_subscribe(true)
.create_network();
assert!(
gs.mesh.get(&topic_hashes[0]).is_some(),
"Subscribe should add a new entry to the mesh[topic] hashmap"
);
// collect all the subscriptions
let subscriptions =
gs.events
.iter()
.fold(vec![], |mut collected_subscriptions, e| match e {
NetworkBehaviourAction::NotifyHandler { event, .. } => match **event {
GossipsubHandlerIn::Message(ref message) => {
for s in &message.subscriptions {
match s.subscribe {
Some(true) => collected_subscriptions.push(s.clone()),
_ => {}
};
}
collected_subscriptions
}
_ => collected_subscriptions,
},
_ => collected_subscriptions,
});
// we sent a subscribe to all known peers
assert!(
subscriptions.len() == 20,
"Should send a subscription to all known peers"
);
}
#[test]
/// Test unsubscribe.
fn test_unsubscribe() {
// Unsubscribe should:
// - Remove the mesh entry for topic
// - Send UNSUBSCRIBE to all known peers
// - Call Leave
let topic_strings = vec![String::from("topic1"), String::from("topic2")];
let topics = topic_strings
.iter()
.map(|t| Topic::new(t.clone()))
.collect::<Vec<Topic>>();
// subscribe to topic_strings
let (mut gs, _, topic_hashes) = inject_nodes1()
.peer_no(20)
.topics(topic_strings)
.to_subscribe(true)
.create_network();
for topic_hash in &topic_hashes {
assert!(
gs.topic_peers.get(&topic_hash).is_some(),
"Topic_peers contain a topic entry"
);
assert!(
gs.mesh.get(&topic_hash).is_some(),
"mesh should contain a topic entry"
);
}
// unsubscribe from both topics
assert!(
gs.unsubscribe(&topics[0]).unwrap(),
"should be able to unsubscribe successfully from each topic",
);
assert!(
gs.unsubscribe(&topics[1]).unwrap(),
"should be able to unsubscribe successfully from each topic",
);
// collect all the subscriptions
let subscriptions =
gs.events
.iter()
.fold(vec![], |mut collected_subscriptions, e| match e {
NetworkBehaviourAction::NotifyHandler { event, .. } => match **event {
GossipsubHandlerIn::Message(ref message) => {
for s in &message.subscriptions {
match s.subscribe {
Some(true) => collected_subscriptions.push(s.clone()),
_ => {}
};
}
collected_subscriptions
}
_ => collected_subscriptions,
},
_ => collected_subscriptions,
});
// we sent a unsubscribe to all known peers, for two topics
assert!(
subscriptions.len() == 40,
"Should send an unsubscribe event to all known peers"
);
// check we clean up internal structures
for topic_hash in &topic_hashes {
assert!(
gs.mesh.get(&topic_hash).is_none(),
"All topics should have been removed from the mesh"
);
}
}
#[test]
/// Test JOIN(topic) functionality.
fn test_join() {
// The Join function should:
// - Remove peers from fanout[topic]
// - Add any fanout[topic] peers to the mesh (up to mesh_n)
// - Fill up to mesh_n peers from known gossipsub peers in the topic
// - Send GRAFT messages to all nodes added to the mesh
// This test is not an isolated unit test, rather it uses higher level,
// subscribe/unsubscribe to perform the test.
let topic_strings = vec![String::from("topic1"), String::from("topic2")];
let topics = topic_strings
.iter()
.map(|t| Topic::new(t.clone()))
.collect::<Vec<Topic>>();
let (mut gs, _, topic_hashes) = inject_nodes1()
.peer_no(20)
.topics(topic_strings)
.to_subscribe(true)
.create_network();
// unsubscribe, then call join to invoke functionality
assert!(
gs.unsubscribe(&topics[0]).unwrap(),
"should be able to unsubscribe successfully"
);
assert!(
gs.unsubscribe(&topics[1]).unwrap(),
"should be able to unsubscribe successfully"
);
// re-subscribe - there should be peers associated with the topic
assert!(
gs.subscribe(&topics[0]).unwrap(),
"should be able to subscribe successfully"
);
// should have added mesh_n nodes to the mesh
assert!(
gs.mesh.get(&topic_hashes[0]).unwrap().len() == 6,
"Should have added 6 nodes to the mesh"
);
fn collect_grafts(
mut collected_grafts: Vec<GossipsubControlAction>,
(_, controls): (&PeerId, &Vec<GossipsubControlAction>),
) -> Vec<GossipsubControlAction> {
for c in controls.iter() {
match c {
GossipsubControlAction::Graft { topic_hash: _ } => {
collected_grafts.push(c.clone())
}
_ => {}
}
}
collected_grafts
}
// there should be mesh_n GRAFT messages.
let graft_messages = gs.control_pool.iter().fold(vec![], collect_grafts);
assert_eq!(
graft_messages.len(),
6,
"There should be 6 grafts messages sent to peers"
);
// verify fanout nodes
// add 3 random peers to the fanout[topic1]
gs.fanout
.insert(topic_hashes[1].clone(), Default::default());
let new_peers: Vec<PeerId> = vec![];
for _ in 0..3 {
let random_peer = PeerId::random();
// inform the behaviour of a new peer
gs.inject_connection_established(
&random_peer,
&ConnectionId::new(1),
&ConnectedPoint::Dialer {
address: "/ip4/127.0.0.1".parse::<Multiaddr>().unwrap(),
role_override: Endpoint::Dialer,
},
None,
);
gs.inject_connected(&random_peer);
// add the new peer to the fanout
let fanout_peers = gs.fanout.get_mut(&topic_hashes[1]).unwrap();
fanout_peers.insert(random_peer);
}
// subscribe to topic1
gs.subscribe(&topics[1]).unwrap();
// the three new peers should have been added, along with 3 more from the pool.
assert!(
gs.mesh.get(&topic_hashes[1]).unwrap().len() == 6,
"Should have added 6 nodes to the mesh"
);
let mesh_peers = gs.mesh.get(&topic_hashes[1]).unwrap();
for new_peer in new_peers {
assert!(
mesh_peers.contains(&new_peer),
"Fanout peer should be included in the mesh"
);
}
// there should now be 12 graft messages to be sent
let graft_messages = gs.control_pool.iter().fold(vec![], collect_grafts);
assert!(
graft_messages.len() == 12,
"There should be 12 grafts messages sent to peers"
);
}
/// Test local node publish to subscribed topic
#[test]
fn test_publish_without_flood_publishing() {
// node should:
// - Send publish message to all peers
// - Insert message into gs.mcache and gs.received
//turn off flood publish to test old behaviour
let config = GossipsubConfigBuilder::default()
.flood_publish(false)
.build()
.unwrap();
let publish_topic = String::from("test_publish");
let (mut gs, _, topic_hashes) = inject_nodes1()
.peer_no(20)
.topics(vec![publish_topic.clone()])
.to_subscribe(true)
.gs_config(config)
.create_network();
assert!(
gs.mesh.get(&topic_hashes[0]).is_some(),
"Subscribe should add a new entry to the mesh[topic] hashmap"
);
// all peers should be subscribed to the topic
assert_eq!(
gs.topic_peers.get(&topic_hashes[0]).map(|p| p.len()),
Some(20),
"Peers should be subscribed to the topic"
);
// publish on topic
let publish_data = vec![0; 42];
gs.publish(Topic::new(publish_topic), publish_data).unwrap();
// Collect all publish messages
let publishes = gs
.events
.iter()
.fold(vec![], |mut collected_publish, e| match e {
NetworkBehaviourAction::NotifyHandler { event, .. } => match **event {
GossipsubHandlerIn::Message(ref message) => {
let event = proto_to_message(&message);
for s in &event.messages {
collected_publish.push(s.clone());
}
collected_publish
}
_ => collected_publish,
},
_ => collected_publish,
});
// Transform the inbound message
let message = &gs
.data_transform
.inbound_transform(
publishes
.first()
.expect("Should contain > 0 entries")
.clone(),
)
.unwrap();
let msg_id = gs.config.message_id(&message);
let config: GossipsubConfig = GossipsubConfig::default();
assert_eq!(
publishes.len(),
config.mesh_n_low(),
"Should send a publish message to all known peers"
);
assert!(
gs.mcache.get(&msg_id).is_some(),
"Message cache should contain published message"
);
}
/// Test local node publish to unsubscribed topic
#[test]
fn test_fanout() {
// node should:
// - Populate fanout peers
// - Send publish message to fanout peers
// - Insert message into gs.mcache and gs.received
//turn off flood publish to test fanout behaviour
let config = GossipsubConfigBuilder::default()
.flood_publish(false)
.build()
.unwrap();
let fanout_topic = String::from("test_fanout");
let (mut gs, _, topic_hashes) = inject_nodes1()
.peer_no(20)
.topics(vec![fanout_topic.clone()])
.to_subscribe(true)
.gs_config(config)
.create_network();
assert!(
gs.mesh.get(&topic_hashes[0]).is_some(),
"Subscribe should add a new entry to the mesh[topic] hashmap"
);
// Unsubscribe from topic
assert!(
gs.unsubscribe(&Topic::new(fanout_topic.clone())).unwrap(),
"should be able to unsubscribe successfully from topic"
);
// Publish on unsubscribed topic
let publish_data = vec![0; 42];
gs.publish(Topic::new(fanout_topic.clone()), publish_data)
.unwrap();
assert_eq!(
gs.fanout
.get(&TopicHash::from_raw(fanout_topic.clone()))
.unwrap()
.len(),
gs.config.mesh_n(),
"Fanout should contain `mesh_n` peers for fanout topic"
);
// Collect all publish messages
let publishes = gs
.events
.iter()
.fold(vec![], |mut collected_publish, e| match e {
NetworkBehaviourAction::NotifyHandler { event, .. } => match **event {
GossipsubHandlerIn::Message(ref message) => {
let event = proto_to_message(&message);
for s in &event.messages {
collected_publish.push(s.clone());
}
collected_publish
}
_ => collected_publish,
},
_ => collected_publish,
});
// Transform the inbound message
let message = &gs
.data_transform
.inbound_transform(
publishes
.first()
.expect("Should contain > 0 entries")
.clone(),
)
.unwrap();
let msg_id = gs.config.message_id(&message);
assert_eq!(
publishes.len(),
gs.config.mesh_n(),
"Should send a publish message to `mesh_n` fanout peers"
);
assert!(
gs.mcache.get(&msg_id).is_some(),
"Message cache should contain published message"
);
}
#[test]
/// Test the gossipsub NetworkBehaviour peer connection logic.
fn test_inject_connected() {
let (gs, peers, topic_hashes) = inject_nodes1()
.peer_no(20)
.topics(vec![String::from("topic1"), String::from("topic2")])
.to_subscribe(true)
.create_network();
// check that our subscriptions are sent to each of the peers
// collect all the SendEvents
let send_events: Vec<_> = gs
.events
.iter()
.filter(|e| match e {
NetworkBehaviourAction::NotifyHandler { event, .. } => {
if let GossipsubHandlerIn::Message(ref m) = **event {
!m.subscriptions.is_empty()
} else {
false
}
}
_ => false,
})
.collect();
// check that there are two subscriptions sent to each peer
for sevent in send_events.clone() {
match sevent {
NetworkBehaviourAction::NotifyHandler { event, .. } => {
if let GossipsubHandlerIn::Message(ref m) = **event {
assert!(
m.subscriptions.len() == 2,
"There should be two subscriptions sent to each peer (1 for each topic)."
);
}
}
_ => {}
};
}
// check that there are 20 send events created
assert!(
send_events.len() == 20,
"There should be a subscription event sent to each peer."
);
// should add the new peers to `peer_topics` with an empty vec as a gossipsub node
for peer in peers {
let known_topics = gs.peer_topics.get(&peer).unwrap();
assert!(
known_topics == &topic_hashes.iter().cloned().collect(),
"The topics for each node should all topics"
);
}
}
#[test]
/// Test subscription handling
fn test_handle_received_subscriptions() {
// For every subscription:
// SUBSCRIBE: - Add subscribed topic to peer_topics for peer.
// - Add peer to topics_peer.
// UNSUBSCRIBE - Remove topic from peer_topics for peer.
// - Remove peer from topic_peers.
let topics = vec!["topic1", "topic2", "topic3", "topic4"]
.iter()
.map(|&t| String::from(t))
.collect();
let (mut gs, peers, topic_hashes) = inject_nodes1()
.peer_no(20)
.topics(topics)
.to_subscribe(false)
.create_network();
// The first peer sends 3 subscriptions and 1 unsubscription
let mut subscriptions = topic_hashes[..3]
.iter()
.map(|topic_hash| GossipsubSubscription {
action: GossipsubSubscriptionAction::Subscribe,
topic_hash: topic_hash.clone(),
})
.collect::<Vec<GossipsubSubscription>>();
subscriptions.push(GossipsubSubscription {
action: GossipsubSubscriptionAction::Unsubscribe,
topic_hash: topic_hashes[topic_hashes.len() - 1].clone(),
});
let unknown_peer = PeerId::random();
// process the subscriptions
// first and second peers send subscriptions
gs.handle_received_subscriptions(&subscriptions, &peers[0]);
gs.handle_received_subscriptions(&subscriptions, &peers[1]);
// unknown peer sends the same subscriptions
gs.handle_received_subscriptions(&subscriptions, &unknown_peer);
// verify the result
let peer_topics = gs.peer_topics.get(&peers[0]).unwrap().clone();
assert!(
peer_topics == topic_hashes.iter().take(3).cloned().collect(),
"First peer should be subscribed to three topics"
);
let peer_topics = gs.peer_topics.get(&peers[1]).unwrap().clone();
assert!(
peer_topics == topic_hashes.iter().take(3).cloned().collect(),
"Second peer should be subscribed to three topics"
);
assert!(
gs.peer_topics.get(&unknown_peer).is_none(),
"Unknown peer should not have been added"
);
for topic_hash in topic_hashes[..3].iter() {
let topic_peers = gs.topic_peers.get(topic_hash).unwrap().clone();
assert!(
topic_peers == peers[..2].into_iter().cloned().collect(),
"Two peers should be added to the first three topics"
);
}
// Peer 0 unsubscribes from the first topic
gs.handle_received_subscriptions(
&vec![GossipsubSubscription {
action: GossipsubSubscriptionAction::Unsubscribe,
topic_hash: topic_hashes[0].clone(),
}],
&peers[0],
);
let peer_topics = gs.peer_topics.get(&peers[0]).unwrap().clone();
assert!(
peer_topics == topic_hashes[1..3].into_iter().cloned().collect(),
"Peer should be subscribed to two topics"
);
let topic_peers = gs.topic_peers.get(&topic_hashes[0]).unwrap().clone(); // only gossipsub at the moment
assert!(
topic_peers == peers[1..2].into_iter().cloned().collect(),
"Only the second peers should be in the first topic"
);
}
#[test]
/// Test Gossipsub.get_random_peers() function
fn test_get_random_peers() {
// generate a default GossipsubConfig
let gs_config = GossipsubConfigBuilder::default()
.validation_mode(ValidationMode::Anonymous)
.build()
.unwrap();
// create a gossipsub struct
let mut gs: Gossipsub = Gossipsub::new(MessageAuthenticity::Anonymous, gs_config).unwrap();
// create a topic and fill it with some peers
let topic_hash = Topic::new("Test").hash().clone();
let mut peers = vec![];
for _ in 0..20 {
peers.push(PeerId::random())
}
gs.topic_peers
.insert(topic_hash.clone(), peers.iter().cloned().collect());
gs.connected_peers = peers
.iter()
.map(|p| {
(
p.clone(),
PeerConnections {
kind: PeerKind::Gossipsubv1_1,
connections: vec![ConnectionId::new(1)],
},
)
})
.collect();
let random_peers =
get_random_peers(&gs.topic_peers, &gs.connected_peers, &topic_hash, 5, |_| {
true
});
assert_eq!(random_peers.len(), 5, "Expected 5 peers to be returned");
let random_peers = get_random_peers(
&gs.topic_peers,
&gs.connected_peers,
&topic_hash,
30,
|_| true,
);
assert!(random_peers.len() == 20, "Expected 20 peers to be returned");
assert!(
random_peers == peers.iter().cloned().collect(),
"Expected no shuffling"
);
let random_peers = get_random_peers(
&gs.topic_peers,
&gs.connected_peers,
&topic_hash,
20,
|_| true,
);
assert!(random_peers.len() == 20, "Expected 20 peers to be returned");
assert!(
random_peers == peers.iter().cloned().collect(),
"Expected no shuffling"
);
let random_peers =
get_random_peers(&gs.topic_peers, &gs.connected_peers, &topic_hash, 0, |_| {
true
});
assert!(random_peers.len() == 0, "Expected 0 peers to be returned");
// test the filter
let random_peers =
get_random_peers(&gs.topic_peers, &gs.connected_peers, &topic_hash, 5, |_| {
false
});
assert!(random_peers.len() == 0, "Expected 0 peers to be returned");
let random_peers =
get_random_peers(&gs.topic_peers, &gs.connected_peers, &topic_hash, 10, {
|peer| peers.contains(peer)
});
assert!(random_peers.len() == 10, "Expected 10 peers to be returned");
}
/// Tests that the correct message is sent when a peer asks for a message in our cache.
#[test]
fn test_handle_iwant_msg_cached() {
let (mut gs, peers, _) = inject_nodes1()
.peer_no(20)
.topics(Vec::new())
.to_subscribe(true)
.create_network();
let raw_message = RawGossipsubMessage {
source: Some(peers[11].clone()),
data: vec![1, 2, 3, 4],
sequence_number: Some(1u64),
topic: TopicHash::from_raw("topic"),
signature: None,
key: None,
validated: true,
};
// Transform the inbound message
let message = &gs
.data_transform
.inbound_transform(raw_message.clone())
.unwrap();
let msg_id = gs.config.message_id(&message);