-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathmod.rs
More file actions
1651 lines (1469 loc) · 63.3 KB
/
Copy pathmod.rs
File metadata and controls
1651 lines (1469 loc) · 63.3 KB
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 2023 litep2p developers
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//! [`/ipfs/kad/1.0.0`](https://github.com/libp2p/specs/blob/master/kad-dht/README.md) implementation.
use crate::{
error::{Error, ImmediateDialError, SubstreamError},
protocol::{
libp2p::kademlia::{
bucket::KBucketEntry,
executor::{QueryContext, QueryExecutor, QueryResult},
message::KademliaMessage,
query::{QueryAction, QueryEngine},
routing_table::RoutingTable,
store::{MemoryStore, MemoryStoreAction},
types::{ConnectionType, KademliaPeer, Key},
},
Direction, TransportEvent, TransportService,
},
substream::Substream,
transport::Endpoint,
types::SubstreamId,
PeerId,
};
use bytes::{Bytes, BytesMut};
use futures::StreamExt;
use multiaddr::Multiaddr;
use tokio::sync::mpsc::{Receiver, Sender};
use std::{
collections::{hash_map::Entry, HashMap},
sync::{
atomic::{AtomicUsize, Ordering},
Arc,
},
time::{Duration, Instant},
};
pub use config::{Config, ConfigBuilder};
pub use handle::{
IncomingRecordValidationMode, KademliaCommand, KademliaEvent, KademliaHandle, Quorum,
RoutingTableUpdateMode,
};
pub use query::QueryId;
pub use record::{ContentProvider, Key as RecordKey, PeerRecord, Record};
/// Logging target for the file.
const LOG_TARGET: &str = "litep2p::ipfs::kademlia";
/// Parallelism factor, `α`.
const PARALLELISM_FACTOR: usize = 3;
mod bucket;
mod config;
mod executor;
mod handle;
mod message;
mod query;
mod record;
mod routing_table;
mod store;
mod types;
mod schema {
pub(super) mod kademlia {
include!(concat!(env!("OUT_DIR"), "/kademlia.rs"));
}
}
/// Peer action.
#[derive(Debug, Clone)]
#[allow(clippy::enum_variant_names)]
enum PeerAction {
/// Find nodes (and values/providers) as part of `FIND_NODE`/`GET_VALUE`/`GET_PROVIDERS` query.
// TODO: may be a better naming would be `SendFindRequest`?
SendFindNode(QueryId),
/// Send `PUT_VALUE` message to peer.
SendPutValue(QueryId, Bytes),
/// Send `ADD_PROVIDER` message to peer.
SendAddProvider(QueryId, Bytes),
}
impl PeerAction {
fn query_id(&self) -> QueryId {
match self {
PeerAction::SendFindNode(query_id) => *query_id,
PeerAction::SendPutValue(query_id, _) => *query_id,
PeerAction::SendAddProvider(query_id, _) => *query_id,
}
}
}
/// Peer context.
#[derive(Default)]
struct PeerContext {
/// Pending action, if any.
pending_actions: HashMap<SubstreamId, PeerAction>,
}
impl PeerContext {
/// Create new [`PeerContext`].
pub fn new() -> Self {
Self {
pending_actions: HashMap::new(),
}
}
/// Add pending action for peer.
pub fn add_pending_action(&mut self, substream_id: SubstreamId, action: PeerAction) {
self.pending_actions.insert(substream_id, action);
}
}
/// Main Kademlia object.
pub(crate) struct Kademlia {
/// Transport service.
service: TransportService,
/// Local Kademlia key.
local_key: Key<PeerId>,
/// Connected peers,
peers: HashMap<PeerId, PeerContext>,
/// TX channel for sending events to `KademliaHandle`.
event_tx: Sender<KademliaEvent>,
/// RX channel for receiving commands from `KademliaHandle`.
cmd_rx: Receiver<KademliaCommand>,
/// Next query ID.
next_query_id: Arc<AtomicUsize>,
/// Routing table.
routing_table: RoutingTable,
/// Replication factor.
replication_factor: usize,
/// Record store.
store: MemoryStore,
/// Pending outbound substreams.
pending_substreams: HashMap<SubstreamId, PeerId>,
/// Pending dials.
pending_dials: HashMap<PeerId, Vec<PeerAction>>,
/// Routing table update mode.
update_mode: RoutingTableUpdateMode,
/// Incoming records validation mode.
validation_mode: IncomingRecordValidationMode,
/// Default record TTL.
record_ttl: Duration,
/// Query engine.
engine: QueryEngine,
/// Query executor.
executor: QueryExecutor,
}
impl Kademlia {
/// Create new [`Kademlia`].
pub(crate) fn new(mut service: TransportService, config: Config) -> Self {
let local_peer_id = service.local_peer_id();
let local_key = Key::from(service.local_peer_id());
let mut routing_table = RoutingTable::new(local_key.clone());
for (peer, addresses) in config.known_peers {
tracing::trace!(target: LOG_TARGET, ?peer, ?addresses, "add bootstrap peer");
routing_table.add_known_peer(peer, addresses.clone(), ConnectionType::NotConnected);
service.add_known_address(&peer, addresses.into_iter());
}
let store = MemoryStore::with_config(local_peer_id, config.memory_store_config);
Self {
service,
routing_table,
peers: HashMap::new(),
cmd_rx: config.cmd_rx,
next_query_id: config.next_query_id,
store,
event_tx: config.event_tx,
local_key,
pending_dials: HashMap::new(),
executor: QueryExecutor::new(),
pending_substreams: HashMap::new(),
update_mode: config.update_mode,
validation_mode: config.validation_mode,
record_ttl: config.record_ttl,
replication_factor: config.replication_factor,
engine: QueryEngine::new(local_peer_id, config.replication_factor, PARALLELISM_FACTOR),
}
}
/// Allocate next query ID.
fn next_query_id(&mut self) -> QueryId {
let query_id = self.next_query_id.fetch_add(1, Ordering::Relaxed);
QueryId(query_id)
}
/// Connection established to remote peer.
fn on_connection_established(&mut self, peer: PeerId, endpoint: Endpoint) -> crate::Result<()> {
tracing::trace!(target: LOG_TARGET, ?peer, "connection established");
match self.peers.entry(peer) {
Entry::Vacant(entry) => {
// Set the conenction type to connected and potentially save the address in the
// table.
//
// Note: this happens regardless of the state of the kademlia managed peers, because
// an already occupied entry in the `self.peers` map does not mean that we are
// no longer interested in the address / connection type of the peer.
self.routing_table.on_connection_established(Key::from(peer), endpoint);
let Some(actions) = self.pending_dials.remove(&peer) else {
// Note that we do not add peer entry if we don't have any pending actions.
// This is done to not populate `self.peers` with peers that don't support
// our Kademlia protocol.
return Ok(());
};
// go over all pending actions, open substreams and save the state to `PeerContext`
// from which it will be later queried when the substream opens
let mut context = PeerContext::new();
for action in actions {
match self.service.open_substream(peer) {
Ok(substream_id) => {
context.add_pending_action(substream_id, action);
}
Err(error) => {
tracing::debug!(
target: LOG_TARGET,
?peer,
?action,
?error,
"connection established to peer but failed to open substream",
);
if let PeerAction::SendFindNode(query_id) = action {
self.engine.register_send_failure(query_id, peer);
self.engine.register_response_failure(query_id, peer);
}
}
}
}
entry.insert(context);
Ok(())
}
Entry::Occupied(_) => {
tracing::warn!(
target: LOG_TARGET,
?peer,
?endpoint,
"connection already exists, discarding opening substreams, this is unexpected"
);
// Update the connection in the routing table, similar as above. The function call
// happens in two places to avoid unnecessary cloning of the endpoint for logging
// purposes.
self.routing_table.on_connection_established(Key::from(peer), endpoint);
Err(Error::PeerAlreadyExists(peer))
}
}
}
/// Disconnect peer from `Kademlia`.
///
/// Peer is disconnected either because the substream was detected closed
/// or because the connection was closed.
///
/// The peer is kept in the routing table but its connection state is set
/// as `NotConnected`, meaning it can be evicted from a k-bucket if another
/// peer that shares the bucket connects.
async fn disconnect_peer(&mut self, peer: PeerId, query: Option<QueryId>) {
tracing::trace!(target: LOG_TARGET, ?peer, ?query, "disconnect peer");
if let Some(query) = query {
self.engine.register_peer_failure(query, peer);
}
// Apart from the failing query, we need to fail all other pending queries for the peer
// being disconnected.
if let Some(PeerContext { pending_actions }) = self.peers.remove(&peer) {
pending_actions.into_iter().for_each(|(_, action)| {
// Don't report failure twice for the same `query_id` if it was already reported
// above. (We can still have other pending queries for the peer that
// need to be reported.)
let query_id = action.query_id();
if Some(query_id) != query {
self.engine.register_peer_failure(query_id, peer);
}
});
}
if let KBucketEntry::Occupied(entry) = self.routing_table.entry(Key::from(peer)) {
entry.connection = ConnectionType::NotConnected;
}
}
/// Local node opened a substream to remote node.
async fn on_outbound_substream(
&mut self,
peer: PeerId,
substream_id: SubstreamId,
substream: Substream,
) -> crate::Result<()> {
tracing::trace!(
target: LOG_TARGET,
?peer,
?substream_id,
"outbound substream opened",
);
let _ = self.pending_substreams.remove(&substream_id);
let pending_action = &mut self
.peers
.get_mut(&peer)
// If we opened an outbound substream, we must have pending actions for the peer.
.ok_or(Error::PeerDoesntExist(peer))?
.pending_actions
.remove(&substream_id);
match pending_action.take() {
None => {
tracing::trace!(
target: LOG_TARGET,
?peer,
?substream_id,
"pending action doesn't exist for peer, closing substream",
);
let _ = substream.close().await;
return Ok(());
}
Some(PeerAction::SendFindNode(query)) => {
match self.engine.next_peer_action(&query, &peer) {
Some(QueryAction::SendMessage {
query,
peer,
message,
}) => {
tracing::trace!(target: LOG_TARGET, ?peer, ?query, "start sending message to peer");
self.executor.send_request_read_response(
peer,
Some(query),
message,
substream,
);
}
// query finished while the substream was being opened
None => {
let _ = substream.close().await;
}
action => {
tracing::warn!(target: LOG_TARGET, ?query, ?peer, ?action, "unexpected action for `FIND_NODE`");
let _ = substream.close().await;
debug_assert!(false);
}
}
}
Some(PeerAction::SendPutValue(query, message)) => {
tracing::trace!(target: LOG_TARGET, ?peer, "send `PUT_VALUE` message");
self.executor.send_request_eat_response_failure(
peer,
Some(query),
message,
substream,
);
// TODO: replace this with `send_request_read_response` as part of
// https://github.com/paritytech/litep2p/issues/429.
}
Some(PeerAction::SendAddProvider(query, message)) => {
tracing::trace!(target: LOG_TARGET, ?peer, "send `ADD_PROVIDER` message");
self.executor.send_message(peer, Some(query), message, substream);
}
}
Ok(())
}
/// Remote opened a substream to local node.
async fn on_inbound_substream(&mut self, peer: PeerId, substream: Substream) {
tracing::trace!(target: LOG_TARGET, ?peer, "inbound substream opened");
// Ensure peer entry exists to treat peer as [`ConnectionType::Connected`].
// when inserting into the routing table.
self.peers.entry(peer).or_default();
self.executor.read_message(peer, None, substream);
}
/// Update routing table if the routing table update mode was set to automatic.
///
/// Inform user about the potential routing table, allowing them to update it manually if
/// the mode was set to manual.
async fn update_routing_table(&mut self, peers: &[KademliaPeer]) {
let peers: Vec<_> =
peers.iter().filter(|peer| peer.peer != self.service.local_peer_id()).collect();
// inform user about the routing table update, regardless of what the routing table update
// mode is
let _ = self
.event_tx
.send(KademliaEvent::RoutingTableUpdate {
peers: peers
.iter()
.map(|peer| (peer.peer, peer.addresses()))
.collect::<Vec<(PeerId, Vec<Multiaddr>)>>(),
})
.await;
if std::matches!(self.update_mode, RoutingTableUpdateMode::Automatic) {
for info in peers {
let addresses = info.addresses();
self.service.add_known_address(&info.peer, addresses.clone().into_iter());
self.routing_table.add_known_peer(
info.peer,
addresses,
self.peers
.get(&info.peer)
.map_or(ConnectionType::NotConnected, |_| ConnectionType::Connected),
);
}
}
}
/// Handle received message.
async fn on_message_received(
&mut self,
peer: PeerId,
query_id: Option<QueryId>,
message: BytesMut,
substream: Substream,
) -> crate::Result<()> {
tracing::trace!(target: LOG_TARGET, ?peer, query = ?query_id, "handle message from peer");
match KademliaMessage::from_bytes(message, self.replication_factor)
.ok_or(Error::InvalidData)?
{
KademliaMessage::FindNode { target, peers } => {
match query_id {
Some(query_id) => {
tracing::trace!(
target: LOG_TARGET,
?peer,
?target,
query = ?query_id,
"handle `FIND_NODE` response",
);
// update routing table and inform user about the update
self.update_routing_table(&peers).await;
self.engine.register_response(
query_id,
peer,
KademliaMessage::FindNode { target, peers },
);
substream.close().await;
}
None => {
tracing::trace!(
target: LOG_TARGET,
?peer,
?target,
"handle `FIND_NODE` request",
);
let message = KademliaMessage::find_node_response(
&target,
self.routing_table
.closest(&Key::new(target.as_ref()), self.replication_factor),
);
self.executor.send_message(peer, None, message.into(), substream);
}
}
}
KademliaMessage::PutValue { record } => match query_id {
Some(query_id) => {
tracing::trace!(
target: LOG_TARGET,
?peer,
query = ?query_id,
record_key = ?record.key,
"handle `PUT_VALUE` response",
);
self.engine.register_response(
query_id,
peer,
KademliaMessage::PutValue { record },
);
substream.close().await;
}
None => {
tracing::trace!(
target: LOG_TARGET,
?peer,
record_key = ?record.key,
"handle `PUT_VALUE` request",
);
if let IncomingRecordValidationMode::Automatic = self.validation_mode {
self.store.put(record.clone());
}
// Send ACK even if the record was/will be filtered out to not reveal any
// internal state.
let message = KademliaMessage::put_value_response(
record.key.clone(),
record.value.clone(),
);
self.executor.send_message_eat_failure(peer, None, message, substream);
// TODO: replace this with `send_message` as part of
// https://github.com/paritytech/litep2p/issues/429.
let _ = self.event_tx.send(KademliaEvent::IncomingRecord { record }).await;
}
},
KademliaMessage::GetRecord { key, record, peers } => {
match (query_id, key) {
(Some(query_id), key) => {
tracing::trace!(
target: LOG_TARGET,
?peer,
query = ?query_id,
?peers,
?record,
"handle `GET_VALUE` response",
);
// update routing table and inform user about the update
self.update_routing_table(&peers).await;
self.engine.register_response(
query_id,
peer,
KademliaMessage::GetRecord { key, record, peers },
);
substream.close().await;
}
(None, Some(key)) => {
tracing::trace!(
target: LOG_TARGET,
?peer,
?key,
"handle `GET_VALUE` request",
);
let value = self.store.get(&key).cloned();
let closest_peers = self
.routing_table
.closest(&Key::new(key.as_ref()), self.replication_factor);
let message =
KademliaMessage::get_value_response(key, closest_peers, value);
self.executor.send_message(peer, None, message.into(), substream);
}
(None, None) => tracing::debug!(
target: LOG_TARGET,
?peer,
?record,
?peers,
"unable to handle `GET_RECORD` request with empty key",
),
}
}
KademliaMessage::AddProvider { key, mut providers } => {
tracing::trace!(
target: LOG_TARGET,
?peer,
?key,
?providers,
"handle `ADD_PROVIDER` message",
);
match (providers.len(), providers.pop()) {
(1, Some(provider)) => {
let addresses = provider.addresses();
if provider.peer == peer {
self.store.put_provider(
key.clone(),
ContentProvider {
peer,
addresses: addresses.clone(),
},
);
let _ = self
.event_tx
.send(KademliaEvent::IncomingProvider {
provided_key: key,
provider: ContentProvider {
peer: provider.peer,
addresses,
},
})
.await;
} else {
tracing::trace!(
target: LOG_TARGET,
publisher = ?peer,
provider = ?provider.peer,
"ignoring `ADD_PROVIDER` message with `publisher` != `provider`"
)
}
}
(n, _) => {
tracing::trace!(
target: LOG_TARGET,
publisher = ?peer,
?n,
"ignoring `ADD_PROVIDER` message with `n` != 1 providers"
)
}
}
}
KademliaMessage::GetProviders {
key,
peers,
providers,
} => {
match (query_id, key) {
(Some(query_id), key) => {
// Note: key is not required, but can be non-empty. We just ignore it here.
tracing::trace!(
target: LOG_TARGET,
?peer,
query = ?query_id,
?key,
?peers,
?providers,
"handle `GET_PROVIDERS` response",
);
// update routing table and inform user about the update
self.update_routing_table(&peers).await;
self.engine.register_response(
query_id,
peer,
KademliaMessage::GetProviders {
key,
peers,
providers,
},
);
substream.close().await;
}
(None, Some(key)) => {
tracing::trace!(
target: LOG_TARGET,
?peer,
?key,
"handle `GET_PROVIDERS` request",
);
let mut providers = self.store.get_providers(&key);
// Make sure local provider addresses are up to date.
let local_peer_id = self.local_key.clone().into_preimage();
if let Some(p) =
providers.iter_mut().find(|p| p.peer == local_peer_id).as_mut()
{
p.addresses = self.service.public_addresses().get_addresses();
}
let closer_peers = self
.routing_table
.closest(&Key::new(key.as_ref()), self.replication_factor);
let message =
KademliaMessage::get_providers_response(providers, &closer_peers);
self.executor.send_message(peer, None, message.into(), substream);
}
(None, None) => tracing::debug!(
target: LOG_TARGET,
?peer,
?peers,
?providers,
"unable to handle `GET_PROVIDERS` request with empty key",
),
}
}
}
Ok(())
}
/// Failed to open substream to remote peer.
async fn on_substream_open_failure(
&mut self,
substream_id: SubstreamId,
error: SubstreamError,
) {
tracing::trace!(
target: LOG_TARGET,
?substream_id,
?error,
"failed to open substream"
);
let Some(peer) = self.pending_substreams.remove(&substream_id) else {
tracing::debug!(
target: LOG_TARGET,
?substream_id,
"outbound substream failed for non-existent peer"
);
return;
};
if let Some(context) = self.peers.get_mut(&peer) {
let query =
context.pending_actions.remove(&substream_id).as_ref().map(PeerAction::query_id);
self.disconnect_peer(peer, query).await;
}
}
/// Handle dial failure.
fn on_dial_failure(&mut self, peer: PeerId, addresses: Vec<Multiaddr>) {
tracing::trace!(target: LOG_TARGET, ?peer, ?addresses, "failed to dial peer");
self.routing_table.on_dial_failure(Key::from(peer), &addresses);
let Some(actions) = self.pending_dials.remove(&peer) else {
return;
};
for action in actions {
let query = action.query_id();
tracing::trace!(
target: LOG_TARGET,
?peer,
?query,
?addresses,
"report failure for pending query",
);
// Fail both sending and receiving due to dial failure.
self.engine.register_send_failure(query, peer);
self.engine.register_response_failure(query, peer);
}
}
/// Open a substream with a peer or dial the peer.
fn open_substream_or_dial(
&mut self,
peer: PeerId,
action: PeerAction,
query: Option<QueryId>,
) -> Result<(), Error> {
match self.service.open_substream(peer) {
Ok(substream_id) => {
self.pending_substreams.insert(substream_id, peer);
self.peers.entry(peer).or_default().pending_actions.insert(substream_id, action);
Ok(())
}
Err(err) => {
tracing::trace!(target: LOG_TARGET, ?query, ?peer, ?err, "Failed to open substream. Dialing peer");
match self.service.dial(&peer) {
Ok(()) => {
self.pending_dials.entry(peer).or_default().push(action);
Ok(())
}
// Already connected is a recoverable error.
Err(ImmediateDialError::AlreadyConnected) => {
// Dial returned `Error::AlreadyConnected`, retry opening the substream.
match self.service.open_substream(peer) {
Ok(substream_id) => {
self.pending_substreams.insert(substream_id, peer);
self.peers
.entry(peer)
.or_default()
.pending_actions
.insert(substream_id, action);
Ok(())
}
Err(err) => {
tracing::debug!(target: LOG_TARGET, ?query, ?peer, ?err, "Failed to open substream a second time");
Err(err.into())
}
}
}
Err(error) => {
tracing::trace!(target: LOG_TARGET, ?query, ?peer, ?error, "Failed to dial peer");
Err(error.into())
}
}
}
}
}
/// Handle next query action.
async fn on_query_action(&mut self, action: QueryAction) -> Result<(), (QueryId, PeerId)> {
match action {
QueryAction::SendMessage { query, peer, .. } => {
// This action is used for `FIND_NODE`, `GET_VALUE` and `GET_PROVIDERS` queries.
if self
.open_substream_or_dial(peer, PeerAction::SendFindNode(query), Some(query))
.is_err()
{
// Announce the error to the query engine.
self.engine.register_send_failure(query, peer);
self.engine.register_response_failure(query, peer);
}
Ok(())
}
QueryAction::FindNodeQuerySucceeded {
target,
peers,
query,
} => {
tracing::debug!(
target: LOG_TARGET,
?query,
peer = ?target,
num_peers = ?peers.len(),
"`FIND_NODE` succeeded",
);
let _ = self
.event_tx
.send(KademliaEvent::FindNodeSuccess {
target,
query_id: query,
peers: peers
.into_iter()
.map(|info| (info.peer, info.addresses()))
.collect(),
})
.await;
Ok(())
}
QueryAction::PutRecordToFoundNodes {
query,
record,
peers,
quorum,
} => {
tracing::trace!(
target: LOG_TARGET,
?query,
record_key = ?record.key,
num_peers = ?peers.len(),
"store record to found peers",
);
let key = record.key.clone();
let message: Bytes = KademliaMessage::put_value(record);
for peer in &peers {
if let Err(error) = self.open_substream_or_dial(
peer.peer,
// `message` is cheaply clonable because of `Bytes` reference counting.
PeerAction::SendPutValue(query, message.clone()),
None,
) {
tracing::debug!(
target: LOG_TARGET,
?peer,
?key,
?error,
"failed to put record to peer",
);
}
}
self.engine.start_put_record_to_found_nodes_requests_tracking(
query,
key,
peers.into_iter().map(|peer| peer.peer).collect(),
quorum,
);
Ok(())
}
QueryAction::PutRecordQuerySucceeded { query, key } => {
tracing::debug!(target: LOG_TARGET, ?query, "`PUT_VALUE` query succeeded");
let _ = self
.event_tx
.send(KademliaEvent::PutRecordSuccess {
query_id: query,
key,
})
.await;
Ok(())
}
QueryAction::AddProviderToFoundNodes {
query,
provided_key,
provider,
peers,
quorum,
} => {
tracing::trace!(
target: LOG_TARGET,
?provided_key,
num_peers = ?peers.len(),
"add provider record to found peers",
);
let message = KademliaMessage::add_provider(provided_key.clone(), provider);
for peer in &peers {
if let Err(error) = self.open_substream_or_dial(
peer.peer,
PeerAction::SendAddProvider(query, message.clone()),
None,
) {
tracing::debug!(
target: LOG_TARGET,
?peer,
?provided_key,
?error,
"failed to add provider record to peer",
)
}
}
self.engine.start_add_provider_to_found_nodes_requests_tracking(
query,
provided_key,
peers.into_iter().map(|peer| peer.peer).collect(),
quorum,
);
Ok(())
}
QueryAction::AddProviderQuerySucceeded {
query,
provided_key,
} => {
tracing::debug!(target: LOG_TARGET, ?query, "`ADD_PROVIDER` query succeeded");
let _ = self
.event_tx
.send(KademliaEvent::AddProviderSuccess {
query_id: query,
provided_key,
})
.await;
Ok(())
}
QueryAction::GetRecordQueryDone { query_id } => {
let _ = self.event_tx.send(KademliaEvent::GetRecordSuccess { query_id }).await;
Ok(())
}
QueryAction::GetProvidersQueryDone {
query_id,
provided_key,
providers,
} => {
let _ = self
.event_tx
.send(KademliaEvent::GetProvidersSuccess {
query_id,
provided_key,