This repository has been archived by the owner on Jun 25, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 80
/
node.rs
1587 lines (1431 loc) · 63.9 KB
/
node.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 2015 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the
// Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
use crust::{ConnectionInfoResult, PeerId, Service};
use crust::Event as CrustEvent;
use itertools::Itertools;
#[cfg(feature = "use-mock-crust")]
use kademlia_routing_table::RoutingTable;
use kademlia_routing_table::{AddedNodeDetails, ContactInfo, DroppedNodeDetails};
use maidsafe_utilities::serialisation;
use sodiumoxide::crypto::sign;
use sodiumoxide::crypto::hash::sha256;
use std::{cmp, fmt, iter};
use std::fmt::{Debug, Formatter};
use std::sync::mpsc::Sender;
use std::time::{Duration, Instant};
use ack_manager::{Ack, AckManager};
use action::Action;
use authority::Authority;
use cache::Cache;
use error::{InterfaceError, RoutingError};
use event::Event;
use id::{FullId, PublicId};
use message_accumulator::MessageAccumulator;
use message_filter::MessageFilter;
use messages::{DEFAULT_PRIORITY, DirectMessage, HopMessage, Message, MessageContent,
RoutingMessage, SignedMessage, UserMessage, UserMessageCache};
use peer_manager::{GROUP_SIZE, PeerManager, QUORUM_SIZE};
use signed_message_filter::SignedMessageFilter;
use state_machine::Transition;
use stats::Stats;
use super::common::{self, AnyState, Bootstrapped, Connect, HandleUserMessage, SendRoutingMessage,
USER_MSG_CACHE_EXPIRY_DURATION_SECS};
#[cfg(feature = "use-mock-crust")]
use super::common::Testable;
use timer::Timer;
use tunnels::Tunnels;
use types::MessageId;
use utils;
use xor_name::{XOR_NAME_BITS, XOR_NAME_LEN, XorName};
/// Time (in seconds) after which a `Tick` event is sent.
const TICK_TIMEOUT_SECS: u64 = 60;
/// Time (in seconds) the new close group waits for a joining node it sent a network name to.
const SENT_NETWORK_NAME_TIMEOUT_SECS: u64 = 30;
/// Initial period for requesting bucket close groups of all non-full buckets. This is doubled each
/// time.
const REFRESH_BUCKET_GROUPS_SECS: u64 = 120;
pub struct Node {
ack_mgr: AckManager,
bucket_filter: MessageFilter<usize>,
bucket_refresh_token_and_delay: Option<(u64, u64)>,
cacheable_user_msg_cache: UserMessageCache,
crust_service: Service,
event_sender: Sender<Event>,
full_id: FullId,
is_first_node: bool,
msg_accumulator: MessageAccumulator,
peer_mgr: PeerManager,
response_cache: Box<Cache>,
/// The last joining node we have sent a `GetNodeName` response to, and when.
sent_network_name_to: Option<(XorName, Instant)>,
signed_msg_filter: SignedMessageFilter,
stats: Stats,
tick_timer_token: u64,
timer: Timer,
tunnels: Tunnels,
user_msg_cache: UserMessageCache,
}
impl Node {
pub fn first(cache: Box<Cache>,
crust_service: Service,
event_sender: Sender<Event>,
mut full_id: FullId,
timer: Timer)
-> Option<Self> {
let name = XorName(sha256::hash(&full_id.public_id().name().0).0);
full_id.public_id_mut().set_name(name);
let public_id = *full_id.public_id();
let mut node = Self::new(cache,
crust_service,
event_sender,
full_id,
MessageAccumulator::new(),
PeerManager::new(public_id),
Default::default(),
timer);
if node.start_new_network() {
debug!("{:?} - State changed to node.", node);
Some(node)
} else {
node.send_event(Event::Terminate);
None
}
}
#[cfg_attr(feature = "clippy", allow(too_many_arguments))]
pub fn from_joining_node(their_peer_id: PeerId,
their_public_id: PublicId,
cache: Box<Cache>,
crust_service: Service,
event_sender: Sender<Event>,
full_id: FullId,
msg_accumulator: MessageAccumulator,
peer_mgr: PeerManager,
stats: Stats,
timer: Timer)
-> Self {
timer.stop();
let mut node = Self::new(cache,
crust_service,
event_sender,
full_id,
msg_accumulator,
peer_mgr,
stats,
timer);
debug!("{:?} - State changed to node.", node);
node.add_to_routing_table(their_public_id, their_peer_id);
node
}
#[cfg_attr(feature = "clippy", allow(too_many_arguments))]
fn new(cache: Box<Cache>,
crust_service: Service,
event_sender: Sender<Event>,
full_id: FullId,
msg_accumulator: MessageAccumulator,
peer_mgr: PeerManager,
stats: Stats,
mut timer: Timer)
-> Self {
let user_msg_cache_duration = Duration::from_secs(USER_MSG_CACHE_EXPIRY_DURATION_SECS);
let tick_period = Duration::from_secs(TICK_TIMEOUT_SECS);
let tick_timer_token = timer.schedule(tick_period);
Node {
ack_mgr: AckManager::new(),
bucket_filter: MessageFilter::with_expiry_duration(Duration::from_secs(60)),
bucket_refresh_token_and_delay: None,
cacheable_user_msg_cache:
UserMessageCache::with_expiry_duration(user_msg_cache_duration),
crust_service: crust_service,
event_sender: event_sender.clone(),
full_id: full_id,
is_first_node: false,
msg_accumulator: msg_accumulator,
peer_mgr: peer_mgr,
response_cache: cache,
signed_msg_filter: SignedMessageFilter::new(),
sent_network_name_to: None,
stats: stats,
tick_timer_token: tick_timer_token,
timer: timer,
tunnels: Default::default(),
user_msg_cache: UserMessageCache::with_expiry_duration(user_msg_cache_duration),
}
}
/// Routing table of this node.
#[cfg(feature = "use-mock-crust")]
pub fn routing_table(&self) -> &RoutingTable<XorName> {
self.peer_mgr.routing_table()
}
fn update_stats(&mut self) {
let old_client_num = self.stats.cur_client_num;
self.stats.cur_client_num = self.peer_mgr.client_num();
if self.stats.cur_client_num != old_client_num {
if self.stats.cur_client_num > old_client_num {
self.stats.cumulative_client_num += self.stats.cur_client_num - old_client_num;
}
info!("{:?} - Connected clients: {}, cumulative: {}",
self,
self.stats.cur_client_num,
self.stats.cumulative_client_num);
}
if self.stats.tunnel_connections != self.tunnels.tunnel_count() ||
self.stats.tunnel_client_pairs != self.tunnels.client_count() {
self.stats.tunnel_connections = self.tunnels.tunnel_count();
self.stats.tunnel_client_pairs = self.tunnels.client_count();
info!("{:?} - Indirect connections: {}, tunneling for: {}",
self,
self.stats.tunnel_connections,
self.stats.tunnel_client_pairs);
}
if self.stats.cur_routing_table_size != self.peer_mgr.routing_table().len() {
self.stats.cur_routing_table_size = self.peer_mgr.routing_table().len();
let status_str = format!("{:?} {:?} - Routing Table size: {:3}",
self,
self.crust_service.id(),
self.stats.cur_routing_table_size);
info!(" -{}- ",
iter::repeat('-').take(status_str.len()).collect::<String>());
info!("| {} |", status_str); // Temporarily error for ci_test.
info!(" -{}- ",
iter::repeat('-').take(status_str.len()).collect::<String>());
}
}
pub fn handle_action(&mut self, action: Action) -> Transition {
match action {
Action::ClientSendRequest { result_tx, .. } => {
let _ = result_tx.send(Err(InterfaceError::InvalidState));
}
Action::NodeSendMessage { src, dst, content, priority, result_tx } => {
let result = match self.send_user_message(src, dst, content, priority) {
Err(RoutingError::Interface(err)) => Err(err),
Err(_) | Ok(_) => Ok(()),
};
let _ = result_tx.send(result);
}
Action::CloseGroup { name, result_tx } => {
let _ =
result_tx.send(self.peer_mgr.routing_table().close_nodes(&name, GROUP_SIZE));
}
Action::Name { result_tx } => {
let _ = result_tx.send(*self.name());
}
Action::QuorumSize { result_tx } => {
let _ = result_tx.send(self.dynamic_quorum_size());
}
Action::Timeout(token) => self.handle_timeout(token),
Action::Terminate => {
return Transition::Terminate;
}
}
self.update_stats();
Transition::Stay
}
pub fn handle_crust_event(&mut self, crust_event: CrustEvent) -> Transition {
match crust_event {
CrustEvent::BootstrapAccept(peer_id) => self.handle_bootstrap_accept(peer_id),
CrustEvent::BootstrapConnect(peer_id, _) => self.handle_bootstrap_connect(peer_id),
CrustEvent::ConnectSuccess(peer_id) => self.handle_connect_success(peer_id),
CrustEvent::ConnectFailure(peer_id) => self.handle_connect_failure(peer_id),
CrustEvent::LostPeer(peer_id) => {
let _ = self.handle_lost_peer(peer_id);
}
CrustEvent::NewMessage(peer_id, bytes) => {
match self.handle_new_message(peer_id, bytes) {
Err(RoutingError::FilterCheckFailed) |
Ok(_) => (),
Err(err) => debug!("{:?} - {:?}", self, err),
}
}
CrustEvent::ConnectionInfoPrepared(ConnectionInfoResult { result_token, result }) => {
self.handle_connection_info_prepared(result_token, result);
}
CrustEvent::ListenerStarted(port) => {
self.handle_listener_started(port);
}
CrustEvent::ListenerFailed => {
error!("{:?} Failed to start listening.", self);
self.send_event(Event::Terminate);
}
CrustEvent::WriteMsgSizeProhibitive(peer_id, msg) => {
error!("{:?} Failed to send {}-byte message to {:?}. Message too large.",
self,
msg.len(),
peer_id);
}
_ => {
debug!("{:?} - Unhandled crust event: {:?}", self, crust_event);
}
}
self.update_stats();
Transition::Stay
}
fn handle_listener_started(&mut self, port: u16) {
trace!("{:?} Listener started on port {}.", self, port);
self.crust_service.set_service_discovery_listen(true);
info!("{:?} - Started a new network as a seed node.", self);
}
fn handle_bootstrap_accept(&mut self, peer_id: PeerId) {
trace!("{:?} Received BootstrapAccept from {:?}.", self, peer_id);
// TODO: Keep track of that peer to make sure we receive a message from them.
}
fn handle_bootstrap_connect(&mut self, peer_id: PeerId) {
self.disconnect_peer(&peer_id)
}
fn handle_connect_success(&mut self, peer_id: PeerId) {
if peer_id == self.crust_service.id() {
debug!("{:?} Received ConnectSuccess event with our Crust peer ID.",
self);
return;
}
// TODO(afck): Keep track of this connection: Disconnect if we don't receive a
// NodeIdentify.
// Remove tunnel connection if we have one for this peer already
if let Some(tunnel_id) = self.tunnels.remove_tunnel_for(&peer_id) {
debug!("{:?} Removing unwanted tunnel for {:?}", self, peer_id);
let message = DirectMessage::TunnelDisconnect(peer_id);
let _ = self.send_direct_message(&tunnel_id, message);
} else if let Some(pub_id) = self.peer_mgr.get_routing_peer(&peer_id) {
warn!("{:?} Received ConnectSuccess from {:?}, but node {:?} is already in our \
routing table.",
self,
peer_id,
pub_id.name());
return;
}
// TODO: Keep track of this peer, even if this returns false.
self.peer_mgr.connected_to(peer_id);
debug!("{:?} Received ConnectSuccess from {:?}. Sending NodeIdentify.",
self,
peer_id);
if let Err(error) = self.send_node_identify(peer_id) {
warn!("{:?} Failed to send NodeIdentify to {:?}: {:?}",
self,
peer_id,
error);
self.disconnect_peer(&peer_id);
}
}
fn handle_connect_failure(&mut self, peer_id: PeerId) {
if peer_id == self.crust_service.id() {
debug!("{:?} Received ConnectFailure event with our Crust peer ID.",
self);
return;
}
if let Some(&pub_id) = self.peer_mgr.get_connecting_peer(&peer_id) {
info!("{:?} Failed to connect to peer {:?} with pub_id {:?}.",
self,
peer_id,
pub_id);
self.find_tunnel_for_peer(peer_id, &pub_id);
}
}
fn find_tunnel_for_peer(&mut self, peer_id: PeerId, pub_id: &PublicId) {
for (name, dst_peer_id) in self.peer_mgr.set_searching_for_tunnel(peer_id, pub_id) {
trace!("{:?} Asking {:?} to serve as a tunnel.", self, name);
let tunnel_request = DirectMessage::TunnelRequest(peer_id);
let _ = self.send_direct_message(&dst_peer_id, tunnel_request);
}
}
fn handle_new_message(&mut self, peer_id: PeerId, bytes: Vec<u8>) -> Result<(), RoutingError> {
match serialisation::deserialise(&bytes) {
Ok(Message::Hop(hop_msg)) => self.handle_hop_message(hop_msg, peer_id),
Ok(Message::Direct(direct_msg)) => self.handle_direct_message(direct_msg, peer_id),
Ok(Message::TunnelDirect { content, src, dst }) => {
if dst == self.crust_service.id() &&
self.tunnels.tunnel_for(&src) == Some(&peer_id) {
self.handle_direct_message(content, src)
} else if self.tunnels.has_clients(src, dst) {
self.send_or_drop(&dst, bytes, content.priority())
} else if self.tunnels.accept_clients(src, dst) {
try!(self.send_direct_message(&dst, DirectMessage::TunnelSuccess(src)));
self.send_or_drop(&dst, bytes, content.priority())
} else {
Err(RoutingError::InvalidDestination)
}
}
Ok(Message::TunnelHop { content, src, dst }) => {
if dst == self.crust_service.id() &&
self.tunnels.tunnel_for(&src) == Some(&peer_id) {
self.handle_hop_message(content, src)
} else if self.tunnels.has_clients(src, dst) {
self.send_or_drop(&dst, bytes, content.content().priority())
} else {
Err(RoutingError::InvalidDestination)
}
}
Err(error) => Err(RoutingError::SerialisationError(error)),
}
}
fn handle_hop_message(&mut self,
hop_msg: HopMessage,
peer_id: PeerId)
-> Result<(), RoutingError> {
let hop_name;
if let Some(public_id) = self.peer_mgr.get_routing_peer(&peer_id) {
try!(hop_msg.verify(public_id.signing_public_key()));
hop_name = *public_id.name();
} else if let Some(client_info) = self.peer_mgr.get_client(&peer_id) {
try!(hop_msg.verify(&client_info.public_key));
if client_info.client_restriction {
try!(self.check_valid_client_message(hop_msg.content().routing_message()));
}
hop_name = *self.name();
} else if let Some(pub_id) = self.peer_mgr.get_proxy_public_id(&peer_id) {
try!(hop_msg.verify(pub_id.signing_public_key()));
hop_name = *pub_id.name();
} else {
// TODO: Drop peer?
// debug!("Received hop message from unknown name {:?}. Dropping peer {:?}.",
// hop_msg.name(),
// peer_id);
// self.disconnect_peer(&peer_id);
return Err(RoutingError::UnknownConnection(peer_id));
}
self.handle_signed_message(hop_msg.content(),
hop_msg.route(),
&hop_name,
hop_msg.sent_to())
}
/// Returns `Ok` if a client is allowed to send the given message.
fn check_valid_client_message(&self, msg: &RoutingMessage) -> Result<(), RoutingError> {
match msg.content {
MessageContent::Ack(..) => Ok(()),
MessageContent::UserMessagePart { priority, .. } if priority >= DEFAULT_PRIORITY => {
Ok(())
}
_ => {
debug!("{:?} Illegitimate client message {:?}. Refusing to relay.",
self,
msg);
Err(RoutingError::RejectedClientMessage)
}
}
}
fn handle_signed_message(&mut self,
signed_msg: &SignedMessage,
route: u8,
hop_name: &XorName,
sent_to: &[XorName])
-> Result<(), RoutingError> {
try!(signed_msg.check_integrity());
let routing_msg = signed_msg.routing_message();
// FIXME: This is currently only in place so acks can get delivered if the
// original ack was lost in transit
if (self.msg_accumulator.contains(routing_msg) || !routing_msg.src.is_group()) &&
self.is_recipient(&routing_msg.dst) {
self.send_ack(routing_msg, route);
}
let count = self.signed_msg_filter.filter_incoming(signed_msg);
// Prevents
// 1) someone sending messages repeatedly to us
// 2) swarm messages generated by us reaching us again
if count > GROUP_SIZE {
return Err(RoutingError::FilterCheckFailed);
}
if self.is_recipient(&routing_msg.dst) {
// TODO: If group, verify the sender's membership.
if let Authority::Client { ref client_key, .. } = signed_msg.routing_message().src {
if client_key != signed_msg.public_id().signing_public_key() {
return Err(RoutingError::FailedSignature);
};
}
} else if try!(self.respond_from_cache(&routing_msg, route)) {
return Ok(());
}
if let Err(error) = self.send_signed_message(signed_msg, route, hop_name, sent_to) {
debug!("{:?} Failed to send {:?}: {:?}", self, signed_msg, error);
}
if count == 1 && self.is_recipient(&routing_msg.dst) {
self.handle_routing_message(routing_msg, signed_msg.public_id())
} else {
Ok(())
}
}
fn respond_from_cache(&mut self,
routing_msg: &RoutingMessage,
route: u8)
-> Result<bool, RoutingError> {
if let MessageContent::UserMessagePart { hash,
part_count,
part_index,
cacheable,
ref payload,
.. } = routing_msg.content {
if !cacheable {
return Ok(false);
}
match self.cacheable_user_msg_cache.add(hash, part_count, part_index, payload.clone()) {
Some(UserMessage::Request(request)) => {
if let Some(response) = self.response_cache.get(&request) {
debug!("{:?} Found cached response to {:?}", self, request);
let priority = response.priority();
let src = Authority::ManagedNode(*self.name());
let dst = routing_msg.src.clone();
self.send_ack_from(routing_msg, route, src.clone());
try!(self.send_user_message(src,
dst,
UserMessage::Response(response),
priority));
return Ok(true);
}
}
Some(UserMessage::Response(response)) => {
debug!("{:?} putting {:?} to cache", self, response);
self.response_cache.put(response);
}
None => (),
}
}
Ok(false)
}
fn handle_routing_message(&mut self,
routing_msg: &RoutingMessage,
public_id: &PublicId)
-> Result<(), RoutingError> {
let dynamic_quorum_size = self.dynamic_quorum_size();
self.msg_accumulator.set_quorum_size(dynamic_quorum_size);
if let Some(msg) = try!(self.accumulate(routing_msg, public_id)) {
if msg.src.is_group() {
self.send_ack(&msg, 0);
}
self.dispatch_routing_message(msg).map(|_| ())
} else {
Ok(())
}
}
fn dynamic_quorum_size(&self) -> usize {
// Routing table entries plus this node itself.
let network_size = self.peer_mgr.routing_table().len() + 1;
if network_size >= GROUP_SIZE {
QUORUM_SIZE
} else {
cmp::max(network_size * QUORUM_SIZE / GROUP_SIZE,
network_size / 2 + 1)
}
}
fn start_new_network(&mut self) -> bool {
self.is_first_node = true;
if let Err(error) = self.crust_service.start_listening_tcp() {
error!("{:?} Failed to start listening: {:?}", self, error);
false
} else {
info!("{:?} Attempting to start listener.", self);
true
}
}
fn send_bootstrap_identify(&mut self, peer_id: PeerId) -> Result<(), RoutingError> {
let direct_message = DirectMessage::BootstrapIdentify {
public_id: *self.full_id.public_id(),
current_quorum_size: self.dynamic_quorum_size(),
};
self.send_direct_message(&peer_id, direct_message)
}
fn handle_direct_message(&mut self,
direct_message: DirectMessage,
peer_id: PeerId)
-> Result<(), RoutingError> {
match direct_message {
DirectMessage::ClientIdentify { ref serialised_public_id,
ref signature,
client_restriction } => {
if let Ok(public_id) = common::verify_signed_public_id(serialised_public_id,
signature) {
self.handle_client_identify(public_id, peer_id, client_restriction)
} else {
warn!("{:?} Signature check failed in ClientIdentify - \
Dropping connection {:?}",
self,
peer_id);
self.disconnect_peer(&peer_id);
Ok(())
}
}
DirectMessage::NodeIdentify { ref serialised_public_id, ref signature } => {
if let Ok(public_id) = common::verify_signed_public_id(serialised_public_id,
signature) {
let _ = self.handle_node_identify(public_id, peer_id);
} else {
warn!("{:?} Signature check failed in NodeIdentify - Dropping peer {:?}",
self,
peer_id);
self.disconnect_peer(&peer_id);
}
Ok(())
}
DirectMessage::NewNode(public_id) => {
trace!("{:?} Received NewNode({:?}).", self, public_id);
if self.peer_mgr.routing_table().need_to_add(public_id.name()) {
let our_name = *self.name();
return self.send_connection_info(public_id,
Authority::ManagedNode(our_name),
Authority::ManagedNode(*public_id.name()))
.map(|_| ());
}
Ok(())
}
DirectMessage::ConnectionUnneeded(ref name) => {
if self.peer_mgr.remove_if_unneeded(name, &peer_id) {
info!("{:?} Dropped {:?} from the routing table.", self, name);
self.crust_service.disconnect(peer_id);
let _ = self.handle_lost_peer(peer_id);
}
Ok(())
}
DirectMessage::TunnelRequest(dst_id) => self.handle_tunnel_request(peer_id, dst_id),
DirectMessage::TunnelSuccess(dst_id) => self.handle_tunnel_success(peer_id, dst_id),
DirectMessage::TunnelClosed(dst_id) => self.handle_tunnel_closed(peer_id, dst_id),
DirectMessage::TunnelDisconnect(dst_id) => {
self.handle_tunnel_disconnect(peer_id, dst_id)
}
_ => {
debug!("{:?} - Unhandled direct message: {:?}",
self,
direct_message);
Ok(())
}
}
}
fn handle_client_identify(&mut self,
public_id: PublicId,
peer_id: PeerId,
client_restriction: bool)
-> Result<(), RoutingError> {
if *public_id.name() != XorName(sha256::hash(&public_id.signing_public_key().0).0) {
warn!("{:?} Incoming Connection not validated as a proper client - dropping",
self);
self.disconnect_peer(&peer_id);
return Ok(());
}
for peer_id in self.peer_mgr.remove_stale_joining_nodes() {
debug!("{:?} Removing stale joining node with Crust ID {:?}",
self,
peer_id);
self.disconnect_peer(&peer_id);
}
if (client_restriction || !self.is_first_node) &&
self.peer_mgr.routing_table().len() < GROUP_SIZE - 1 {
debug!("{:?} Client {:?} rejected: Routing table has {} entries. {} required.",
self,
public_id.name(),
self.peer_mgr.routing_table().len(),
GROUP_SIZE - 1);
return self.send_direct_message(&peer_id, DirectMessage::BootstrapDeny);
}
if self.peer_mgr.get_client(&peer_id).is_some() {
debug!("{:?} Received two ClientInfo from the same peer ID {:?}.",
self,
peer_id);
}
self.peer_mgr.insert_client(peer_id, &public_id, client_restriction);
debug!("{:?} Accepted client {:?}.", self, public_id.name());
self.send_bootstrap_identify(peer_id)
}
fn add_to_routing_table(&mut self, public_id: PublicId, peer_id: PeerId) {
let name = *public_id.name();
if self.peer_mgr.routing_table().contains(&name) {
return; // We already sent a `NodeIdentify` to this peer.
}
let bucket_index = self.name().bucket_index(&name);
let common_groups = self.peer_mgr
.routing_table()
.is_in_any_close_group_with(bucket_index, GROUP_SIZE);
match self.peer_mgr.add_to_routing_table(public_id, peer_id) {
None => {
debug!("{:?} Peer was not added to the routing table: {:?}",
self,
peer_id);
self.disconnect_peer(&peer_id);
}
Some(AddedNodeDetails { must_notify, unneeded }) => {
info!("{:?} Added {:?} to routing table.", self, name);
if self.peer_mgr.routing_table().len() == 1 {
let _ = self.event_sender.send(Event::Connected);
}
for peer_id in self.peer_mgr.get_peer_ids(&must_notify) {
let message = DirectMessage::NewNode(public_id);
let _ = self.send_direct_message(&peer_id, message);
}
for peer_id in self.peer_mgr.get_peer_ids(&unneeded) {
let message = DirectMessage::ConnectionUnneeded(*self.name());
let _ = self.send_direct_message(&peer_id, message);
}
self.reset_bucket_refresh_timer();
if common_groups {
let event = Event::NodeAdded(name, self.peer_mgr.routing_table().clone());
if let Err(err) = self.event_sender.send(event) {
error!("{:?} Error sending event to routing user - {:?}", self, err);
}
}
}
}
if self.peer_mgr.routing_table().len() == 1 {
self.request_bucket_close_groups();
}
for dst_id in self.peer_mgr.peers_needing_tunnel() {
let tunnel_request = DirectMessage::TunnelRequest(dst_id);
let _ = self.send_direct_message(&peer_id, tunnel_request);
}
}
fn reset_bucket_refresh_timer(&mut self) {
if let Some((_, REFRESH_BUCKET_GROUPS_SECS)) = self.bucket_refresh_token_and_delay {
return; // Timer has already been reset.
}
let new_token = self.timer.schedule(Duration::from_secs(REFRESH_BUCKET_GROUPS_SECS));
self.bucket_refresh_token_and_delay = Some((new_token, REFRESH_BUCKET_GROUPS_SECS));
}
/// Sends a `GetCloseGroup` request to the close group with our `bucket_index`-th bucket
/// address.
fn request_bucket_ids(&mut self, bucket_index: usize) -> Result<(), RoutingError> {
if bucket_index >= XOR_NAME_BITS {
return Ok(());
}
trace!("{:?} Send GetCloseGroup to bucket {}.", self, bucket_index);
let bucket_address = self.name().with_flipped_bit(bucket_index);
self.request_close_group(bucket_address)
}
fn request_close_group(&mut self, name: XorName) -> Result<(), RoutingError> {
let request_msg = RoutingMessage {
src: Authority::ManagedNode(*self.name()),
dst: Authority::NaeManager(name),
content: MessageContent::GetCloseGroup(MessageId::new()),
};
self.send_routing_message(request_msg)
}
/// Handle a request by `peer_id` to act as a tunnel connecting it with `dst_id`.
fn handle_tunnel_request(&mut self,
peer_id: PeerId,
dst_id: PeerId)
-> Result<(), RoutingError> {
if self.peer_mgr.can_tunnel_for(&peer_id, &dst_id) {
if let Some((id0, id1)) = self.tunnels.consider_clients(peer_id, dst_id) {
debug!("{:?} Accepted tunnel request from {:?} for {:?}.",
self,
peer_id,
dst_id);
return self.send_direct_message(&id0, DirectMessage::TunnelSuccess(id1));
}
} else {
debug!("{:?} Rejected tunnel request from {:?} for {:?}.",
self,
peer_id,
dst_id);
}
Ok(())
}
/// Handle a `TunnelSuccess` response from `peer_id`: It will act as a tunnel to `dst_id`.
fn handle_tunnel_success(&mut self,
peer_id: PeerId,
dst_id: PeerId)
-> Result<(), RoutingError> {
if self.peer_mgr.tunnelling_to(dst_id) && self.tunnels.add(dst_id, peer_id) {
debug!("{:?} Adding {:?} as a tunnel node for {:?}.",
self,
peer_id,
dst_id);
return self.send_node_identify(dst_id);
}
Ok(())
}
/// Handle a `TunnelClosed` message from `peer_id`: `dst_id` disconnected.
fn handle_tunnel_closed(&mut self,
peer_id: PeerId,
dst_id: PeerId)
-> Result<(), RoutingError> {
if self.tunnels.remove(dst_id, peer_id) {
debug!("{:?} Tunnel to {:?} via {:?} closed.",
self,
dst_id,
peer_id);
if !self.crust_service.is_connected(&dst_id) {
self.dropped_routing_node_connection(&dst_id);
}
}
Ok(())
}
/// Handle a `TunnelDisconnect` message from `peer_id` who wants to disconnect `dst_id`.
fn handle_tunnel_disconnect(&mut self,
peer_id: PeerId,
dst_id: PeerId)
-> Result<(), RoutingError> {
debug!("{:?} Closing tunnel connecting {:?} and {:?}.",
self,
dst_id,
peer_id);
if self.tunnels.drop_client_pair(dst_id, peer_id) {
self.send_direct_message(&dst_id, DirectMessage::TunnelClosed(peer_id))
} else {
Ok(())
}
}
/// Disconnects from the given peer, via Crust or by dropping the tunnel node, if the peer is
/// not a proxy, client or routing table entry.
fn disconnect_peer(&mut self, peer_id: &PeerId) {
if let Some(&pub_id) = self.peer_mgr.get_routing_peer(peer_id) {
debug!("{:?} Not disconnecting routing table entry {:?} ({:?}).",
self,
pub_id.name(),
peer_id);
} else if let Some(&public_id) = self.peer_mgr.get_proxy_public_id(peer_id) {
debug!("{:?} Not disconnecting proxy node {:?} ({:?}).",
self,
public_id.name(),
peer_id);
} else if self.peer_mgr.get_client(peer_id).is_some() {
debug!("{:?} Not disconnecting client {:?}.", self, peer_id);
} else if let Some(tunnel_id) = self.tunnels.remove_tunnel_for(peer_id) {
debug!("{:?} Disconnecting {:?} (indirect).", self, peer_id);
let message = DirectMessage::TunnelDisconnect(*peer_id);
let _ = self.send_direct_message(&tunnel_id, message);
} else {
debug!("{:?} Disconnecting {:?}. Calling crust::Service::disconnect.",
self,
peer_id);
let _ = self.crust_service.disconnect(*peer_id);
let _ = self.peer_mgr.remove_peer(peer_id);
}
}
// Received by X; From A -> X
fn handle_get_name_range_request(&mut self,
mut their_public_id: PublicId,
client_key: sign::PublicKey,
proxy_name: XorName,
dst_name: XorName,
peer_id: PeerId,
message_id: MessageId)
-> Result<(), RoutingError> {
let hashed_key = sha256::hash(&client_key.0);
let close_group_to_client = XorName(hashed_key.0);
// Validate Client (relocating node) has contacted the correct Group-X
if close_group_to_client != dst_name {
return Err(RoutingError::InvalidDestination);
}
let close_group = match self.peer_mgr.routing_table().close_nodes(&dst_name, GROUP_SIZE) {
Some(close_group) => close_group,
None => return Err(RoutingError::InvalidDestination),
};
let relocated_name = try!(utils::calculate_relocated_name(close_group,
&their_public_id.name()));
their_public_id.set_name(relocated_name);
// From X -> Y; Send to close group of the relocated name
let request_content = MessageContent::ExpectCloseNode {
expect_id: their_public_id,
client_auth: Authority::Client {
client_key: client_key,
proxy_node_name: proxy_name,
peer_id: peer_id,
},
message_id: message_id,
};
let request_msg = RoutingMessage {
src: Authority::NaeManager(dst_name),
dst: Authority::NaeManager(relocated_name),
content: request_content,
};
self.send_routing_message(request_msg)
}
// Received by Y; From X -> Y
fn handle_expect_close_node_request(&mut self,
expect_id: PublicId,
client_auth: Authority,
message_id: MessageId)
-> Result<(), RoutingError> {
if expect_id == *self.full_id.public_id() {
return Ok(());
}
let now = Instant::now();
if let Some((_, timestamp)) = self.sent_network_name_to {
if (now - timestamp).as_secs() <= SENT_NETWORK_NAME_TIMEOUT_SECS {
return Ok(()); // Not sending node name, as we are already waiting for a node.
}
self.sent_network_name_to = None;
}
let mut public_ids = match self.peer_mgr
.routing_table()
.close_nodes(expect_id.name(), GROUP_SIZE) {
Some(close_group) => self.peer_mgr.get_pub_ids(&close_group),
None => return Err(RoutingError::InvalidDestination),
};
self.sent_network_name_to = Some((*expect_id.name(), now));
// From Y -> A (via B)
let response_content = MessageContent::GetNameRangeResponse {
name_range: Node::max_range(&mut public_ids),
close_group_ids: public_ids,
message_id: message_id,
};
debug!("{:?} Responding to client {:?}: {:?}.",
self,
client_auth,
response_content);
let response_msg = RoutingMessage {
src: Authority::NodeManager(*expect_id.name()),
dst: client_auth,
content: response_content,
};
self.send_routing_message(response_msg)
}
fn max_range(nodes: &mut [PublicId]) -> (XorName, XorName) {
println!("input nodes {:?}", nodes);
let name = XorName([0u8; XOR_NAME_LEN]);
nodes.sort_by(|node0, node1| name.cmp_distance(&node0.name(), &node1.name()));
println!("sorted nodes {:?}", nodes);
let mut max_range = XorName([0u8; XOR_NAME_LEN]);
let mut range_index = 0;
for i in 0..(nodes.len() - 1) {
let range = nodes[i+1].name().minus(nodes[i].name());
if range > max_range {
max_range = range;
range_index = i;
}
}
println!("max_range {:?} between node {}", max_range, range_index);
(*nodes[range_index].name(), *nodes[range_index + 1].name())
}
// Received by Y; From A -> Y, or from any node to one of its bucket addresses.
fn handle_get_close_group_request(&mut self,
src: Authority,
dst_name: XorName,
message_id: MessageId)
-> Result<(), RoutingError> {
// If msg is from ourselves, ignore it.