-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathgossip_acceptor.rs
4218 lines (3889 loc) · 169 KB
/
gossip_acceptor.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 (c) 2019, MASQ (https://masq.ai) and/or its affiliates. All rights reserved.
use crate::neighborhood::gossip::{GossipBuilder, Gossip_0v1};
use crate::neighborhood::neighborhood_database::{NeighborhoodDatabase, NeighborhoodDatabaseError};
use crate::neighborhood::node_record::NodeRecord;
use crate::neighborhood::AccessibleGossipRecord;
use crate::sub_lib::cryptde::{CryptDE, PublicKey};
use crate::sub_lib::neighborhood::{
ConnectionProgressEvent, ConnectionProgressMessage, GossipFailure_0v1,
};
use crate::sub_lib::node_addr::NodeAddr;
use crate::sub_lib::proxy_server::DEFAULT_MINIMUM_HOP_COUNT;
use actix::Recipient;
use masq_lib::logger::Logger;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::net::{IpAddr, SocketAddr};
use std::time::{Duration, SystemTime};
/// Note: if you decide to change this, make sure you test thoroughly. Values less than 5 may lead
/// to inability to grow the network beyond a very small size; values greater than 5 may lead to
/// Gossip storms.
pub const MAX_DEGREE: usize = 5;
// In case we meet a pass target after this duration, we would treat
// pass target as if we met it for the first time.
const PASS_GOSSIP_EXPIRED_TIME: Duration = Duration::from_secs(60);
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum GossipAcceptanceResult {
// The incoming Gossip produced database changes. Generate standard Gossip and broadcast.
Accepted,
// Don't generate Gossip from the database: instead, send this Gossip to the provided key and NodeAddr.
Reply(Gossip_0v1, PublicKey, NodeAddr),
// The incoming Gossip was proper, and we tried to accept it, but couldn't.
Failed(GossipFailure_0v1, PublicKey, NodeAddr),
// The incoming Gossip contained nothing we didn't know. Don't send out any Gossip because of it.
Ignored,
// Gossip was ignored because it was evil: ban the sender of the Gossip as a malefactor.
Ban(String),
}
#[derive(Clone, PartialEq, Eq, Debug)]
enum Qualification {
Matched,
Unmatched,
Malformed(String),
}
trait NamedType {
fn type_name(&self) -> &'static str;
}
trait GossipHandler: NamedType + Send /* Send because lazily-written tests require it */ {
fn qualifies(
&self,
database: &NeighborhoodDatabase,
agrs: &[AccessibleGossipRecord],
gossip_source: SocketAddr,
) -> Qualification;
fn handle(
&self,
cryptde: &dyn CryptDE,
database: &mut NeighborhoodDatabase,
agrs: Vec<AccessibleGossipRecord>,
gossip_source: SocketAddr,
connection_progress_peers: &[IpAddr],
cpm_recipient: &Recipient<ConnectionProgressMessage>,
) -> GossipAcceptanceResult;
}
struct DebutHandler {
logger: Logger,
}
impl NamedType for DebutHandler {
fn type_name(&self) -> &'static str {
"DebutHandler"
}
}
impl GossipHandler for DebutHandler {
// A Debut must contain a single AGR; it must provide its IP address if it accepts connections;
// it must specify at least one port; it must be sourced by the debuting Node;
// and it must not already be in our database.
fn qualifies(
&self,
database: &NeighborhoodDatabase,
agrs: &[AccessibleGossipRecord],
gossip_source: SocketAddr,
) -> Qualification {
if agrs.len() != 1 {
return Qualification::Unmatched;
}
if database.node_by_key(&agrs[0].inner.public_key).is_some() {
return Qualification::Unmatched;
}
match &agrs[0].node_addr_opt {
None => {
if agrs[0].inner.accepts_connections {
Qualification::Malformed(format!(
"Debut from {} for {} contained no NodeAddr",
gossip_source, agrs[0].inner.public_key
))
} else {
Qualification::Matched
}
}
Some(node_addr) => {
if agrs[0].inner.accepts_connections {
if node_addr.ports().is_empty() {
Qualification::Malformed(format!(
"Debut from {} for {} contained NodeAddr with no ports",
gossip_source, agrs[0].inner.public_key
))
} else if node_addr.ip_addr() == gossip_source.ip() {
Qualification::Matched
} else {
Qualification::Unmatched
}
} else {
Qualification::Malformed(format!(
"Debut from {} for {} does not accept connections, yet contained NodeAddr",
gossip_source, agrs[0].inner.public_key
))
}
}
}
}
fn handle(
&self,
cryptde: &dyn CryptDE,
database: &mut NeighborhoodDatabase,
mut agrs: Vec<AccessibleGossipRecord>,
gossip_source: SocketAddr,
_connection_progress_peers: &[IpAddr],
_cpm_recipient: &Recipient<ConnectionProgressMessage>,
) -> GossipAcceptanceResult {
let source_agr = {
let mut agr = agrs.remove(0); // empty Gossip shouldn't get here
if agr.node_addr_opt.is_none() {
agr.node_addr_opt = Some(NodeAddr::from(&gossip_source));
}
agr
};
let source_key = source_agr.inner.public_key.clone();
let source_node_addr = source_agr
.node_addr_opt
.as_ref()
.expect("Source Node NodeAddr disappeared")
.clone();
if let Some(preferred_key) = self.find_more_appropriate_neighbor(database, &source_agr) {
let preferred_ip = database
.node_by_key(preferred_key)
.expect("Preferred Node disappeared")
.node_addr_opt()
.expect("Preferred Node's NodeAddr disappeared")
.ip_addr();
debug!(self.logger,
"DebutHandler is commissioning Pass of {} at {} to more appropriate neighbor {} at {}",
source_key,
gossip_source,
preferred_key,
preferred_ip,
);
return GossipAcceptanceResult::Reply(
Self::make_pass_gossip(database, preferred_key),
source_key,
source_node_addr,
);
}
if let Ok(result) = self.try_accept_debut(cryptde, database, &source_agr, gossip_source) {
return result;
}
debug!(self.logger, "Seeking neighbor for Pass");
let lcn_key = match Self::find_least_connected_half_neighbor_excluding(
database,
&source_agr,
) {
None => {
debug!(self.logger,
"Neighbor count at maximum, but no non-common neighbors. DebutHandler is reluctantly ignoring debut from {} at {}",
source_key, source_node_addr
);
return GossipAcceptanceResult::Failed(
GossipFailure_0v1::NoSuitableNeighbors,
(&source_agr.inner.public_key).clone(),
(&source_agr
.node_addr_opt
.expect("Debuter's NodeAddr disappeared"))
.clone(),
);
}
Some(key) => key,
};
let lcn_ip_str = match database
.node_by_key(lcn_key)
.expect("LCN Disappeared")
.node_addr_opt()
{
Some(node_addr) => node_addr.ip_addr().to_string(),
None => "?.?.?.?".to_string(),
};
debug!(
self.logger,
"DebutHandler is commissioning Pass of {} at {} to {} at {}",
source_key,
source_node_addr.ip_addr(),
lcn_key,
lcn_ip_str
);
GossipAcceptanceResult::Reply(
Self::make_pass_gossip(database, lcn_key),
source_key,
source_node_addr,
)
}
}
impl DebutHandler {
fn new(logger: Logger) -> DebutHandler {
DebutHandler { logger }
}
fn find_more_appropriate_neighbor<'b>(
&self,
database: &'b NeighborhoodDatabase,
excluded: &'b AccessibleGossipRecord,
) -> Option<&'b PublicKey> {
let neighbor_vec =
Self::root_full_neighbors_ordered_by_degree_excluding(database, excluded);
let qualified_neighbors: Vec<&PublicKey> = neighbor_vec
.into_iter()
.filter(|k| {
database
.node_by_key(*k)
.expect("Node disappeared")
.accepts_connections()
})
.skip_while(|k| database.gossip_target_degree(*k) <= 2)
.collect();
match qualified_neighbors.first().cloned() {
// No neighbors of degree 3 or greater
None => {
debug!(
self.logger,
"No degree-3-or-greater neighbors; can't find more-appropriate neighbor"
);
None
}
// Neighbor of degree 3 or greater, but not less connected than I am
Some(key)
if database.gossip_target_degree(key)
>= database.gossip_target_degree(database.root().public_key()) =>
{
debug!(self.logger, "No neighbors of degree 3 or greater are less-connected than this Node: can't find more-appropriate neighbor");
None
}
// Neighbor of degree 3 or greater less connected than I am
Some(key) => {
debug!(self.logger, "Found more-appropriate neighbor");
Some(key)
}
}
}
fn try_accept_debut(
&self,
cryptde: &dyn CryptDE,
database: &mut NeighborhoodDatabase,
debuting_agr: &AccessibleGossipRecord,
gossip_source: SocketAddr,
) -> Result<GossipAcceptanceResult, ()> {
if database.gossip_target_degree(database.root().public_key()) >= MAX_DEGREE {
debug!(self.logger, "Neighbor count already at maximum");
return Err(());
}
let debut_node_addr_opt = debuting_agr.node_addr_opt.clone();
let debuting_node = NodeRecord::from(debuting_agr);
let debut_node_key = database
.add_node(debuting_node)
.expect("Debuting Node suddenly appeared in database");
match database.add_half_neighbor(&debut_node_key) {
Err(NeighborhoodDatabaseError::NodeKeyNotFound(k)) => {
panic!("Node {} magically disappeared", k)
}
Err(e) => panic!(
"Unexpected error accepting debut from {}/{:?}: {:?}",
debut_node_key, debut_node_addr_opt, e
),
Ok(true) => {
let root_mut = database.root_mut();
root_mut.increment_version();
root_mut.regenerate_signed_gossip(cryptde);
trace!(self.logger, "Current database: {}", database.to_dot_graph());
if Self::should_not_make_introduction(debuting_agr) {
let ip_addr_str = match &debuting_agr.node_addr_opt {
Some(node_addr) => node_addr.ip_addr().to_string(),
None => "?.?.?.?".to_string(),
};
debug!(self.logger, "Node {} at {} is responding to first introduction: sending update Gossip instead of further introduction",
debuting_agr.inner.public_key,
ip_addr_str);
Ok(GossipAcceptanceResult::Accepted)
} else {
match self.make_introduction(database, debuting_agr, gossip_source) {
Some((introduction, target_key, target_node_addr)) => {
Ok(GossipAcceptanceResult::Reply(
introduction,
target_key,
target_node_addr,
))
}
None => {
debug!(
self.logger,
"DebutHandler can't make an introduction, but is accepting {} at {} and broadcasting change",
&debut_node_key,
gossip_source,
);
Ok(GossipAcceptanceResult::Accepted)
}
}
}
}
Ok(false) => panic!("Brand-new neighbor already existed"),
}
}
fn make_introduction(
&self,
database: &NeighborhoodDatabase,
debuting_agr: &AccessibleGossipRecord,
gossip_source: SocketAddr,
) -> Option<(Gossip_0v1, PublicKey, NodeAddr)> {
if let Some(lcn_key) =
Self::find_least_connected_full_neighbor_excluding(database, debuting_agr)
{
let lcn_node_addr_str = match database
.node_by_key(lcn_key)
.expect("LCN disappeared")
.node_addr_opt()
{
Some(node_addr) => node_addr.to_string(),
None => "?.?.?.?:?".to_string(),
};
let debut_node_addr = match &debuting_agr.node_addr_opt {
Some(node_addr) => node_addr.clone(),
None => NodeAddr::from(&gossip_source),
};
debug!(
self.logger,
"DebutHandler commissioning Introduction of {} at {} to {} at {}",
lcn_key,
lcn_node_addr_str,
&debuting_agr.inner.public_key,
debut_node_addr
);
Some((
GossipBuilder::new(database)
.node(database.root().public_key(), true)
.node(lcn_key, true)
.build(),
debuting_agr.inner.public_key.clone(),
debut_node_addr,
))
} else {
None
}
}
fn find_least_connected_half_neighbor_excluding<'b>(
database: &'b NeighborhoodDatabase,
excluded: &'b AccessibleGossipRecord,
) -> Option<&'b PublicKey> {
Self::find_least_connected_neighbor_excluding(
database.root().half_neighbor_keys(),
database,
excluded,
)
}
fn find_least_connected_full_neighbor_excluding<'b>(
database: &'b NeighborhoodDatabase,
excluded: &'b AccessibleGossipRecord,
) -> Option<&'b PublicKey> {
Self::find_least_connected_neighbor_excluding(
database
.root()
.full_neighbor_keys(database)
.into_iter()
.filter(|k| {
database
.node_by_key(*k)
.expect("Node disappeared")
.accepts_connections()
})
.collect(),
database,
excluded,
)
}
fn find_least_connected_neighbor_excluding<'b>(
keys: HashSet<&'b PublicKey>,
database: &'b NeighborhoodDatabase,
excluded: &'b AccessibleGossipRecord,
) -> Option<&'b PublicKey> {
let excluded_keys = Self::node_and_neighbor_keys(excluded);
Self::keys_ordered_by_degree_excluding(database, keys, excluded_keys)
.first()
.cloned()
}
fn keys_ordered_by_degree_excluding<'b>(
database: &'b NeighborhoodDatabase,
keys: HashSet<&'b PublicKey>,
excluding: HashSet<&'b PublicKey>,
) -> Vec<&'b PublicKey> {
let mut neighbor_keys_vec: Vec<&PublicKey> = keys.difference(&excluding).cloned().collect();
neighbor_keys_vec.sort_unstable_by(|a, b| {
database
.gossip_target_degree(*a)
.cmp(&database.gossip_target_degree(*b))
});
neighbor_keys_vec
}
fn root_full_neighbors_ordered_by_degree_excluding<'b>(
database: &'b NeighborhoodDatabase,
excluded: &'b AccessibleGossipRecord,
) -> Vec<&'b PublicKey> {
let excluded_keys = Self::node_and_neighbor_keys(excluded);
Self::keys_ordered_by_degree_excluding(
database,
database.root().full_neighbor_keys(database),
excluded_keys,
)
}
fn node_and_neighbor_keys(agr: &AccessibleGossipRecord) -> HashSet<&PublicKey> {
let mut keys = HashSet::new();
keys.insert(&agr.inner.public_key);
for key_ref in &agr.inner.neighbors {
keys.insert(key_ref);
}
keys
}
fn should_not_make_introduction(debuting_agr: &AccessibleGossipRecord) -> bool {
!debuting_agr.inner.neighbors.is_empty()
}
fn make_pass_gossip(database: &NeighborhoodDatabase, pass_target: &PublicKey) -> Gossip_0v1 {
GossipBuilder::new(database).node(pass_target, true).build()
}
}
#[derive(PartialEq, Debug)]
struct PassHandler {
// previous_pass_targets is used to stop the cycle of infinite pass gossips
// in case it receives an ip address that is already a part of this hash set.
// previous_pass_targets: HashSet<IpAddr>,
previous_pass_targets: RefCell<HashMap<IpAddr, SystemTime>>,
}
impl NamedType for PassHandler {
fn type_name(&self) -> &'static str {
"PassHandler"
}
}
impl GossipHandler for PassHandler {
// A Pass must contain a single AGR representing the pass target; it must provide its IP address;
// it must specify at least one port; and it must _not_ be sourced by the pass target.
fn qualifies(
&self,
_database: &NeighborhoodDatabase,
agrs: &[AccessibleGossipRecord],
gossip_source: SocketAddr,
) -> Qualification {
if agrs.len() != 1 {
return Qualification::Unmatched;
}
match &agrs[0].node_addr_opt {
None => Qualification::Malformed(format!(
"Pass from {} to {} did not contain NodeAddr",
gossip_source, agrs[0].inner.public_key
)),
Some(node_addr) => {
if node_addr.ports().is_empty() {
Qualification::Malformed(format!(
"Pass from {} to {} at {} contained NodeAddr with no ports",
gossip_source,
agrs[0].inner.public_key,
node_addr.ip_addr()
))
} else if node_addr.ip_addr() == gossip_source.ip() {
Qualification::Unmatched
} else {
Qualification::Matched
}
}
}
}
fn handle(
&self,
_cryptde: &dyn CryptDE,
database: &mut NeighborhoodDatabase,
agrs: Vec<AccessibleGossipRecord>,
_gossip_source: SocketAddr,
connection_progress_peers: &[IpAddr],
cpm_recipient: &Recipient<ConnectionProgressMessage>,
) -> GossipAcceptanceResult {
let pass_agr = &agrs[0]; // empty Gossip shouldn't get here
let pass_target_node_addr: NodeAddr = pass_agr
.node_addr_opt
.clone()
.expect("Pass lost its NodeAddr");
let pass_target_ip_addr = pass_target_node_addr.ip_addr();
let send_cpm = |event: ConnectionProgressEvent| {
let connection_progress_message = ConnectionProgressMessage {
peer_addr: _gossip_source.ip(),
event,
};
cpm_recipient
.try_send(connection_progress_message)
.expect("System is dead.");
};
let gossip_acceptance_reply = || {
let gossip = GossipBuilder::new(database)
.node(database.root().public_key(), true)
.build();
GossipAcceptanceResult::Reply(
gossip,
pass_agr.inner.public_key.clone(),
pass_target_node_addr,
)
};
let mut hash_map = self.previous_pass_targets.borrow_mut();
let gossip_acceptance_result = match hash_map.get_mut(&pass_target_ip_addr) {
None => match connection_progress_peers.contains(&pass_target_ip_addr) {
true => {
send_cpm(ConnectionProgressEvent::PassLoopFound);
GossipAcceptanceResult::Ignored
}
false => {
hash_map.insert(pass_target_ip_addr, SystemTime::now());
send_cpm(ConnectionProgressEvent::PassGossipReceived(
pass_target_ip_addr,
));
gossip_acceptance_reply()
}
},
Some(timestamp) => {
let duration_since = SystemTime::now()
.duration_since(*timestamp)
.expect("Failed to calculate duration for pass target timestamp.");
*timestamp = SystemTime::now();
if duration_since <= PASS_GOSSIP_EXPIRED_TIME {
send_cpm(ConnectionProgressEvent::PassLoopFound);
GossipAcceptanceResult::Ignored
} else {
send_cpm(ConnectionProgressEvent::PassGossipReceived(
pass_target_ip_addr,
));
gossip_acceptance_reply()
}
}
};
gossip_acceptance_result
}
}
impl PassHandler {
fn new() -> PassHandler {
PassHandler {
previous_pass_targets: RefCell::new(Default::default()),
}
}
}
struct IntroductionHandler {
logger: Logger,
}
impl NamedType for IntroductionHandler {
fn type_name(&self) -> &'static str {
"IntroductionHandler"
}
}
impl GossipHandler for IntroductionHandler {
// An Introduction must contain two AGRs, one representing the introducer and one representing
// the introducee. Both records must provide their IP addresses. One of the IP addresses must
// match the gossip_source. The other record's IP address must not match the gossip_source. The
// record whose IP address does not match the gossip source must not already be in the database.
fn qualifies(
&self,
database: &NeighborhoodDatabase,
agrs: &[AccessibleGossipRecord],
gossip_source: SocketAddr,
) -> Qualification {
if let Some(qual) = Self::verify_size(agrs) {
return qual;
}
let (introducer, introducee) =
match Self::order_is_introducee_introducer(agrs, gossip_source) {
Err(qual) => return qual,
Ok(true) => (&agrs[0], &agrs[1]),
Ok(false) => (&agrs[1], &agrs[0]),
};
if let Some(qual) = Self::verify_introducer(introducer, database.root()) {
return qual;
};
if let Some(qual) = Self::verify_introducee(database, introducer, introducee, gossip_source)
{
return qual;
};
Qualification::Matched
}
fn handle(
&self,
cryptde: &dyn CryptDE,
database: &mut NeighborhoodDatabase,
agrs: Vec<AccessibleGossipRecord>,
gossip_source: SocketAddr,
_connection_progress_peers: &[IpAddr],
cpm_recipient: &Recipient<ConnectionProgressMessage>,
) -> GossipAcceptanceResult {
if database.root().full_neighbor_keys(database).len() >= MAX_DEGREE {
GossipAcceptanceResult::Ignored
} else {
let (introducer, introducee) = Self::identify_players(agrs, gossip_source)
.expect("Introduction not properly qualified");
let introducer_key = introducer.inner.public_key.clone();
let introducer_ip_addr = introducer
.node_addr_opt
.as_ref()
.expect("IP Address not found for the Node Addr.")
.ip_addr();
let introducee_ip_addr = introducee
.node_addr_opt
.as_ref()
.expect("IP Address not found for the Node Addr.")
.ip_addr();
match self.update_database(database, cryptde, introducer) {
Ok(_) => (),
Err(e) => {
return GossipAcceptanceResult::Ban(format!(
"Introducer {} tried changing immutable characteristic: {}",
introducer_key, e
));
}
}
let connection_progess_message = ConnectionProgressMessage {
peer_addr: introducer_ip_addr,
event: ConnectionProgressEvent::IntroductionGossipReceived(introducee_ip_addr),
};
cpm_recipient
.try_send(connection_progess_message)
.expect("Neighborhood is dead");
let (debut, target_key, target_node_addr) =
GossipAcceptorReal::make_debut_triple(database, &introducee)
.expect("Introduction not properly qualified");
GossipAcceptanceResult::Reply(debut, target_key, target_node_addr)
}
}
}
impl IntroductionHandler {
fn new(logger: Logger) -> IntroductionHandler {
IntroductionHandler { logger }
}
fn verify_size(agrs: &[AccessibleGossipRecord]) -> Option<Qualification> {
if agrs.len() != 2 {
return Some(Qualification::Unmatched);
}
None
}
fn order_is_introducee_introducer(
agrs_ref: &[AccessibleGossipRecord],
gossip_source: SocketAddr,
) -> Result<bool, Qualification> {
let first_agr = &agrs_ref[0];
let first_ip = match first_agr.node_addr_opt.as_ref() {
None => return Err(Qualification::Unmatched),
Some(node_addr) => node_addr.ip_addr(),
};
let second_agr = &agrs_ref[1];
let second_ip = match second_agr.node_addr_opt.as_ref() {
None => return Err(Qualification::Unmatched),
Some(node_addr) => node_addr.ip_addr(),
};
if first_ip == gossip_source.ip() {
Ok(true)
} else if second_ip == gossip_source.ip() {
Ok(false)
} else {
Err(Qualification::Malformed(format!(
"In Introduction, neither {} from {} nor {} from {} claims the source IP {}",
first_agr.inner.public_key,
first_ip,
second_agr.inner.public_key,
second_ip,
gossip_source.ip()
)))
}
}
#[allow(clippy::branches_sharing_code)]
fn identify_players(
mut agrs: Vec<AccessibleGossipRecord>,
gossip_source: SocketAddr,
) -> Result<(AccessibleGossipRecord, AccessibleGossipRecord), Qualification> {
let pair = if Self::order_is_introducee_introducer(&agrs, gossip_source)? {
let introducer = agrs.remove(0);
let introducee = agrs.remove(0);
(introducer, introducee)
} else {
let introducee = agrs.remove(0);
let introducer = agrs.remove(0);
(introducer, introducee)
};
Ok(pair)
}
fn verify_introducer(
agr: &AccessibleGossipRecord,
root_node: &NodeRecord,
) -> Option<Qualification> {
if &agr.inner.public_key == root_node.public_key() {
return Some(Qualification::Malformed(format!(
"Introducer {} claims local Node's public key",
agr.inner.public_key
)));
}
let introducer_node_addr = agr.node_addr_opt.as_ref().expect("NodeAddr disappeared");
if introducer_node_addr.ports().is_empty() {
return Some(Qualification::Malformed(format!(
"Introducer {} from {} has no ports",
&agr.inner.public_key,
introducer_node_addr.ip_addr()
)));
}
if let Some(root_node_addr) = root_node.node_addr_opt() {
if introducer_node_addr.ip_addr() == root_node_addr.ip_addr() {
return Some(Qualification::Malformed(format!(
"Introducer {} claims to be at local Node's IP address",
agr.inner.public_key
)));
}
}
None
}
fn verify_introducee(
database: &NeighborhoodDatabase,
introducer: &AccessibleGossipRecord,
introducee: &AccessibleGossipRecord,
gossip_source: SocketAddr,
) -> Option<Qualification> {
if database.node_by_key(&introducee.inner.public_key).is_some() {
return Some(Qualification::Unmatched);
}
let introducee_node_addr = match introducee.node_addr_opt.as_ref() {
None => return Some(Qualification::Unmatched),
Some(node_addr) => node_addr,
};
if introducee_node_addr.ports().is_empty() {
return Some(Qualification::Malformed(format!(
"Introducer {} from {} introduced {} from {} with no ports",
&introducer.inner.public_key,
match &introducer.node_addr_opt {
Some(node_addr) => node_addr.ip_addr().to_string(),
None => "?.?.?.?".to_string(),
},
&introducee.inner.public_key,
introducee_node_addr.ip_addr()
)));
}
if introducee
.node_addr_opt
.as_ref()
.expect("Introducee NodeAddr disappeared")
.ip_addr()
== gossip_source.ip()
{
return Some(Qualification::Malformed(format!(
"Introducer {} and introducee {} both claim {}",
introducer.inner.public_key,
introducee.inner.public_key,
gossip_source.ip()
)));
}
None
}
fn update_database(
&self,
database: &mut NeighborhoodDatabase,
cryptde: &dyn CryptDE,
introducer: AccessibleGossipRecord,
) -> Result<bool, String> {
let introducer_key = introducer.inner.public_key.clone();
match database.node_by_key_mut(&introducer_key) {
Some(existing_introducer_ref) => {
if existing_introducer_ref.version() < introducer.inner.version {
debug!(
self.logger,
"Updating obsolete introducer {} from version {} to version {}",
introducer_key,
existing_introducer_ref.version(),
introducer.inner.version
);
existing_introducer_ref.update(introducer)?;
} else {
debug!(
self.logger,
"Preserving existing introducer {} at version {}",
introducer_key,
existing_introducer_ref.version()
);
return Ok(false);
}
}
None => {
let new_introducer = NodeRecord::from(introducer);
debug!(
self.logger,
"Adding introducer {} to database", introducer_key
);
database
.add_node(new_introducer)
.expect("add_node should always work here");
}
}
if database
.add_half_neighbor(&introducer_key)
.expect("introducer not in database")
{
database.root_mut().increment_version();
database.root_mut().regenerate_signed_gossip(cryptde);
}
trace!(self.logger, "Current database: {}", database.to_dot_graph());
Ok(true)
}
}
struct StandardGossipHandler {
logger: Logger,
}
impl NamedType for StandardGossipHandler {
fn type_name(&self) -> &'static str {
"StandardGossipHandler"
}
}
impl GossipHandler for StandardGossipHandler {
// Standard Gossip must not be a Debut, Pass, or Introduction. There must be no record in the
// Gossip describing the local Node (although there may be records that reference the local Node as a neighbor).
fn qualifies(
&self,
database: &NeighborhoodDatabase,
agrs: &[AccessibleGossipRecord],
gossip_source: SocketAddr,
) -> Qualification {
// must-not-be-debut-pass-or-introduction is assured by StandardGossipHandler's placement in the gossip_handlers list
let agrs_next_door = agrs
.iter()
.filter(|agr| agr.node_addr_opt.is_some())
.collect::<Vec<&AccessibleGossipRecord>>();
let root_node = database.root();
if root_node.accepts_connections() {
if let Some(impostor) = agrs_next_door.iter().find(|agr| {
Self::ip_of(agr)
== root_node
.node_addr_opt()
.expect("Root Node that accepts connections must have NodeAddr")
.ip_addr()
}) {
return Qualification::Malformed(
format!("Standard Gossip from {} contains a record claiming that {} has this Node's IP address",
gossip_source,
impostor.inner.public_key));
}
}
if agrs
.iter()
.any(|agr| &agr.inner.public_key == root_node.public_key())
{
return Qualification::Malformed(format!(
"Standard Gossip from {} contains a record with this Node's public key",
gossip_source
));
}
let init_addr_set: HashSet<IpAddr> = HashSet::new();
let init_dup_set: HashSet<IpAddr> = HashSet::new();
let dup_set = agrs_next_door
.into_iter()
.fold((init_addr_set, init_dup_set), |so_far, agr| {
let (addr_set, dup_set) = so_far;
let ip_addr = Self::ip_of(agr);
if addr_set.contains(&ip_addr) {
(addr_set, Self::add_ip_addr(dup_set, ip_addr))
} else {
(Self::add_ip_addr(addr_set, ip_addr), dup_set)
}
})
.1;
if dup_set.is_empty() {
Qualification::Matched
} else {
let dup_vec = dup_set.into_iter().take(1).collect::<Vec<IpAddr>>();
let first_dup_ip = dup_vec.first().expect("Duplicate IP address disappeared");
Qualification::Malformed(format!(
"Standard Gossip from {} contains multiple records claiming to be from {}",
gossip_source, first_dup_ip
))
}
}
fn handle(
&self,
cryptde: &dyn CryptDE,
database: &mut NeighborhoodDatabase,
agrs: Vec<AccessibleGossipRecord>,
gossip_source: SocketAddr,
_connection_progress_peers: &[IpAddr],
cpm_recipient: &Recipient<ConnectionProgressMessage>,
) -> GossipAcceptanceResult {
let initial_neighborship_status =
StandardGossipHandler::check_full_neighbor(database, gossip_source.ip());
let patch = self.compute_patch(&agrs, database.root());
let agrs = self.filter_agrs_from_patch(agrs, patch);
let mut db_changed =
self.identify_and_add_non_introductory_new_nodes(database, &agrs, gossip_source);
db_changed = self.identify_and_update_obsolete_nodes(database, agrs) || db_changed;
db_changed = self.handle_root_node(cryptde, database, gossip_source) || db_changed;
let final_neighborship_status =
StandardGossipHandler::check_full_neighbor(database, gossip_source.ip());
// If no Nodes need updating, return ::Ignored and don't change the database.
// Otherwise, return ::Accepted.
if db_changed {
trace!(self.logger, "Current database: {}", database.to_dot_graph());
if (initial_neighborship_status, final_neighborship_status) == (false, true) {
// Received Reply for Acceptance of Debut Gossip (false, true)
let cpm = ConnectionProgressMessage {
peer_addr: gossip_source.ip(),
event: ConnectionProgressEvent::StandardGossipReceived,
};
cpm_recipient
.try_send(cpm)
.unwrap_or_else(|e| panic!("Neighborhood is dead: {}", e));
}
GossipAcceptanceResult::Accepted
} else {
debug!(
self.logger,
"Gossip contained nothing new: StandardGossipHandler is ignoring it"
);
GossipAcceptanceResult::Ignored
}
}
}
impl StandardGossipHandler {
fn new(logger: Logger) -> StandardGossipHandler {
StandardGossipHandler { logger }
}
fn compute_patch(
&self,
agrs: &[AccessibleGossipRecord],
root_node: &NodeRecord,
) -> HashSet<PublicKey> {
let agrs_by_key = agrs
.iter()
.map(|agr| (&agr.inner.public_key, agr))
.collect::<HashMap<&PublicKey, &AccessibleGossipRecord>>();
let mut patch: HashSet<PublicKey> = HashSet::new();
self.compute_patch_recursive(
&mut patch,
root_node.public_key(),
&agrs_by_key,
DEFAULT_MINIMUM_HOP_COUNT,
root_node,
);
patch