-
Notifications
You must be signed in to change notification settings - Fork 64
/
service.rs
1698 lines (1572 loc) · 71.6 KB
/
service.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! The Discovery v5 protocol. See `lib.rs` for further details.
//!
//! Note: Discovered ENR's are not automatically added to the routing table. Only established
//! sessions get added, ensuring only valid ENRs are added. Manual additions can be made using the
//! `add_enr()` function.
//!
//! Response to queries return `PeerId`. Only the trusted (a session has been established with)
//! `PeerId`'s are returned, as ENR's for these `PeerId`'s are stored in the routing table and as
//! such should have an address to connect to. Untrusted `PeerId`'s can be obtained from the
//! `Service::Discovered` event, which is fired as peers get discovered.
//!
//! Note that although the ENR crate does support Ed25519 keys, these are currently not
//! supported as the ECDH procedure isn't specified in the specification. Therefore, only
//! secp256k1 keys are supported currently.
use self::{
ip_vote::IpVote,
query_info::{QueryInfo, QueryType},
};
use crate::{
error::{RequestError, ResponseError},
handler::{Handler, HandlerIn, HandlerOut},
kbucket::{
self, ConnectionDirection, ConnectionState, FailureReason, InsertResult, KBucketsTable,
NodeStatus, UpdateResult, MAX_NODES_PER_BUCKET,
},
node_info::{NodeAddress, NodeContact, NonContactable},
packet::{ProtocolIdentity, MAX_PACKET_SIZE},
query_pool::{
FindNodeQueryConfig, PredicateQueryConfig, QueryId, QueryPool, QueryPoolState, TargetKey,
},
rpc, Config, Enr, Event, IpMode,
};
use connectivity_state::{
ConnectivityState, TimerFailure, DURATION_UNTIL_NEXT_CONNECTIVITY_ATTEMPT,
};
use delay_map::HashSetDelay;
use enr::{CombinedKey, NodeId};
use fnv::FnvHashMap;
use futures::prelude::*;
use more_asserts::debug_unreachable;
use parking_lot::RwLock;
use rpc::*;
use std::{
collections::HashMap,
convert::TryInto,
net::{IpAddr, SocketAddr},
sync::Arc,
task::Poll,
time::Instant,
};
use tokio::sync::{mpsc, oneshot};
use tracing::{debug, error, info, trace, warn};
mod connectivity_state;
mod ip_vote;
mod query_info;
mod test;
/// The number of distances (buckets) we simultaneously request from each peer.
/// NOTE: This must not be larger than 127.
pub(crate) const DISTANCES_TO_REQUEST_PER_PEER: usize = 3;
/// Currently, a maximum of `DISTANCES_TO_REQUEST_PER_PEER * BUCKET_SIZE` peers
/// can be returned. Datagrams have a max size of 1280 and ENR's have a max size
/// of 300 bytes. Bucket sizes should be 16. Therefore, to return all required peers
/// there should be no more than `5 * DISTANCES_TO_REQUEST_PER_PEER` responses.
pub(crate) const MAX_NODES_RESPONSES: usize =
(MAX_NODES_PER_BUCKET / 4 + 1) * DISTANCES_TO_REQUEST_PER_PEER;
/// Request type for Protocols using `TalkReq` message.
///
/// Automatically responds with an empty body on drop if
/// [`TalkRequest::respond`] is not called.
#[derive(Debug)]
pub struct TalkRequest {
id: RequestId,
node_address: NodeAddress,
protocol: Vec<u8>,
body: Vec<u8>,
sender: Option<mpsc::UnboundedSender<HandlerIn>>,
}
impl Drop for TalkRequest {
fn drop(&mut self) {
let sender = match self.sender.take() {
Some(s) => s,
None => return,
};
let response = Response {
id: self.id.clone(),
body: ResponseBody::Talk { response: vec![] },
};
debug!(node_address = %self.node_address, "Sending empty TALK response");
if let Err(e) = sender.send(HandlerIn::Response(
self.node_address.clone(),
Box::new(response),
)) {
warn!(error = %e,"Failed to send empty talk response")
}
}
}
impl TalkRequest {
pub fn id(&self) -> &RequestId {
&self.id
}
pub fn node_id(&self) -> &NodeId {
&self.node_address.node_id
}
pub fn protocol(&self) -> &[u8] {
&self.protocol
}
pub fn body(&self) -> &[u8] {
&self.body
}
pub fn respond(mut self, response: Vec<u8>) -> Result<(), ResponseError> {
debug!(node_address = %self.node_address, "Sending TALK response");
let response = Response {
id: self.id.clone(),
body: ResponseBody::Talk { response },
};
self.sender
.take()
.unwrap()
.send(HandlerIn::Response(
self.node_address.clone(),
Box::new(response),
))
.map_err(|_| ResponseError::ChannelClosed)?;
Ok(())
}
}
/// The types of requests to send to the Discv5 service.
pub enum ServiceRequest {
/// A request to start a query. There are two types of queries:
/// - A FindNode Query - Searches for peers using a random target.
/// - A Predicate Query - Searches for peers closest to a random target that match a specified
/// predicate.
StartQuery(QueryKind, oneshot::Sender<Vec<Enr>>),
/// Send a FINDNODE request for nodes that fall within the given set of distances,
/// to the designated peer and wait for a response.
FindNodeDesignated(
NodeContact,
Vec<u64>,
oneshot::Sender<Result<Vec<Enr>, RequestError>>,
),
/// The TALK discv5 RPC function.
Talk(
NodeContact,
Vec<u8>,
Vec<u8>,
oneshot::Sender<Result<Vec<u8>, RequestError>>,
),
/// The PING discv5 RPC function.
Ping(Enr, Option<oneshot::Sender<Result<Pong, RequestError>>>),
/// Sets up an event stream where the discv5 server will return various events such as
/// discovered nodes as it traverses the DHT.
RequestEventStream(oneshot::Sender<mpsc::Receiver<Event>>),
}
use crate::discv5::PERMIT_BAN_LIST;
pub struct Service {
/// Configuration parameters.
config: Config,
/// The local ENR of the server.
local_enr: Arc<RwLock<Enr>>,
/// The key associated with the local ENR.
enr_key: Arc<RwLock<CombinedKey>>,
/// Storage of the ENR record for each node.
kbuckets: Arc<RwLock<KBucketsTable<NodeId, Enr>>>,
/// All the iterative queries we are currently performing.
queries: QueryPool<QueryInfo, NodeId, Enr>,
/// RPC requests that have been sent and are awaiting a response. Some requests are linked to a
/// query.
active_requests: FnvHashMap<RequestId, ActiveRequest>,
/// Keeps track of the number of responses received from a NODES response.
active_nodes_responses: HashMap<RequestId, NodesResponse>,
/// A map of votes nodes have made about our external IP address. We accept the majority.
ip_votes: Option<IpVote>,
/// The channel to send messages to the handler.
handler_send: mpsc::UnboundedSender<HandlerIn>,
/// The channel to receive messages from the handler.
handler_recv: mpsc::Receiver<HandlerOut>,
/// The exit channel to shutdown the handler.
handler_exit: Option<oneshot::Sender<()>>,
/// The channel of messages sent by the controlling discv5 wrapper.
discv5_recv: mpsc::Receiver<ServiceRequest>,
/// The exit channel for the service.
exit: oneshot::Receiver<()>,
/// A queue of peers that require regular ping to check connectivity.
peers_to_ping: HashSetDelay<NodeId>,
/// A channel that the service emits events on.
event_stream: Option<mpsc::Sender<Event>>,
/// Type of socket we are using
ip_mode: IpMode,
/// This stores information about whether we think we have open ports and if we are externally
/// contactable or not. This decides if we should update our ENR or set it to None, if we are
/// not contactable.
connectivity_state: ConnectivityState,
}
/// Active RPC request awaiting a response from the handler.
struct ActiveRequest {
/// The address the request was sent to.
pub contact: NodeContact,
/// The request that was sent.
pub request_body: RequestBody,
/// The query ID if the request was related to a query.
pub query_id: Option<QueryId>,
/// Channel callback if this request was from a user level request.
pub callback: Option<CallbackResponse>,
}
#[derive(Debug)]
pub struct Pong {
/// The current ENR sequence number of the responder.
pub enr_seq: u64,
/// Our external IP address as observed by the responder.
pub ip: IpAddr,
/// Our external UDP port as observed by the responder.
pub port: u16,
}
/// The kinds of responses we can send back to the discv5 layer.
pub enum CallbackResponse {
/// A response to a requested Nodes.
Nodes(oneshot::Sender<Result<Vec<Enr>, RequestError>>),
/// A response from a TALK request
Talk(oneshot::Sender<Result<Vec<u8>, RequestError>>),
/// A response from a Pong request
Pong(oneshot::Sender<Result<Pong, RequestError>>),
}
/// For multiple responses to a FindNodes request, this keeps track of the request count
/// and the nodes that have been received.
struct NodesResponse {
/// The response count.
count: usize,
/// The filtered nodes that have been received.
received_nodes: Vec<Enr>,
}
impl Default for NodesResponse {
fn default() -> Self {
NodesResponse {
count: 1,
received_nodes: Vec::new(),
}
}
}
impl Service {
/// Builds the `Service` main struct.
///
/// `local_enr` is the `ENR` representing the local node. This contains node identifying information, such
/// as IP addresses and ports which we wish to broadcast to other nodes via this discovery
/// mechanism.
pub async fn spawn<P: ProtocolIdentity>(
local_enr: Arc<RwLock<Enr>>,
enr_key: Arc<RwLock<CombinedKey>>,
kbuckets: Arc<RwLock<KBucketsTable<NodeId, Enr>>>,
config: Config,
) -> Result<(oneshot::Sender<()>, mpsc::Sender<ServiceRequest>), std::io::Error> {
// process behaviour-level configuration parameters
let ip_votes = if config.enr_update {
Some(IpVote::new(
config.enr_peer_update_min,
config.vote_duration,
))
} else {
None
};
let ip_mode = IpMode::new_from_listen_config(&config.listen_config);
// build the session service
let (handler_exit, handler_send, handler_recv) =
Handler::spawn::<P>(local_enr.clone(), enr_key.clone(), config.clone()).await?;
// create the required channels
let (discv5_send, discv5_recv) = mpsc::channel(30);
let (exit_send, exit) = oneshot::channel();
let connectivity_state = ConnectivityState::new(config.auto_nat_listen_duration);
config
.executor
.clone()
.expect("Executor must be present")
.spawn(Box::pin(async move {
let mut service = Service {
local_enr,
enr_key,
kbuckets,
queries: QueryPool::new(config.query_timeout),
active_requests: Default::default(),
active_nodes_responses: HashMap::new(),
ip_votes,
handler_send,
handler_recv,
handler_exit: Some(handler_exit),
peers_to_ping: HashSetDelay::new(config.ping_interval),
discv5_recv,
event_stream: None,
exit,
config: config.clone(),
ip_mode,
connectivity_state,
};
info!(mode = ?service.ip_mode, "Discv5 Service started");
service.start().await;
}));
Ok((exit_send, discv5_send))
}
/// The main execution loop of the discv5 serviced.
async fn start(&mut self) {
loop {
tokio::select! {
_ = &mut self.exit => {
if let Some(exit) = self.handler_exit.take() {
let _ = exit.send(());
info!("Discv5 Service shutdown");
}
return;
}
Some(service_request) = self.discv5_recv.recv() => {
match service_request {
ServiceRequest::StartQuery(query, callback) => {
match query {
QueryKind::FindNode { target_node } => {
self.start_findnode_query(target_node, callback);
}
QueryKind::Predicate { target_node, target_peer_no, predicate } => {
self.start_predicate_query(target_node, target_peer_no, predicate, callback);
}
}
}
ServiceRequest::FindNodeDesignated(node_contact, distance, callback) => {
self.request_find_node_designated_peer(node_contact, distance, Some(callback));
}
ServiceRequest::Talk(node_contact, protocol, request, callback) => {
self.talk_request(node_contact, protocol, request, callback);
}
ServiceRequest::Ping(enr, callback) => {
self.send_ping(enr, callback);
}
ServiceRequest::RequestEventStream(callback) => {
// the channel size needs to be large to handle many discovered peers
// if we are reporting them on the event stream.
let channel_size = if self.config.report_discovered_peers { 100 } else { 30 };
let (event_stream, event_stream_recv) = mpsc::channel(channel_size);
self.event_stream = Some(event_stream);
if callback.send(event_stream_recv).is_err() {
error!("Failed to return the event stream channel");
}
}
}
}
Some(event) = self.handler_recv.recv() => {
match event {
HandlerOut::Established(enr, socket_addr, direction) => {
self.inject_session_established(enr.clone(), &socket_addr, direction);
self.send_event(Event::SessionEstablished(enr, socket_addr));
}
HandlerOut::Request(node_address, request) => {
self.handle_rpc_request(node_address, *request);
}
HandlerOut::Response(node_address, response) => {
self.handle_rpc_response(node_address, *response);
}
HandlerOut::WhoAreYou(whoareyou_ref) => {
// check what our latest known ENR is for this node.
if let Some(known_enr) = self.find_enr(&whoareyou_ref.0.node_id) {
if let Err(e) = self.handler_send.send(HandlerIn::WhoAreYou(whoareyou_ref, Some(known_enr))) {
warn!(error = %e, "Failed to send whoareyou");
};
} else {
// do not know of this peer
debug!(node_address = %whoareyou_ref.0, "NodeId unknown, requesting ENR.");
if let Err(e) = self.handler_send.send(HandlerIn::WhoAreYou(whoareyou_ref, None)) {
warn!(error = %e, "Failed to send who are you to unknown enr peer");
}
}
}
HandlerOut::RequestFailed(request_id, error) => {
if let RequestError::Timeout = error {
debug!(id = %request_id, "RPC Request timed out");
} else {
warn!(id = %request_id, ?error, "RPC Request failed");
}
self.rpc_failure(request_id, error);
}
HandlerOut::UnverifiableEnr{enr, socket, node_id} => {
// We have received an ENR that has incorrect socket address fields
// (given the source of the pakcet we received.
// If this node exists in our routing table, remove it, as it may have shifted
// ip addresses and is now no longer contactable.
let key = kbucket::Key::from(node_id);
if self.kbuckets.write().remove(&key) {
debug!(?node_id, "Uncontactable node removed from routing table");
}
self.send_event(Event::UnverifiableEnr{enr, socket, node_id});
}
}
}
event = Service::bucket_maintenance_poll(&self.kbuckets) => {
self.send_event(event);
}
query_event = Service::query_event_poll(&mut self.queries) => {
match query_event {
QueryEvent::Waiting(query_id, node_id, request_body) => {
self.send_rpc_query(query_id, node_id, request_body);
}
// Note: Currently the distinction between a timed-out query and a finished
// query is superfluous, however it may be useful in future versions.
QueryEvent::Finished(query) | QueryEvent::TimedOut(query) => {
let id = query.id();
let mut result = query.into_result();
// obtain the ENR's for the resulting nodes
let mut found_enrs = Vec::new();
for node_id in result.closest_peers {
if let Some(position) = result.target.untrusted_enrs.iter().position(|enr| enr.node_id() == node_id) {
let enr = result.target.untrusted_enrs.swap_remove(position);
found_enrs.push(enr);
} else if let Some(enr) = self.find_enr(&node_id) {
// look up from the routing table
found_enrs.push(enr);
}
else {
warn!("ENR not present in queries results");
}
}
if result.target.callback.send(found_enrs).is_err() {
warn!(query_id = *id, "Callback dropped for query. Results dropped");
}
}
}
}
Some(Ok(node_id)) = self.peers_to_ping.next() => {
// If the node is in the routing table, Ping it and re-queue the node.
let key = kbucket::Key::from(node_id);
let enr = {
if let kbucket::Entry::Present(entry, _) = self.kbuckets.write().entry(&key) {
// The peer is in the routing table, ping it and re-queue the ping
self.peers_to_ping.insert(node_id);
Some(entry.value().clone())
} else { None }
};
if let Some(enr) = enr {
self.send_ping(enr, None);
}
}
connectivity_timeout = self.connectivity_state.poll() => {
let updated_enr = match connectivity_timeout {
TimerFailure::V4 => {
// We have not received enough incoming connections in the required
// time. Remove our ENR advertisement.
info!(ip_version="v4", next_attempt_in=%DURATION_UNTIL_NEXT_CONNECTIVITY_ATTEMPT.as_secs(), "UDP Socket removed from ENR");
if let Err(error) = self.local_enr.write().remove_udp_socket(&self.enr_key.read()) {
error!(?error, "Failed to update the ENR");
false
} else {
// ENR was updated
true
}
}
TimerFailure::V6 => {
// We have not received enough incoming connections in the required
// time. Remove our ENR advertisement.
info!(ip_version="v6", next_attempt_in=%DURATION_UNTIL_NEXT_CONNECTIVITY_ATTEMPT.as_secs(), "UDP Socket removed from ENR");
if let Err(error) = self.local_enr.write().remove_udp6_socket(&self.enr_key.read()) {
error!(?error, "Failed to update the ENR");
false
} else {
// ENR was updated
true
}
}
};
if updated_enr {
// Inform our known peers of our updated ENR
self.ping_connected_peers();
}
}
}
}
}
/// Internal function that starts a query.
fn start_findnode_query(&mut self, target_node: NodeId, callback: oneshot::Sender<Vec<Enr>>) {
let mut target = QueryInfo {
query_type: QueryType::FindNode(target_node),
untrusted_enrs: Default::default(),
distances_to_request: DISTANCES_TO_REQUEST_PER_PEER,
callback,
};
let target_key: kbucket::Key<NodeId> = target.key();
let mut known_closest_peers = Vec::new();
{
let mut kbuckets = self.kbuckets.write();
for closest in kbuckets.closest_values(&target_key) {
// Add the known ENR's to the untrusted list
target.untrusted_enrs.push(closest.value);
// Add the key to the list for the query
known_closest_peers.push(closest.key);
}
}
if known_closest_peers.is_empty() {
warn!("No known_closest_peers found. Return empty result without sending query.");
if target.callback.send(vec![]).is_err() {
warn!("Failed to callback");
}
} else {
let query_config = FindNodeQueryConfig::new_from_config(&self.config);
self.queries
.add_findnode_query(query_config, target, known_closest_peers);
}
}
/// Internal function that starts a query.
fn start_predicate_query(
&mut self,
target_node: NodeId,
num_nodes: usize,
predicate: Box<dyn Fn(&Enr) -> bool + Send>,
callback: oneshot::Sender<Vec<Enr>>,
) {
let mut target = QueryInfo {
query_type: QueryType::FindNode(target_node),
untrusted_enrs: Default::default(),
distances_to_request: DISTANCES_TO_REQUEST_PER_PEER,
callback,
};
let target_key: kbucket::Key<NodeId> = target.key();
// Map the TableEntry to an ENR.
let kbucket_predicate = |e: &Enr| predicate(e);
let mut known_closest_peers = Vec::<kbucket::PredicateKey<_>>::new();
{
let mut kbuckets = self.kbuckets.write();
for closest in kbuckets.closest_values_predicate(&target_key, &kbucket_predicate) {
let (node_id_predicate, enr) = closest.to_key_value();
// Add the known ENR's to the untrusted list
target.untrusted_enrs.push(enr);
// Add the key to the list for the query
known_closest_peers.push(node_id_predicate);
}
};
if known_closest_peers.is_empty() {
warn!("No known_closest_peers found. Return empty result without sending query.");
if target.callback.send(vec![]).is_err() {
warn!("Failed to callback");
}
} else {
let mut query_config = PredicateQueryConfig::new_from_config(&self.config);
query_config.num_results = num_nodes;
self.queries
.add_predicate_query(query_config, target, known_closest_peers, predicate);
}
}
/// Returns an ENR if one is known for the given NodeId.
pub fn find_enr(&self, node_id: &NodeId) -> Option<Enr> {
// check if we know this node id in our routing table
let key = kbucket::Key::from(*node_id);
if let kbucket::Entry::Present(entry, _) = self.kbuckets.write().entry(&key) {
return Some(entry.value().clone());
}
// check the untrusted addresses for ongoing queries
for query in self.queries.iter() {
if let Some(enr) = query
.target()
.untrusted_enrs
.iter()
.find(|v| v.node_id() == *node_id)
{
return Some(enr.clone());
}
}
None
}
/// Processes an RPC request from a peer. Requests respond to the received socket address,
/// rather than the IP of the known ENR.
fn handle_rpc_request(&mut self, node_address: NodeAddress, req: Request) {
let id = req.id;
match req.body {
RequestBody::FindNode { distances } => {
self.send_nodes_response(node_address, id, distances);
}
RequestBody::Ping { enr_seq } => {
// check if we need to update the known ENR
let mut to_request_enr = None;
match self.kbuckets.write().entry(&node_address.node_id.into()) {
kbucket::Entry::Present(ref mut entry, _) => {
if entry.value().seq() < enr_seq {
let enr = entry.value().clone();
to_request_enr = Some(enr);
}
}
kbucket::Entry::Pending(ref mut entry, _) => {
if entry.value().seq() < enr_seq {
let enr = entry.value().clone();
to_request_enr = Some(enr);
}
}
// don't know the peer, don't request its most recent ENR
_ => {}
}
if let Some(enr) = to_request_enr {
match NodeContact::try_from_enr(enr, self.ip_mode) {
Ok(contact) => {
self.request_find_node_designated_peer(contact, vec![0], None);
}
Err(NonContactable { enr }) => {
debug_unreachable!("Stored ENR is not contactable. {}", enr);
error!(
%enr,
"Stored ENR is not contactable! This should never happen",
);
}
}
}
// build the PONG response
let src = node_address.socket_addr;
if let Ok(port) = src.port().try_into() {
let response = Response {
id,
body: ResponseBody::Pong {
enr_seq: self.local_enr.read().seq(),
ip: src.ip(),
port,
},
};
debug!(%node_address, "Sending PONG response");
if let Err(e) = self
.handler_send
.send(HandlerIn::Response(node_address, Box::new(response)))
{
warn!(error = %e, "Failed to send response");
}
} else {
warn!(%src, "The src port number should be non zero");
}
}
RequestBody::Talk { protocol, request } => {
let req = TalkRequest {
id,
node_address,
protocol,
body: request,
sender: Some(self.handler_send.clone()),
};
self.send_event(Event::TalkRequest(req));
}
}
}
/// Processes an RPC response from a peer.
fn handle_rpc_response(&mut self, node_address: NodeAddress, response: Response) {
// verify we know of the rpc_id
let id = response.id.clone();
let Some(mut active_request) = self.active_requests.remove(&id) else {
warn!(%id, "Received an RPC response which doesn't match a request");
return;
};
debug!(
response = %response.body,
request = %active_request.request_body,
from = %active_request.contact,
"Received RPC response",
);
// Check that the responder matches the expected request
let expected_node_address = active_request.contact.node_address();
if expected_node_address != node_address {
debug_unreachable!("Handler returned a response not matching the used socket addr");
return error!(
expected = %expected_node_address,
received = %node_address,
request_id = %id,
"Received a response from an unexpected address",
);
}
if !response.match_request(&active_request.request_body) {
warn!(
%node_address,
"Node gave an incorrect response type. Ignoring response"
);
return;
}
let node_id = node_address.node_id;
match response.body {
ResponseBody::Nodes { total, mut nodes } => {
if total > MAX_NODES_RESPONSES as u64 {
warn!(
total,
"NodesResponse has a total larger than {}, nodes will be truncated",
MAX_NODES_RESPONSES
);
}
// These are sanitized and ordered
let distances_requested = match &active_request.request_body {
RequestBody::FindNode { distances } => distances,
_ => unreachable!(),
};
if let Some(CallbackResponse::Nodes(callback)) = active_request.callback.take() {
if let Err(e) = callback.send(Ok(nodes)) {
warn!(error = ?e, "Failed to send response in callback")
}
return;
}
// Filter out any nodes that are not of the correct distance
let peer_key: kbucket::Key<NodeId> = node_id.into();
// The distances we send are sanitized an ordered.
// We never send an ENR request in combination of other requests.
if distances_requested.len() == 1 && distances_requested[0] == 0 {
// we requested an ENR update
if nodes.len() > 1 {
warn!(
%node_address,
"Peer returned more than one ENR for itself. Blacklisting",
);
let ban_timeout = self.config.ban_duration.map(|v| Instant::now() + v);
PERMIT_BAN_LIST.write().ban(node_address, ban_timeout);
nodes.retain(|enr| peer_key.log2_distance(&enr.node_id().into()).is_none());
}
} else {
let before_len = nodes.len();
nodes.retain(|enr| {
peer_key
.log2_distance(&enr.node_id().into())
.map(|distance| distances_requested.contains(&distance))
.unwrap_or_else(|| false)
});
if nodes.len() < before_len {
// Peer sent invalid ENRs. Blacklist the Node
let node_id = active_request.contact.node_id();
let addr = active_request.contact.socket_addr();
warn!(%node_id, %addr, "ENRs received of unsolicited distances. Blacklisting");
let ban_timeout = self.config.ban_duration.map(|v| Instant::now() + v);
PERMIT_BAN_LIST.write().ban(node_address, ban_timeout);
}
}
// handle the case that there is more than one response
if total > 1 {
let mut current_response =
self.active_nodes_responses.remove(&id).unwrap_or_default();
debug!(
"Nodes Response: {} of {} received",
current_response.count, total
);
// If there are more requests coming, store the nodes and wait for
// another response
// If we have already received all our required nodes, drop any extra
// rpc messages.
if current_response.received_nodes.len() < self.config.max_nodes_response
&& (current_response.count as u64) < total
&& current_response.count < MAX_NODES_RESPONSES
{
current_response.count += 1;
current_response.received_nodes.append(&mut nodes);
self.active_nodes_responses
.insert(id.clone(), current_response);
self.active_requests.insert(id, active_request);
return;
}
// have received all the Nodes responses we are willing to accept
// ignore duplicates here as they will be handled when adding
// to the DHT
current_response.received_nodes.append(&mut nodes);
nodes = current_response.received_nodes;
}
debug!(
len = nodes.len(),
total,
from = %active_request.contact,
"Received a nodes response",
);
// note: If a peer sends an initial NODES response with a total > 1 then
// in a later response sends a response with a total of 1, all previous nodes
// will be ignored.
// ensure any mapping is removed in this rare case
self.active_nodes_responses.remove(&id);
self.discovered(&node_id, nodes, active_request.query_id);
}
ResponseBody::Pong { enr_seq, ip, port } => {
// Send the response to the user, if they are who asked
if let Some(CallbackResponse::Pong(callback)) = active_request.callback {
let response = Pong {
enr_seq,
ip,
port: port.get(),
};
if let Err(e) = callback.send(Ok(response)) {
warn!(error = ?e, "Failed to send callback response")
};
return;
}
let socket = SocketAddr::new(ip, port.get());
// Register the vote, this counts towards potentially updating the ENR for external
// advertisement
self.handle_ip_vote_from_pong(node_id, socket);
// check if we need to request a new ENR
if let Some(enr) = self.find_enr(&node_id) {
if enr.seq() < enr_seq {
// request an ENR update
debug!(from = %active_request.contact, "Requesting an ENR update");
let request_body = RequestBody::FindNode { distances: vec![0] };
let active_request = ActiveRequest {
contact: active_request.contact,
request_body,
query_id: None,
callback: None,
};
self.send_rpc_request(active_request);
}
// Only update the routing table if the new ENR is contactable
if self.ip_mode.get_contactable_addr(&enr).is_some() {
self.connection_updated(node_id, ConnectionStatus::PongReceived(enr));
}
}
}
ResponseBody::Talk { response } => {
// Send the response to the user
match active_request.callback {
Some(CallbackResponse::Talk(callback)) => {
if let Err(e) = callback.send(Ok(response)) {
warn!(error = ?e, "Failed to send callback response")
};
}
_ => error!("Invalid callback for response"),
}
}
}
}
// We have received a PONG which informs us for our external socket. This function decides
// how we should handle this vote and whether or not to update our ENR. This is done on a
// majority-based voting system, see `IpVote` for more details.
fn handle_ip_vote_from_pong(&mut self, node_id: NodeId, socket: SocketAddr) {
// Check that we are in a state to handle any IP votes
if !self.connectivity_state.should_count_ip_vote(&socket) {
return;
}
// Only count votes that are from peers we have contacted.
let key: kbucket::Key<NodeId> = node_id.into();
let is_connected_and_outgoing = matches!(
self.kbuckets.write().entry(&key),
kbucket::Entry::Present(_, status)
if status.is_connected() && !status.is_incoming());
// Check to make sure this is an outgoing peer vote, otherwise if we need the vote due to a
// lack of minority, we accept it.
if !(is_connected_and_outgoing | self.require_more_ip_votes(socket.is_ipv6())) {
return;
}
match socket {
SocketAddr::V4(_) => {
let local_ip4_socket = self.local_enr.read().udp4_socket();
if let Some(ip_votes) = self.ip_votes.as_mut() {
ip_votes.insert(node_id, socket);
let maybe_ip4_majority = ip_votes.majority().0;
let new_ip4 = maybe_ip4_majority.and_then(|majority| {
if Some(majority) != local_ip4_socket {
Some(majority)
} else {
None
}
});
// If we have a new ipv4 majority
if let Some(new_ip4) = new_ip4 {
let new_ip4: SocketAddr = new_ip4.into();
let result = self
.local_enr
.write()
.set_udp_socket(new_ip4, &self.enr_key.read());
match result {
Ok(_) => {
// Inform the connectivity state that we have updated our IP advertisement
self.connectivity_state.enr_socket_update(&new_ip4);
info!(ip_version="v4", %new_ip4, "Local UDP socket updated");
self.send_event(Event::SocketUpdated(new_ip4));
self.ping_connected_peers();
}
Err(e) => {
warn!(ip = %new_ip4, error = ?e, "Failed to update local UDP socket.");
}
}
}
}
}
SocketAddr::V6(_) => {
let local_ip6_socket = self.local_enr.read().udp6_socket();
if let Some(ip_votes) = self.ip_votes.as_mut() {
ip_votes.insert(node_id, socket);
let maybe_ip6_majority = ip_votes.majority().1;
let new_ip6 = maybe_ip6_majority.and_then(|majority| {
if Some(majority) != local_ip6_socket {
Some(majority)
} else {
None
}
});
// Check if our advertised IPV6 address needs to be updated.
if let Some(new_ip6) = new_ip6 {
let new_ip6: SocketAddr = new_ip6.into();
let result = self
.local_enr
.write()
.set_udp_socket(new_ip6, &self.enr_key.read());
match result {
Ok(_) => {
// Inform the connectivity state that we have updated our IP advertisement
self.connectivity_state.enr_socket_update(&new_ip6);
info!(ip_version="v6", %new_ip6, "Local UDP socket updated");
self.send_event(Event::SocketUpdated(new_ip6));
self.ping_connected_peers();
}
Err(e) => {
warn!(ip6 = %new_ip6, error = ?e, "Failed to update local UDP ip6 socket.");
}
}
}
}
}
}
}
// Send RPC Requests //
/// Sends a PING request to a node.
fn send_ping(
&mut self,
enr: Enr,
callback: Option<oneshot::Sender<Result<Pong, RequestError>>>,
) {
match NodeContact::try_from_enr(enr, self.ip_mode) {
Ok(contact) => {
let request_body = RequestBody::Ping {
enr_seq: self.local_enr.read().seq(),
};
let active_request = ActiveRequest {
contact,
request_body,
query_id: None,
callback: callback.map(CallbackResponse::Pong),
};
self.send_rpc_request(active_request);
}
Err(NonContactable { enr }) => error!(%enr, "Trying to ping a non-contactable peer"),
}
}