-
Notifications
You must be signed in to change notification settings - Fork 113
/
service.rs
4022 lines (3597 loc) · 152 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
use std::{
collections::HashMap,
fmt::Debug,
marker::{PhantomData, Sync},
sync::Arc,
task::Poll,
time::Duration,
};
use anyhow::anyhow;
use bytes::Bytes;
use delay_map::HashSetDelay;
use discv5::{
enr::NodeId,
kbucket::{
self, ConnectionDirection, ConnectionState, FailureReason, InsertResult, KBucketsTable,
Key, NodeStatus, UpdateResult,
},
rpc::RequestId,
};
use futures::{channel::oneshot, future::join_all, prelude::*};
use itertools::Itertools;
use parking_lot::RwLock;
use rand::seq::SliceRandom;
use smallvec::SmallVec;
use ssz::Encode;
use ssz_types::BitList;
use tokio::{
sync::{
broadcast,
mpsc::{self, UnboundedReceiver, UnboundedSender},
OwnedSemaphorePermit,
},
task::JoinHandle,
};
use tracing::{debug, enabled, error, info, trace, warn, Level};
use utp_rs::cid::ConnectionId;
use crate::{
accept_queue::AcceptQueue,
discovery::{Discovery, UtpEnr},
events::{EventEnvelope, OverlayEvent},
find::{
iterators::{
findcontent::{FindContentQuery, FindContentQueryResponse, FindContentQueryResult},
findnodes::FindNodeQuery,
query::{Query, QueryConfig},
},
query_info::{QueryInfo, QueryType, RecursiveFindContentResult},
query_pool::{QueryId, QueryPool, QueryPoolState, TargetKey},
},
gossip::propagate_gossip_cross_thread,
overlay::{
command::OverlayCommand,
errors::OverlayRequestError,
request::{
ActiveOutgoingRequest, OverlayRequest, OverlayRequestId, OverlayResponse,
RequestDirection,
},
},
types::node::Node,
utils::portal_wire,
utp_controller::UtpController,
};
use ethportal_api::{
generate_random_node_id,
types::{
distance::{Distance, Metric},
enr::{Enr, SszEnr},
portal_wire::{
Accept, Content, CustomPayload, FindContent, FindNodes, Message, Nodes, Offer, Ping,
Pong, PopulatedOffer, ProtocolId, Request, Response, MAX_PORTAL_CONTENT_PAYLOAD_SIZE,
MAX_PORTAL_NODES_ENRS_SIZE,
},
query_trace::QueryTrace,
},
utils::bytes::hex_encode_compact,
OverlayContentKey, RawContentKey,
};
use trin_metrics::overlay::OverlayMetricsReporter;
use trin_storage::{ContentStore, ShouldWeStoreContent};
use trin_validation::validator::{ValidationResult, Validator};
pub const FIND_NODES_MAX_NODES: usize = 32;
/// Maximum number of ENRs in response to FindContent.
pub const FIND_CONTENT_MAX_NODES: usize = 32;
/// With even distribution assumptions, 2**17 is enough to put each node (estimating 100k nodes,
/// which is more than 10x the ethereum mainnet node count) into a unique bucket by the 17th bucket
/// index.
const EXPECTED_NON_EMPTY_BUCKETS: usize = 17;
/// Bucket refresh lookup interval in seconds
const BUCKET_REFRESH_INTERVAL_SECS: u64 = 60;
/// The capacity of the event-stream's broadcast channel.
const EVENT_STREAM_CHANNEL_CAPACITY: usize = 10;
/// The overlay service.
pub struct OverlayService<TContentKey, TMetric, TValidator, TStore>
where
TContentKey: OverlayContentKey,
{
/// The underlying Discovery v5 protocol.
discovery: Arc<Discovery>,
/// The content database of the local node.
store: Arc<RwLock<TStore>>,
/// The routing table of the local node.
kbuckets: Arc<RwLock<KBucketsTable<NodeId, Node>>>,
/// The protocol identifier.
protocol: ProtocolId,
/// A queue of peers that require regular ping to check connectivity.
/// Inserted entries expire after a fixed time. Nodes to be pinged are inserted with a timeout
/// duration equal to some ping interval, and we continuously poll the queue to check for
/// expired entries.
peers_to_ping: HashSetDelay<NodeId>,
// TODO: This should probably be a bounded channel.
/// The receiver half of the service command channel.
command_rx: UnboundedReceiver<OverlayCommand<TContentKey>>,
/// The sender half of the service command channel.
/// This is used internally to submit requests (e.g. maintenance ping requests).
command_tx: UnboundedSender<OverlayCommand<TContentKey>>,
/// A map of active outgoing requests.
active_outgoing_requests: Arc<RwLock<HashMap<OverlayRequestId, ActiveOutgoingRequest>>>,
/// A query pool that manages find node queries.
find_node_query_pool: Arc<RwLock<QueryPool<NodeId, FindNodeQuery<NodeId>, TContentKey>>>,
/// A query pool that manages find content queries.
find_content_query_pool: Arc<RwLock<QueryPool<NodeId, FindContentQuery<NodeId>, TContentKey>>>,
/// Timeout after which a peer in an ongoing query is marked unresponsive.
query_peer_timeout: Duration,
/// Number of peers to request data from in parallel for a single query.
query_parallelism: usize,
/// Number of new peers to discover before considering a FINDNODES query complete.
query_num_results: usize,
/// The number of buckets we simultaneously request from each peer in a FINDNODES query.
findnodes_query_distances_per_peer: usize,
/// The receiver half of a channel for responses to outgoing requests.
response_rx: UnboundedReceiver<OverlayResponse>,
/// The sender half of a channel for responses to outgoing requests.
response_tx: UnboundedSender<OverlayResponse>,
/// uTP controller.
utp_controller: Arc<UtpController>,
/// Phantom content key.
phantom_content_key: PhantomData<TContentKey>,
/// Phantom metric (distance function).
phantom_metric: PhantomData<TMetric>,
/// Metrics reporting component
metrics: OverlayMetricsReporter,
/// Validator for overlay network content.
validator: Arc<TValidator>,
/// A channel that the overlay service emits events on.
event_stream: broadcast::Sender<EventEnvelope>,
/// Disable poke mechanism
disable_poke: bool,
/// Accept Queue for inbound content keys
accept_queue: Arc<RwLock<AcceptQueue<TContentKey>>>,
}
impl<
TContentKey: 'static + OverlayContentKey + Send + Sync,
TMetric: Metric + Send + Sync,
TValidator: 'static + Validator<TContentKey> + Send + Sync,
TStore: 'static + ContentStore + Send + Sync,
> OverlayService<TContentKey, TMetric, TValidator, TStore>
where
<TContentKey as TryFrom<Vec<u8>>>::Error: Debug,
{
/// Spawns the overlay network service.
///
/// The state of the overlay network largely consists of its routing table. The routing table
/// is updated according to incoming requests and responses as well as autonomous maintenance
/// processes.
#[allow(clippy::too_many_arguments)]
pub async fn spawn(
discovery: Arc<Discovery>,
store: Arc<RwLock<TStore>>,
kbuckets: Arc<RwLock<KBucketsTable<NodeId, Node>>>,
bootnode_enrs: Vec<Enr>,
ping_queue_interval: Option<Duration>,
protocol: ProtocolId,
utp_controller: Arc<UtpController>,
metrics: OverlayMetricsReporter,
validator: Arc<TValidator>,
query_timeout: Duration,
query_peer_timeout: Duration,
query_parallelism: usize,
query_num_results: usize,
findnodes_query_distances_per_peer: usize,
disable_poke: bool,
) -> UnboundedSender<OverlayCommand<TContentKey>>
where
<TContentKey as TryFrom<Vec<u8>>>::Error: Send,
{
let (command_tx, command_rx) = mpsc::unbounded_channel();
let internal_command_tx = command_tx.clone();
let peers_to_ping = if let Some(interval) = ping_queue_interval {
HashSetDelay::new(interval)
} else {
HashSetDelay::default()
};
let (response_tx, response_rx) = mpsc::unbounded_channel();
let (event_stream, _) = broadcast::channel(EVENT_STREAM_CHANNEL_CAPACITY);
tokio::spawn(async move {
let mut service = Self {
discovery,
store,
kbuckets,
protocol,
peers_to_ping,
command_rx,
command_tx: internal_command_tx,
active_outgoing_requests: Arc::new(RwLock::new(HashMap::new())),
find_node_query_pool: Arc::new(RwLock::new(QueryPool::new(query_timeout))),
find_content_query_pool: Arc::new(RwLock::new(QueryPool::new(query_timeout))),
query_peer_timeout,
query_parallelism,
query_num_results,
findnodes_query_distances_per_peer,
response_rx,
response_tx,
utp_controller,
phantom_content_key: PhantomData,
phantom_metric: PhantomData,
metrics,
validator,
event_stream,
disable_poke,
accept_queue: Arc::new(RwLock::new(AcceptQueue::default())),
};
info!(protocol = %protocol, "Starting overlay service");
service.initialize_routing_table(bootnode_enrs);
service.start().await;
});
command_tx
}
/// Insert a vector of enrs into the routing table
/// set_connected: should only be true for tests, false for production code
/// Tests that use this function are testing if adding to queues work, not if our connection
/// code works.
fn add_bootnodes(&mut self, bootnode_enrs: Vec<Enr>, set_connected: bool) {
// Attempt to insert bootnodes into the routing table in a disconnected state.
// If successful, then add the node to the ping queue. A subsequent successful ping
// will mark the node as connected.
for enr in bootnode_enrs {
let node_id = enr.node_id();
// TODO: Decide default data radius, and define a constant. Or if there is an
// associated database, then look for a radius value there.
let node = Node::new(enr, Distance::MAX);
let state = if set_connected {
ConnectionState::Connected
} else {
ConnectionState::Disconnected
};
let status = NodeStatus {
state,
direction: ConnectionDirection::Outgoing,
};
// Attempt to insert the node into the routing table.
match self
.kbuckets
.write()
.insert_or_update(&kbucket::Key::from(node_id), node, status)
{
InsertResult::Failed(reason) => {
warn!(
protocol = %self.protocol,
bootnode = %node_id,
error = ?reason,
"Error inserting bootnode into routing table",
);
}
_ => {
debug!(
protocol = %self.protocol,
bootnode = %node_id,
"Inserted bootnode into routing table",
);
// Queue the node in the ping queue.
self.peers_to_ping.insert(node_id);
}
}
}
}
/// Begins initial FINDNODES query to populate the routing table.
fn initialize_routing_table(&mut self, bootnodes: Vec<Enr>) {
self.add_bootnodes(bootnodes, false);
let local_node_id = self.local_enr().node_id();
// Begin request for our local node ID.
self.init_find_nodes_query(&local_node_id, None);
for bucket_index in (255 - EXPECTED_NON_EMPTY_BUCKETS as u8)..255 {
let target_node_id = generate_random_node_id(bucket_index, self.local_enr().into());
self.init_find_nodes_query(&target_node_id, None);
}
}
/// The main loop for the overlay service. The loop selects over different possible tasks to
/// perform.
///
/// Process request: Process an incoming or outgoing request through the overlay.
///
/// Process response: Process a response to an outgoing request from the local node. Try to
/// match this response to an active request, and send the response or error over the
/// associated response channel. Update node state based on result of response.
///
/// Ping queue: Ping a node in the routing table to perform a liveness check and to refresh
/// information relevant to the overlay network.
///
/// Bucket maintenance: Maintain the routing table (more info documented above function).
async fn start(&mut self) {
// Construct bucket refresh interval
let mut bucket_refresh_interval =
tokio::time::interval(Duration::from_secs(BUCKET_REFRESH_INTERVAL_SECS));
loop {
tokio::select! {
Some(command) = self.command_rx.recv() => {
match command {
OverlayCommand::Request(request) => self.process_request(request),
OverlayCommand::Event(event) => self.process_event(event),
OverlayCommand::FindContentQuery { target, callback, is_trace } => {
if let Some(query_id) = self.init_find_content_query(target.clone(), Some(callback), is_trace) {
trace!(
query.id = %query_id,
content.id = %hex_encode_compact(target.content_id()),
content.key = %target,
"FindContent query initialized"
);
}
}
OverlayCommand::FindNodeQuery { target, callback } => {
if let Some(query_id) = self.init_find_nodes_query(&target, Some(callback)) {
trace!(
query.id = %query_id,
node.id = %hex_encode_compact(target),
"FindNode query initialized"
);
}
}
OverlayCommand::RequestEventStream(callback) => {
if callback.send(self.event_stream.subscribe()).is_err() {
error!("Failed to return the event stream channel");
}
}
}
}
Some(response) = self.response_rx.recv() => {
// Look up active request that corresponds to the response.
let active_request = self.active_outgoing_requests.write().remove(&response.request_id);
if let Some(request) = active_request {
// Send response to responder if present.
if let Some(responder) = request.responder {
let _ = responder.send(response.response.clone());
}
// Perform background processing.
match response.response {
Ok(response) => {
self.metrics.report_inbound_response(&response);
self.process_response(response, request.destination, request.request, request.query_id, request.request_permit)
}
Err(error) => self.process_request_failure(response.request_id, request.destination, error),
}
} else {
warn!(request.id = %hex_encode_compact(response.request_id.to_be_bytes()), "No request found for response");
}
}
Some(Ok(node_id)) = self.peers_to_ping.next() => {
// If the node is in the routing table, then ping and re-queue the node.
let key = kbucket::Key::from(node_id);
if let kbucket::Entry::Present(ref mut entry, _) = self.kbuckets.write().entry(&key) {
self.ping_node(&entry.value().enr());
self.peers_to_ping.insert(node_id);
}
}
query_event = OverlayService::<TContentKey, TMetric, TValidator, TStore>::query_event_poll(self.find_node_query_pool.clone()) => {
self.handle_find_nodes_query_event(query_event);
}
// Handle query events for queries in the find content query pool.
query_event = OverlayService::<TContentKey, TMetric, TValidator, TStore>::query_event_poll(self.find_content_query_pool.clone()) => {
self.handle_find_content_query_event(query_event);
}
_ = OverlayService::<TContentKey, TMetric, TValidator, TStore>::bucket_maintenance_poll(self.protocol, &self.kbuckets) => {}
_ = bucket_refresh_interval.tick() => {
trace!(protocol = %self.protocol, "Routing table bucket refresh");
self.bucket_refresh_lookup();
}
}
}
}
/// Main bucket refresh lookup logic
fn bucket_refresh_lookup(&mut self) {
// Look at local routing table and select the largest 17 buckets.
// We only need the 17 bits furthest from our own node ID, because the closest 239 bits of
// buckets are going to be empty-ish.
let target_node_id = {
let buckets = self.kbuckets.read();
let buckets = buckets.buckets_iter().enumerate().collect::<Vec<_>>();
let buckets = &buckets[256 - EXPECTED_NON_EMPTY_BUCKETS..];
// Randomly pick one of these buckets.
let target_bucket = buckets.choose(&mut rand::thread_rng());
match target_bucket {
Some(bucket) => {
trace!(protocol = %self.protocol, bucket = %bucket.0, "Refreshing routing table bucket");
match u8::try_from(bucket.0) {
Ok(idx) => generate_random_node_id(idx, self.local_enr().into()),
Err(err) => {
error!(error = %err, "Error downcasting bucket index");
return;
}
}
}
None => {
error!("Error choosing random bucket index for refresh");
return;
}
}
};
self.init_find_nodes_query(&target_node_id, None);
}
/// Returns the local ENR of the node.
fn local_enr(&self) -> Enr {
self.discovery.local_enr()
}
/// Returns the data radius of the node.
fn data_radius(&self) -> Distance {
self.store.read().radius()
}
/// Maintains the routing table.
///
/// Consumes previously applied pending entries from the `KBucketsTable`. An `AppliedPending`
/// result is recorded when a pending bucket entry replaces a disconnected entry in the
/// respective bucket.
async fn bucket_maintenance_poll(
protocol: ProtocolId,
kbuckets: &Arc<RwLock<KBucketsTable<NodeId, Node>>>,
) {
future::poll_fn(move |_cx| {
// Drain applied pending entries from the routing table.
if let Some(entry) = kbuckets.write().take_applied_pending() {
debug!(
%protocol,
inserted = %entry.inserted.into_preimage(),
evicted = ?entry.evicted.map(|n| n.key.into_preimage()),
"Pending node inserted",
);
return Poll::Ready(());
}
Poll::Pending
})
.await
}
/// Maintains the query pool.
/// Returns a `QueryEvent` when the `QueryPoolState` updates.
/// This happens when a query needs to send a request to a node, when a query has completed,
/// or when a query has timed out.
async fn query_event_poll<TQuery: Query<NodeId>>(
queries: Arc<RwLock<QueryPool<NodeId, TQuery, TContentKey>>>,
) -> QueryEvent<TQuery, TContentKey> {
future::poll_fn(move |_cx| match queries.write().poll() {
QueryPoolState::Finished(query_id, query_info, query) => {
Poll::Ready(QueryEvent::Finished(query_id, query_info, query))
}
QueryPoolState::Timeout(query_id, query_info, query) => {
warn!(query.id = %query_id, "Query timed out");
Poll::Ready(QueryEvent::TimedOut(query_id, query_info, query))
}
QueryPoolState::Waiting(Some((query_id, query_info, query, return_peer))) => {
let node_id = return_peer;
let request_body = match query_info.rpc_request(return_peer) {
Ok(request_body) => request_body,
Err(_) => {
query.on_failure(&node_id);
return Poll::Pending;
}
};
Poll::Ready(QueryEvent::Waiting(query_id, node_id, request_body))
}
QueryPoolState::Waiting(None) | QueryPoolState::Idle => Poll::Pending,
})
.await
}
/// Handles a `QueryEvent` from a poll on the find nodes query pool.
fn handle_find_nodes_query_event(
&mut self,
query_event: QueryEvent<FindNodeQuery<NodeId>, TContentKey>,
) {
match query_event {
// Send a FINDNODES on behalf of the query.
QueryEvent::Waiting(query_id, node_id, request) => {
// Look up the node's ENR.
if let Some(enr) = self.find_enr(&node_id) {
let request = OverlayRequest::new(
request,
RequestDirection::Outgoing { destination: enr },
None,
Some(query_id),
None,
);
let _ = self.command_tx.send(OverlayCommand::Request(request));
} else {
error!(
protocol = %self.protocol,
peer = %node_id,
query.id = %query_id,
"Cannot query peer with unknown ENR",
);
if let Some((_, query)) = self.find_node_query_pool.write().get_mut(query_id) {
query.on_failure(&node_id);
}
}
}
// Query has ended.
QueryEvent::Finished(query_id, mut query_info, query)
| QueryEvent::TimedOut(query_id, mut query_info, query) => {
let result = query.into_result();
// Obtain the ENRs for the resulting nodes.
let mut found_enrs = Vec::new();
for node_id in result.into_iter() {
if let Some(position) = query_info
.untrusted_enrs
.iter()
.position(|enr| enr.node_id() == node_id)
{
let enr = query_info.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!(
query.id = %query_id,
"ENR from FindNode query not present in query results"
);
}
}
if let QueryType::FindNode {
callback: Some(callback),
..
} = query_info.query_type
{
if let Err(err) = callback.send(found_enrs.clone()) {
error!(
query.id = %query_id,
error = ?err,
"Error sending FindNode query result to callback",
);
}
}
trace!(
protocol = %self.protocol,
query.id = %query_id,
"Discovered {} ENRs via FindNode query",
found_enrs.len()
);
}
}
}
/// Handles a `QueryEvent` from a poll on the find content query pool.
fn handle_find_content_query_event(
&mut self,
query_event: QueryEvent<FindContentQuery<NodeId>, TContentKey>,
) {
match query_event {
QueryEvent::Waiting(query_id, node_id, request) => {
if let Some(enr) = self.find_enr(&node_id) {
// If we find the node's ENR, then send the request on behalf of the
// query. No callback channel is necessary for the request, because the
// response will be incorporated into the query.
let request = OverlayRequest::new(
request,
RequestDirection::Outgoing { destination: enr },
None,
Some(query_id),
None,
);
let _ = self.command_tx.send(OverlayCommand::Request(request));
} else {
// If we cannot find the node's ENR, then we cannot contact the
// node, so fail the query for this node.
error!(
protocol = %self.protocol,
peer = %node_id,
query.id = %query_id,
"Cannot query peer with unknown ENR"
);
if let Some((_, query)) = self.find_node_query_pool.write().get_mut(query_id) {
query.on_failure(&node_id);
}
}
}
QueryEvent::Finished(_, query_info, query)
| QueryEvent::TimedOut(_, query_info, query) => {
let (callback, content_key) = match query_info.query_type {
QueryType::FindContent { callback, target } => (callback, target),
_ => {
error!(
"Only FindContent queries trigger a Finished or TimedOut event, but this is a {:?}",
query_info.query_type
);
return;
}
};
match query.into_result() {
FindContentQueryResult::ClosestNodes(_closest_nodes) => {
if let Some(responder) = callback {
let _ = responder.send(Err(OverlayRequestError::ContentNotFound {
message: "Unable to locate content on the network".to_string(),
utp: false,
trace: query_info.trace,
}));
}
}
FindContentQueryResult::Content {
content,
nodes_to_poke,
} => {
let utp_processing = UtpProcessing::from(&*self);
tokio::spawn(async move {
Self::process_received_content(
content.clone(),
false,
content_key,
callback,
query_info.trace,
nodes_to_poke,
utp_processing,
)
.await;
});
}
FindContentQueryResult::Utp {
connection_id,
peer,
nodes_to_poke,
} => {
let source = match self.find_enr(&peer) {
Some(enr) => enr,
_ => {
debug!("Received uTP payload from unknown {peer}");
if let Some(responder) = callback {
let _ =
responder.send(Err(OverlayRequestError::ContentNotFound {
message: "Unable to locate content on the network: received utp payload from unknown peer"
.to_string(),
utp: true,
trace: query_info.trace,
}));
};
return;
}
};
let utp_processing = UtpProcessing::from(&*self);
tokio::spawn(async move {
let trace = query_info.trace;
let cid = utp_rs::cid::ConnectionId {
recv: connection_id,
send: connection_id.wrapping_add(1),
peer: UtpEnr(source),
};
let data = match utp_processing
.utp_controller
.connect_inbound_stream(cid)
.await
{
Ok(data) => data,
Err(e) => {
if let Some(responder) = callback {
let _ = responder.send(Err(
OverlayRequestError::ContentNotFound {
message: format!(
"Unable to locate content on the network: {e}"
),
utp: true,
trace,
},
));
}
return;
}
};
Self::process_received_content(
data,
true,
content_key,
callback,
trace,
nodes_to_poke,
utp_processing,
)
.await;
});
}
};
}
}
}
/// Submits outgoing requests to offer `content` to the closest known nodes whose radius
/// contains `content_key`.
fn poke_content(
kbuckets: Arc<RwLock<KBucketsTable<NodeId, Node>>>,
command_tx: UnboundedSender<OverlayCommand<TContentKey>>,
content_key: TContentKey,
content: Vec<u8>,
nodes_to_poke: Vec<NodeId>,
utp_controller: Arc<UtpController>,
) {
let content_id = content_key.content_id();
// Offer content to closest nodes with sufficient radius.
for node_id in nodes_to_poke.iter() {
// Look up node in the routing table. We need the ENR and the radius. If we can't find
// the node, then move on to the next.
let key = kbucket::Key::from(*node_id);
let node = match kbuckets.write().entry(&key) {
kbucket::Entry::Present(entry, _) => entry.value().clone(),
kbucket::Entry::Pending(mut entry, _) => entry.value().clone(),
_ => continue,
};
// If the content is within the node's radius, then offer the node the content.
let is_within_radius =
TMetric::distance(&node_id.raw(), &content_id) <= node.data_radius;
if is_within_radius {
let content_items = vec![(content_key.clone().into(), content.clone())];
let offer_request = Request::PopulatedOffer(PopulatedOffer { content_items });
// if we have met the max outbound utp transfer limit continue the loop as we aren't
// allow to generate another utp stream
let permit = match utp_controller.get_outbound_semaphore() {
Some(permit) => permit,
None => continue,
};
let request = OverlayRequest::new(
offer_request,
RequestDirection::Outgoing {
destination: node.enr(),
},
None,
None,
Some(permit),
);
match command_tx.send(OverlayCommand::Request(request)) {
Ok(_) => {
trace!(
content.id = %hex_encode_compact(content_id),
content.key = %content_key,
peer.node_id = %node_id,
"Content poked"
);
}
Err(err) => {
warn!(
content.id = %hex_encode_compact(content_id),
content.key = %content_key,
peer.node_id = %node_id,
%err,
"Failed to poke content to peer"
);
}
}
}
}
}
/// Processes an overlay request.
fn process_request(&mut self, request: OverlayRequest) {
// For incoming requests, handle the request, possibly send the response over the channel,
// and then process the request.
//
// For outgoing requests, send the request via a TALK request over Discovery v5, send the
// response over the channel, and then process the response. There may not be a response
// channel if the request was initiated internally (e.g. for maintenance).
match request.direction {
RequestDirection::Incoming { id, source } => {
self.register_node_activity(source);
let response = self.handle_request(request.request.clone(), id.clone(), &source);
// Send response to responder if present.
if let Some(responder) = request.responder {
if let Ok(ref response) = response {
self.metrics.report_outbound_response(response);
}
let _ = responder.send(response);
}
// Perform background processing.
self.process_incoming_request(request.request, id, source);
}
RequestDirection::Outgoing { destination } => {
self.active_outgoing_requests.write().insert(
request.id,
ActiveOutgoingRequest {
destination: destination.clone(),
responder: request.responder,
request: request.request.clone(),
query_id: request.query_id,
request_permit: request.request_permit,
},
);
self.metrics.report_outbound_request(&request.request);
self.send_talk_req(request.request, request.id, destination);
}
}
}
/// Process an event dispatched by another overlay on the discovery.
fn process_event(&mut self, _event: EventEnvelope) {}
/// Attempts to build a response for a request.
#[allow(clippy::result_large_err)]
fn handle_request(
&mut self,
request: Request,
id: RequestId,
source: &NodeId,
) -> Result<Response, OverlayRequestError> {
match request {
Request::Ping(ping) => Ok(Response::Pong(self.handle_ping(ping, source, id))),
Request::FindNodes(find_nodes) => Ok(Response::Nodes(
self.handle_find_nodes(find_nodes, source, id),
)),
Request::FindContent(find_content) => Ok(Response::Content(self.handle_find_content(
find_content,
source,
id,
)?)),
Request::Offer(offer) => Ok(Response::Accept(self.handle_offer(offer, source, id)?)),
Request::PopulatedOffer(_) | Request::PopulatedOfferWithResult(_) => {
Err(OverlayRequestError::InvalidRequest(
"An offer with content attached is not a valid network message to receive"
.to_owned(),
))
}
}
}
/// Builds a `Pong` response for a `Ping` request.
fn handle_ping(&self, request: Ping, source: &NodeId, request_id: RequestId) -> Pong {
trace!(
protocol = %self.protocol,
request.source = %source,
request.discv5.id = %request_id,
"Handling Ping message {}",
request
);
let enr_seq = self.local_enr().seq();
let data_radius = self.data_radius();
let custom_payload = CustomPayload::from(data_radius.as_ssz_bytes());
Pong {
enr_seq,
custom_payload,
}
}
/// Builds a `Nodes` response for a `FindNodes` request.
fn handle_find_nodes(
&self,
request: FindNodes,
source: &NodeId,
request_id: RequestId,
) -> Nodes {
trace!(
protocol = %self.protocol,
request.source = %source,
request.discv5.id = %request_id,
"Handling FindNodes message",
);
let distances64: Vec<u64> = request.distances.iter().map(|x| (*x).into()).collect();
let mut enrs = self
.nodes_by_distance(distances64)
.into_iter()
.filter(|enr| {
// Filter out the source node.
&enr.node_id() != source
})
.collect();
// Limit the ENRs so that their summed sizes do not surpass the max TALKREQ packet size.
pop_while_ssz_bytes_len_gt(&mut enrs, MAX_PORTAL_NODES_ENRS_SIZE);
Nodes { total: 1, enrs }
}
/// Attempts to build a `Content` response for a `FindContent` request.
#[allow(clippy::result_large_err)]
fn handle_find_content(
&self,
request: FindContent,
source: &NodeId,
request_id: RequestId,
) -> Result<Content, OverlayRequestError> {
trace!(
protocol = %self.protocol,
request.source = %source,
request.discv5.id = %request_id,
"Handling FindContent message",
);
let content_key = match (TContentKey::try_from)(request.content_key) {
Ok(key) => key,
Err(_) => {
return Err(OverlayRequestError::InvalidRequest(
"Invalid content key".to_string(),
))
}
};
match (
self.store.read().get(&content_key),
self.utp_controller.get_outbound_semaphore(),
) {
(Ok(Some(content)), Some(permit)) => {
if content.len() <= MAX_PORTAL_CONTENT_PAYLOAD_SIZE {
Ok(Content::Content(content))
} else {
// Generate a connection ID for the uTP connection.
let node_addr = self.discovery.cached_node_addr(source).ok_or_else(|| {
OverlayRequestError::AcceptError(
"unable to find ENR for NodeId".to_string(),
)
})?;
let enr = UtpEnr(node_addr.enr);
let cid = self.utp_controller.cid(enr, false);
let cid_send = cid.send;
// Wait for an incoming connection with the given CID. Then, write the data
// over the uTP stream.
let utp = Arc::clone(&self.utp_controller);
tokio::spawn(async move {
utp.accept_outbound_stream(cid, content).await;
drop(permit);
});
// Connection id is sent as BE because uTP header values are stored also as BE
Ok(Content::ConnectionId(cid_send.to_be()))
}
}
// If we don't have data to send back or can't obtain a permit, send the requester a
// list of closer ENRs.
(Ok(Some(_)), _) | (Ok(None), _) => {
let mut enrs = self.find_nodes_close_to_content(content_key);
enrs.retain(|enr| source != &enr.node_id());
pop_while_ssz_bytes_len_gt(&mut enrs, MAX_PORTAL_CONTENT_PAYLOAD_SIZE);
Ok(Content::Enrs(enrs))
}
(Err(msg), _) => Err(OverlayRequestError::Failure(format!(
"Unable to respond to FindContent: {msg}",
))),
}
}
/// Attempts to build an `Accept` response for an `Offer` request.
#[allow(clippy::result_large_err)]
fn handle_offer(
&self,
request: Offer,
source: &NodeId,
request_id: RequestId,
) -> Result<Accept, OverlayRequestError> {
trace!(
protocol = %self.protocol,
request.source = %source,
request.discv5.id = %request_id,
"Handling Offer message",
);
let mut requested_keys =