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
2499 lines (2279 loc) · 88.1 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 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// 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 super::{
common::{Approved, Base, Bootstrapped, Relocated, USER_MSG_CACHE_EXPIRY_DURATION},
establishing_node::EstablishingNode,
};
use crate::{
ack_manager::{Ack, AckManager},
cache::Cache,
chain::{
Chain, ChainState, GenesisPfxInfo, NetworkEvent, PrefixChangeOutcome, Proof, ProofSet,
ProvingSection, SectionInfo,
},
config_handler,
crust::{CrustError, CrustUser, PrivConnectionInfo},
error::{BootstrapResponseError, InterfaceError, RoutingError},
event::Event,
id::{FullId, PublicId},
messages::{
DirectMessage, HopMessage, MessageContent, RoutingMessage, SignedMessage, UserMessage,
UserMessageCache, DEFAULT_PRIORITY, MAX_PARTS, MAX_PART_LEN,
},
outbox::EventBox,
parsec::{self, ParsecMap},
peer_manager::{Peer, PeerManager, PeerState},
rate_limiter::RateLimiter,
resource_prover::RESOURCE_PROOF_DURATION,
routing_message_filter::{FilteringResult, RoutingMessageFilter},
routing_table::Error as RoutingTableError,
routing_table::{Authority, Prefix, Xorable, DEFAULT_PREFIX},
sha3::Digest256,
signature_accumulator::SignatureAccumulator,
state_machine::Transition,
time::{Duration, Instant},
timer::Timer,
types::MessageId,
utils::{self, DisplayDuration},
xor_name::XorName,
Service,
};
use itertools::Itertools;
use log::LogLevel;
use lru_time_cache::LruCache;
use maidsafe_utilities::serialisation;
use rand::{self, Rng};
use safe_crypto::Signature;
#[cfg(feature = "mock_base")]
use std::collections::BTreeMap;
use std::{
cmp,
collections::{BTreeSet, VecDeque},
fmt::{self, Display, Formatter},
iter, mem,
net::{IpAddr, SocketAddr},
};
/// Time after which a `Ticked` event is sent.
const TICK_TIMEOUT: Duration = Duration::from_secs(15);
const GOSSIP_TIMEOUT: Duration = Duration::from_secs(2);
const RECONNECT_PEER_TIMEOUT: Duration = Duration::from_secs(20);
//const MAX_IDLE_ROUNDS: u64 = 100;
//const TICK_TIMEOUT_SECS: u64 = 60;
/// The number of required leading zero bits for the resource proof
const RESOURCE_PROOF_DIFFICULTY: u8 = 0;
/// The total size of the resource proof data.
const RESOURCE_PROOF_TARGET_SIZE: usize = 250 * 1024 * 1024;
/// Interval between displaying info about current candidate.
const CANDIDATE_STATUS_INTERVAL: Duration = Duration::from_secs(60);
/// Duration for which all clients on a given IP will be blocked from joining this node.
const CLIENT_BAN_DURATION: Duration = Duration::from_secs(2 * 60 * 60);
/// Duration for which clients' IDs we disconnected from are retained.
const DROPPED_CLIENT_TIMEOUT: Duration = Duration::from_secs(2 * 60 * 60);
pub struct Node {
ack_mgr: AckManager,
cacheable_user_msg_cache: UserMessageCache,
crust_service: Service,
full_id: FullId,
is_first_node: bool,
/// The queue of routing messages addressed to us. These do not themselves need forwarding,
/// although they may wrap a message which needs forwarding.
msg_queue: VecDeque<RoutingMessage>,
peer_mgr: PeerManager,
response_cache: Box<Cache>,
routing_msg_filter: RoutingMessageFilter,
sig_accumulator: SignatureAccumulator,
tick_timer_token: u64,
timer: Timer,
user_msg_cache: UserMessageCache,
/// Value which can be set in mock-crust tests to be used as the calculated name for the next
/// relocation request received by this node.
next_relocation_dst: Option<XorName>,
/// Interval used for relocation in mock crust tests.
next_relocation_interval: Option<(XorName, XorName)>,
/// The timer token for accepting a new candidate.
candidate_timer_token: Option<u64>,
/// The timer token for displaying the current candidate status.
candidate_status_token: u64,
/// Limits the rate at which clients can pass messages through this node when it acts as their
/// proxy.
clients_rate_limiter: RateLimiter,
/// IPs of clients which have been temporarily blocked from bootstrapping off this node.
banned_client_ips: LruCache<IpAddr, ()>,
/// Recently-disconnected clients. Clients are added to this when we disconnect from them so we
/// have a way to know to not handle subsequent hop messages from them (i.e. those which were
/// already enqueued in the channel or added before Crust handled the disconnect request). If a
/// client then re-connects, its ID is removed from here when we add it to the `PeerManager`.
dropped_clients: LruCache<PublicId, ()>,
/// Proxy client traffic handled
proxy_load_amount: u64,
/// Whether resource proof is disabled.
disable_resource_proof: bool,
parsec_map: ParsecMap,
gen_pfx_info: GenesisPfxInfo,
gossip_timer_token: u64,
chain: Chain,
// Peers we want to try reconnecting to
reconnect_peers: Vec<PublicId>,
reconnect_peers_token: u64,
// TODO: notify without local state
notified_nodes: BTreeSet<PublicId>,
}
impl Node {
pub fn first(
cache: Box<Cache>,
crust_service: Service,
full_id: FullId,
min_section_size: usize,
timer: Timer,
) -> Option<Self> {
let dev_config = config_handler::get_config().dev.unwrap_or_default();
let public_id = *full_id.public_id();
let gen_pfx_info = GenesisPfxInfo {
first_info: create_first_section_info(public_id).ok()?,
latest_info: SectionInfo::default(),
};
let parsec_map = ParsecMap::new(full_id.clone(), &gen_pfx_info);
let chain = Chain::new(min_section_size, public_id, gen_pfx_info.clone());
let mut node = Self::new(
AckManager::new(),
cache,
chain,
crust_service,
full_id,
gen_pfx_info,
true,
Default::default(),
Default::default(),
parsec_map,
PeerManager::new(public_id, dev_config.disable_client_rate_limiter),
RoutingMessageFilter::new(),
timer,
);
if let Err(error) = node.crust_service.start_listening_tcp() {
error!("{} - Failed to start listening: {:?}", node, error);
None
} else {
debug!("{} - State changed to Node.", node);
info!("{} - Started a new network as a seed node.", node);
Some(node)
}
}
pub fn from_establishing_node(
source: EstablishingNode,
sec_info: SectionInfo,
old_pfx: Prefix<XorName>,
outbox: &mut EventBox,
) -> Result<Self, RoutingError> {
let mut node = Self::new(
source.ack_mgr,
source.cache,
source.chain,
source.crust_service,
source.full_id,
source.gen_pfx_info,
false,
source.msg_backlog.into_iter().collect(),
source.notified_nodes,
source.parsec_map,
source.peer_mgr,
source.routing_msg_filter,
source.timer,
);
node.init(sec_info, old_pfx, outbox)?;
Ok(node)
}
#[allow(clippy::too_many_arguments)]
fn new(
ack_mgr: AckManager,
cache: Box<Cache>,
chain: Chain,
crust_service: Service,
full_id: FullId,
gen_pfx_info: GenesisPfxInfo,
is_first_node: bool,
msg_queue: VecDeque<RoutingMessage>,
notified_nodes: BTreeSet<PublicId>,
parsec_map: ParsecMap,
peer_mgr: PeerManager,
routing_msg_filter: RoutingMessageFilter,
timer: Timer,
) -> Self {
let dev_config = config_handler::get_config().dev.unwrap_or_default();
let tick_timer_token = timer.schedule(TICK_TIMEOUT);
let gossip_timer_token = timer.schedule(GOSSIP_TIMEOUT);
let candidate_status_token = timer.schedule(CANDIDATE_STATUS_INTERVAL);
let reconnect_peers_token = timer.schedule(RECONNECT_PEER_TIMEOUT);
Self {
ack_mgr,
cacheable_user_msg_cache: UserMessageCache::with_expiry_duration(
USER_MSG_CACHE_EXPIRY_DURATION,
),
crust_service: crust_service,
full_id: full_id.clone(),
is_first_node,
msg_queue,
peer_mgr,
response_cache: cache,
routing_msg_filter,
sig_accumulator: Default::default(),
tick_timer_token: tick_timer_token,
timer: timer,
user_msg_cache: UserMessageCache::with_expiry_duration(USER_MSG_CACHE_EXPIRY_DURATION),
next_relocation_dst: None,
next_relocation_interval: None,
candidate_timer_token: None,
candidate_status_token,
clients_rate_limiter: RateLimiter::new(dev_config.disable_client_rate_limiter),
banned_client_ips: LruCache::with_expiry_duration(CLIENT_BAN_DURATION),
dropped_clients: LruCache::with_expiry_duration(DROPPED_CLIENT_TIMEOUT),
proxy_load_amount: 0,
disable_resource_proof: dev_config.disable_resource_proof,
parsec_map,
gen_pfx_info,
gossip_timer_token,
chain,
reconnect_peers: Default::default(),
reconnect_peers_token,
notified_nodes,
}
}
fn print_rt_size(&self) {
const TABLE_LVL: LogLevel = LogLevel::Info;
if log_enabled!(TABLE_LVL) {
let status_str = format!(
"{} - Routing Table size: {:3}",
self,
self.chain.valid_peers().len()
);
let network_estimate = match self.chain.network_size_estimate() {
(n, true) => format!("Exact network size: {}", n),
(n, false) => format!("Estimated network size: {}", n),
};
let sep_len = cmp::max(status_str.len(), network_estimate.len());
let sep_str = iter::repeat('-').take(sep_len).collect::<String>();
log!(target: "routing_stats", TABLE_LVL, " -{}- ", sep_str);
log!(target: "routing_stats", TABLE_LVL, "| {:<1$} |", status_str, sep_len);
log!(target: "routing_stats", TABLE_LVL, "| {:<1$} |", network_estimate, sep_len);
log!(target: "routing_stats", TABLE_LVL, " -{}- ", sep_str);
}
}
// Initialise regular node
fn init(
&mut self,
sec_info: SectionInfo,
old_pfx: Prefix<XorName>,
outbox: &mut EventBox,
) -> Result<(), RoutingError> {
debug!("{} - State changed to Node.", self);
trace!(
"{} - Node Established. Prefixes: {:?}",
self,
self.chain.prefixes()
);
// We have just become established. Now we can supply our votes for all latest neighbour
// infos that have accumulated so far.
let neighbour_info_events = self
.chain
.neighbour_infos()
.map(|info| info.clone().into_network_event())
.collect_vec();
neighbour_info_events.into_iter().for_each(|event| {
self.vote_for_event(event);
});
outbox.send_event(Event::Connected);
// Handle the SectionInfo event which triggered us becoming established node.
let _ = self.handle_section_info_event(sec_info, old_pfx, outbox)?;
// Allow other peers to bootstrap via us.
if let Err(err) = self.crust_service.set_accept_bootstrap(true) {
warn!("{} Unable to accept bootstrap connections. {:?}", self, err);
}
self.crust_service.set_service_discovery_listen(true);
Ok(())
}
// Initialises the first node of the network
fn init_first_node(&mut self, outbox: &mut EventBox) -> Result<(), RoutingError> {
outbox.send_event(Event::Connected);
self.crust_service.set_accept_bootstrap(true)?;
self.crust_service.set_service_discovery_listen(true);
Ok(())
}
#[cfg(feature = "mock_base")]
pub fn chain(&self) -> &Chain {
&self.chain
}
fn handle_routing_messages(&mut self, outbox: &mut EventBox) {
while let Some(routing_msg) = self.msg_queue.pop_front() {
if self.in_authority(&routing_msg.dst) {
if let Err(err) = self.dispatch_routing_message(routing_msg, outbox) {
debug!("{} Routing message dispatch failed: {:?}", self, err);
}
}
}
}
fn handle_parsec_poke(&mut self, msg_version: u64, pub_id: PublicId) {
self.send_parsec_gossip(Some((msg_version, pub_id)))
}
/// Votes for `Merge` if necessary, or for the merged `SectionInfo` if both siblings have
/// already accumulated `Merge`.
fn merge_if_necessary(&mut self) -> Result<(), RoutingError> {
let sibling_pfx = self.our_prefix().sibling();
if self.chain.is_self_merge_ready() && self.chain.other_prefixes().contains(&sibling_pfx) {
let payload = *self.chain.our_info().hash();
let src = Authority::PrefixSection(*self.our_prefix());
let dst = Authority::PrefixSection(sibling_pfx);
let content = MessageContent::Merge(payload);
if let Err(err) = self.send_routing_message(src, dst, content) {
debug!("{} Failed to send Merge: {:?}.", self, err);
}
}
if let Some(merged_info) = self.chain.try_merge()? {
self.vote_for_event(NetworkEvent::SectionInfo(merged_info));
} else if self.chain.should_vote_for_merge() && !self.chain.is_self_merge_ready() {
self.vote_for_event(NetworkEvent::OurMerge);
}
Ok(())
}
// Connected peers which are valid need added to RT
// Peers no longer required currently connected as PeerState::Routing are disconnected
// Establish connection to peers missing from peer manager
fn update_peer_states(&mut self, outbox: &mut EventBox) {
let mut peers_to_add = Vec::new();
let mut peers_to_remove = Vec::new();
for peer in self.peer_mgr.connected_peers() {
let pub_id = peer.pub_id();
if self.chain.is_peer_valid(pub_id) {
peers_to_add.push(*pub_id);
} else if peer.is_routing() && self.chain.state() == &ChainState::Normal {
peers_to_remove.push(*peer.pub_id());
}
}
for pub_id in peers_to_add {
self.add_to_routing_table(&pub_id, outbox);
}
for pub_id in peers_to_remove {
trace!("{} Removing {:?} from RT.", self, pub_id);
let _ = self.peer_mgr.remove_peer(&pub_id);
self.disconnect_peer(&pub_id);
}
let peers_to_connect: BTreeSet<PublicId> = self
.chain
.valid_peers()
.into_iter()
.filter(|pub_id| {
self.peer_mgr.get_peer(pub_id).is_none() && *pub_id != self.full_id.public_id()
})
.cloned()
.collect();
for pub_id in peers_to_connect {
debug!("{} Sending connection info to {:?}.", self, pub_id);
let src = Authority::ManagedNode(*self.name());
let node_auth = Authority::ManagedNode(*pub_id.name());
if let Err(error) = self.send_connection_info_request(pub_id, src, node_auth, outbox) {
debug!(
"{} - Failed to send connection info to {:?}: {:?}",
self, pub_id, error
);
}
}
}
fn finalise_prefix_change(&mut self) -> Result<(), RoutingError> {
let drained_obs: Vec<_> = self
.parsec_map
.our_unpolled_observations()
.cloned()
.collect();
let sibling_pfx = self.chain.our_prefix().sibling();
let PrefixChangeOutcome {
gen_pfx_info,
mut cached_events,
completed_events,
} = self.chain.finalise_prefix_change()?;
self.gen_pfx_info = gen_pfx_info;
self.init_parsec(); // We don't reset the chain on prefix change.
let neighbour_infos: Vec<_> = self.chain.neighbour_infos().cloned().collect();
for ni in neighbour_infos {
if sibling_pfx != *ni.prefix() {
debug!("{} Committing neighbour section proof for {:?}", self, ni);
let ps = self.chain.get_proving_sections(&ni, *self.name())?;
self.vote_for_event(NetworkEvent::ProvingSections(ps, ni.clone()));
}
debug!("{} Re-voting for neighbour section {:?}", self, ni);
self.vote_for_event(ni.into_network_event());
}
for obs in drained_obs {
let event = match obs {
parsec::Observation::Add {
peer_id,
related_info,
} => NetworkEvent::Online(peer_id, serialisation::deserialise(&related_info)?),
parsec::Observation::Remove { peer_id, .. } => NetworkEvent::Offline(peer_id),
parsec::Observation::OpaquePayload(event) => event.clone(),
_ => continue,
};
let _ = cached_events.insert(event);
}
let our_pfx = *self.chain.our_prefix();
// filter cached events to SectionInfo where we benefit from additional signatures for
// neighbours for sec-msg-relay. Online/Offline events we only need to re-vote events which
// havent yet accumulated in old prefix and that are relevant to our new prefix.
cached_events
.iter()
.filter(|event| match **event {
NetworkEvent::Online(pub_id, _) | NetworkEvent::Offline(pub_id) => {
our_pfx.matches(pub_id.name()) && !completed_events.contains(event)
}
NetworkEvent::SectionInfo(ref sec_info) => our_pfx.is_neighbour(sec_info.prefix()),
NetworkEvent::OurMerge => false,
_ => true,
})
.for_each(|event| {
self.vote_for_event(event.clone());
});
Ok(())
}
fn send_neighbour_infos(&mut self) {
self.chain.other_prefixes().iter().for_each(|pfx| {
let payload = *self.chain.our_info().hash();
let src = Authority::ManagedNode(*self.full_id.public_id().name());
let dst = Authority::PrefixSection(*pfx);
let content = MessageContent::NeighbourInfo(payload);
if let Err(err) = self.send_routing_message(src, dst, content) {
debug!("{} Failed to send NeighbourInfo: {:?}.", self, err);
}
});
}
/// Returns `Ok` if the peer's state indicates it's allowed to send the given message type.
fn check_direct_message_sender(
&self,
direct_message: &DirectMessage,
pub_id: &PublicId,
) -> Result<(), RoutingError> {
match self.peer_mgr.get_peer(pub_id).map(Peer::state) {
Some(&PeerState::Bootstrapper { .. }) => {
if let DirectMessage::BootstrapRequest(_) = *direct_message {
return Ok(());
}
}
Some(&PeerState::Client { .. }) => (),
None => return Err(RoutingError::ClientConnectionNotFound),
_ => return Ok(()),
}
debug!(
"{} Illegitimate direct message {:?} from {:?}.",
self, direct_message, pub_id
);
Err(RoutingError::InvalidStateForOperation)
}
/// Handles a signature of a `SignedMessage`, and if we have enough to verify the signed
/// message, handles it.
fn handle_message_signature(
&mut self,
digest: Digest256,
sig: Signature,
pub_id: PublicId,
) -> Result<(), RoutingError> {
if !self
.peer_mgr
.get_peer(&pub_id)
.map_or(false, Peer::is_routing)
{
debug!(
"{} Received message signature from unknown peer {}",
self, pub_id
);
return Err(RoutingError::UnknownConnection(pub_id));
}
let min_section_size = self.min_section_size();
let proof = Proof { sig, pub_id };
if let Some((signed_msg, route)) =
self.sig_accumulator
.add_proof(min_section_size, digest, proof)
{
let hop = *self.name(); // we accumulated the message, so now we act as the last hop
self.handle_signed_message(signed_msg, route, hop, &BTreeSet::new())?;
}
Ok(())
}
// Verify the message, then, if it is for us, handle the enclosed routing message and swarm it
// to the rest of our section when destination is targeting multiple; if not, forward it.
fn handle_signed_message(
&mut self,
mut signed_msg: SignedMessage,
route: u8,
hop_name: XorName,
sent_to: &BTreeSet<XorName>,
) -> Result<(), RoutingError> {
signed_msg.check_integrity(self.min_section_size())?;
if signed_msg.routing_message().src.is_client() {
if signed_msg.previous_hop().is_some() {
warn!("{} Unexpected section infos in {:?}", self, signed_msg);
return Err(RoutingError::InvalidProvingSection);
}
} else {
// Remove any untrusted trailing section infos.
// TODO: remove wasted clone. Only useful when msg isnt trusted for log msg.
let msg_clone = signed_msg.clone();
while match signed_msg.previous_hop() {
None => true,
Some(hop) => !self.is_trusted(hop)?,
} {
// We don't know the last hop! Try the one before that.
if !signed_msg.pop_previous_hop() {
debug!("{} Untrusted message: {:?}", self, msg_clone);
return Err(RoutingError::NotEnoughSignatures);
}
}
// Now that we validated the sections, inform our peers about any new ones.
if signed_msg
.section_infos()
.any(|si| self.chain.is_new_neighbour(si))
{
if let Some(si) = signed_msg.source_section() {
// TODO: Why is `add_new_sections` still necessary? The vote should suffice.
// TODO: This is enabled for relayed messages only because it considerably
// slows down the tests. Find out why, maybe enable it in more cases.
if self.add_new_sections(signed_msg.section_infos())
&& !self.in_authority(&signed_msg.routing_message().dst)
{
let ps = signed_msg.proving_sections().clone();
self.vote_for_event(NetworkEvent::ProvingSections(ps, si.clone()));
}
}
}
}
let filter_res = self
.routing_msg_filter
.filter_incoming(signed_msg.routing_message(), route);
if filter_res == FilteringResult::KnownMessageAndRoute {
return Ok(());
};
if self.in_authority(&signed_msg.routing_message().dst) {
self.send_ack(signed_msg.routing_message(), route);
if signed_msg.routing_message().dst.is_multiple() {
// Broadcast to the rest of the section.
if let Err(error) =
self.send_signed_message(&mut signed_msg, route, &hop_name, sent_to)
{
debug!("{} Failed to send {:?}: {:?}", self, signed_msg, error);
}
}
if filter_res == FilteringResult::NewMessage {
// if addressed to us, then we just queue it and return
self.msg_queue.push_back(signed_msg.into_routing_message());
}
return Ok(());
}
if self.respond_from_cache(signed_msg.routing_message(), route)? {
return Ok(());
}
if let Err(error) = self.send_signed_message(&mut signed_msg, route, &hop_name, sent_to) {
debug!("{} Failed to send {:?}: {:?}", self, signed_msg, error);
}
Ok(())
}
fn dispatch_routing_message(
&mut self,
routing_msg: RoutingMessage,
outbox: &mut EventBox,
) -> Result<(), RoutingError> {
use crate::messages::MessageContent::*;
use crate::Authority::{Client, ManagedNode, PrefixSection, Section};
match routing_msg.content {
Ack(..) | UserMessagePart { .. } => (),
_ => trace!("{} Got routing message {:?}.", self, routing_msg),
}
match (routing_msg.content, routing_msg.src, routing_msg.dst) {
(
Relocate { message_id },
Client {
client_id,
proxy_node_name,
},
Section(dst_name),
) => self.handle_relocate_request(client_id, proxy_node_name, dst_name, message_id),
(
ExpectCandidate {
old_public_id,
old_client_auth,
message_id,
},
Section(_),
relocation_dst @ Section(_),
) => self.handle_expect_candidate(
old_public_id,
old_client_auth,
relocation_dst,
message_id,
),
(
AcceptAsCandidate {
old_public_id,
old_client_auth,
target_interval,
message_id,
},
Section(_),
dst @ Section(_),
) => self.handle_accept_as_candidate(
old_public_id,
old_client_auth,
dst,
target_interval,
message_id,
),
(
ConnectionInfoRequest {
encrypted_conn_info,
pub_id,
msg_id,
},
src @ Client { .. },
dst @ ManagedNode(_),
)
| (
ConnectionInfoRequest {
encrypted_conn_info,
pub_id,
msg_id,
},
src @ ManagedNode(_),
dst @ ManagedNode(_),
)
| (
ConnectionInfoRequest {
encrypted_conn_info,
pub_id,
msg_id,
},
src @ ManagedNode(_),
dst @ Client { .. },
) => self.handle_connection_info_request(
encrypted_conn_info,
pub_id,
msg_id,
src,
dst,
outbox,
),
(
ConnectionInfoResponse {
encrypted_conn_info,
pub_id,
msg_id,
},
ManagedNode(src_name),
dst @ Client { .. },
)
| (
ConnectionInfoResponse {
encrypted_conn_info,
pub_id,
msg_id,
},
ManagedNode(src_name),
dst @ ManagedNode(_),
) => self.handle_connection_info_response(
encrypted_conn_info,
pub_id,
msg_id,
src_name,
dst,
),
(NeighbourInfo(_digest), ManagedNode(_), PrefixSection(_)) => Ok(()),
(
NeighbourConfirm(digest, proofs, sec_infos_and_proofs),
ManagedNode(_),
Section(_),
) => self.handle_neighbour_confirm(digest, proofs, sec_infos_and_proofs),
(Merge(digest), PrefixSection(_), PrefixSection(_)) => self.handle_merge(digest),
(Ack(ack, _), _, _) => {
self.handle_ack_response(ack);
Ok(())
}
(
UserMessagePart {
hash,
part_count,
part_index,
payload,
..
},
src,
dst,
) => {
if let Some(msg) = self
.user_msg_cache
.add(hash, part_count, part_index, payload)
{
outbox.send_event(msg.into_event(src, dst));
}
Ok(())
}
(content, src, dst) => {
debug!(
"{} Unhandled routing message {:?} from {:?} to {:?}",
self, content, src, dst
);
Err(RoutingError::BadAuthority)
}
}
}
fn handle_candidate_approval(
&mut self,
new_pub_id: PublicId,
new_client_auth: Authority<XorName>,
outbox: &mut EventBox,
) -> Result<(), RoutingError> {
self.remove_expired_peers();
// Once the joining node joined, it may receive the vote regarding itself.
// Or a node may receive CandidateApproval before connection established.
// If we are not connected to the candidate, we do not want to add them
// to our RT.
// This will flag peer as valid if its found in peer_mgr regardless of their
// connection status to us.
let is_connected = match self.peer_mgr.handle_candidate_approval(&new_pub_id) {
Ok(is_connected) => is_connected,
Err(_) => {
let src = Authority::ManagedNode(*self.name());
if let Err(error) =
self.send_connection_info_request(new_pub_id, src, new_client_auth, outbox)
{
debug!(
"{} - Failed to send connection info to {}: {:?}",
self, new_pub_id, error
);
}
false
}
};
info!(
"{} Our section with {:?} has approved candidate {}.",
self,
self.our_prefix(),
new_pub_id
);
let trimmed_info = GenesisPfxInfo {
first_info: self.gen_pfx_info.first_info.clone(),
latest_info: self.chain.our_info().clone(),
};
let src = Authority::PrefixSection(*trimmed_info.first_info.prefix());
let content = MessageContent::NodeApproval(trimmed_info);
if let Err(error) = self.send_routing_message(src, new_client_auth, content) {
debug!(
"{} Failed sending NodeApproval to {}: {:?}",
self, new_pub_id, error
);
}
if is_connected {
self.add_to_routing_table(&new_pub_id, outbox);
}
Ok(())
}
fn init_parsec(&mut self) {
let log_ident = format!("{}", self);
self.parsec_map
.init(self.full_id.clone(), &self.gen_pfx_info, &log_ident)
}
fn handle_resource_proof_response(
&mut self,
pub_id: PublicId,
part_index: usize,
part_count: usize,
proof: Vec<u8>,
leading_zero_bytes: u64,
) {
if self.candidate_timer_token.is_none() {
debug!(
"{} Won't handle resource proof response from {:?} - not currently waiting.",
self, pub_id
);
return;
}
match self.peer_mgr.verify_candidate(
&pub_id,
part_index,
part_count,
proof,
leading_zero_bytes,
) {
Err(error) => {
debug!(
"{} Failed to verify candidate {}: {:?}",
self, pub_id, error
);
}
Ok(None) => {
self.send_direct_message(pub_id, DirectMessage::ResourceProofResponseReceipt);
}
Ok(Some((target_size, difficulty, elapsed)))
if difficulty == 0 && target_size < 1000 =>
{
// Small tests don't require waiting for synchronisation. Send approval now.
info!(
"{} Candidate {} passed our challenge in {}. Sending approval \
to our section with {:?}.",
self,
pub_id,
elapsed.display_secs(),
self.our_prefix()
);
// We set the timer token to None so we do not send another
// CandidateApproval when the token fires
self.candidate_timer_token = None;
self.send_candidate_approval();
}
Ok(Some((_, _, elapsed))) => {
info!(
"{} Candidate {} passed our challenge in {}. Waiting to send approval to \
our section with {:?}.",
self,
pub_id,
elapsed.display_secs(),
self.our_prefix()
);
}
}
}
/// Returns `Ok` with rate_limiter charged size if client is allowed to send the given message.
fn check_valid_client_message(
&mut self,
ip: &IpAddr,
msg: &RoutingMessage,
) -> Result<u64, RoutingError> {
match (&msg.src, &msg.content) {
(
&Authority::Client { .. },
&MessageContent::UserMessagePart {
ref hash,
ref msg_id,
ref part_count,
ref part_index,
ref priority,
ref payload,
..
},
) if *part_count <= MAX_PARTS
&& part_index < part_count
&& *priority >= DEFAULT_PRIORITY
&& payload.len() <= MAX_PART_LEN =>
{
self.clients_rate_limiter.add_message(
ip,
hash,
msg_id,
*part_count,
*part_index,
payload,
)
}
_ => {
debug!(
"{} Illegitimate client message {:?}. Refusing to relay.",
self, msg
);
Err(RoutingError::RejectedClientMessage)
}
}
}
fn correct_rate_limits(&mut self, ip: &IpAddr, msg: &RoutingMessage) -> Option<u64> {
if let MessageContent::UserMessagePart {
ref msg_id,
part_count,
part_index,
ref payload,
..
} = msg.content
{
self.clients_rate_limiter
.apply_refund_for_response(ip, msg_id, part_count, part_index, payload)
} else {
None
}
}
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;
let msg = UserMessage::Response(response);
self.send_ack_from(routing_msg, route, src);
self.send_user_message(src, dst, msg, priority)?;
return Ok(true);
}
}
Some(UserMessage::Response(response)) => {
debug!("{} Putting {:?} in cache", self, response);
self.response_cache.put(response);
}