Skip to content

Commit 8993a75

Browse files
network: don't log re-discovered addresses (paritytech#6881)
* network: move LruHashSet to network crate utils * network: don't log re-discovered external addresses * Update client/network/src/utils.rs Co-authored-by: mattrutherford <44339188+mattrutherford@users.noreply.github.com> Co-authored-by: mattrutherford <44339188+mattrutherford@users.noreply.github.com>
1 parent 4d3c948 commit 8993a75

File tree

4 files changed

+94
-89
lines changed

4 files changed

+94
-89
lines changed

client/network/src/discovery.rs

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
//!
4747
4848
use crate::config::ProtocolId;
49+
use crate::utils::LruHashSet;
4950
use futures::prelude::*;
5051
use futures_timer::Delay;
5152
use ip_network::IpNetwork;
@@ -63,10 +64,15 @@ use libp2p::swarm::toggle::Toggle;
6364
use libp2p::mdns::{Mdns, MdnsEvent};
6465
use libp2p::multiaddr::Protocol;
6566
use log::{debug, info, trace, warn};
66-
use std::{cmp, collections::{HashMap, HashSet, VecDeque}, io, time::Duration};
67+
use std::{cmp, collections::{HashMap, HashSet, VecDeque}, io, num::NonZeroUsize, time::Duration};
6768
use std::task::{Context, Poll};
6869
use sp_core::hexdisplay::HexDisplay;
6970

71+
/// Maximum number of known external addresses that we will cache.
72+
/// This only affects whether we will log whenever we (re-)discover
73+
/// a given address.
74+
const MAX_KNOWN_EXTERNAL_ADDRESSES: usize = 32;
75+
7076
/// `DiscoveryBehaviour` configuration.
7177
///
7278
/// Note: In order to discover nodes or load and store values via Kademlia one has to add at least
@@ -190,7 +196,11 @@ impl DiscoveryConfig {
190196
} else {
191197
None.into()
192198
},
193-
allow_non_globals_in_dht: self.allow_non_globals_in_dht
199+
allow_non_globals_in_dht: self.allow_non_globals_in_dht,
200+
known_external_addresses: LruHashSet::new(
201+
NonZeroUsize::new(MAX_KNOWN_EXTERNAL_ADDRESSES)
202+
.expect("value is a constant; constant is non-zero; qed.")
203+
),
194204
}
195205
}
196206
}
@@ -221,7 +231,9 @@ pub struct DiscoveryBehaviour {
221231
/// Number of active connections over which we interrupt the discovery process.
222232
discovery_only_if_under_num: u64,
223233
/// Should non-global addresses be added to the DHT?
224-
allow_non_globals_in_dht: bool
234+
allow_non_globals_in_dht: bool,
235+
/// A cache of discovered external addresses. Only used for logging purposes.
236+
known_external_addresses: LruHashSet<Multiaddr>,
225237
}
226238

227239
impl DiscoveryBehaviour {
@@ -507,7 +519,16 @@ impl NetworkBehaviour for DiscoveryBehaviour {
507519
fn inject_new_external_addr(&mut self, addr: &Multiaddr) {
508520
let new_addr = addr.clone()
509521
.with(Protocol::P2p(self.local_peer_id.clone().into()));
510-
info!(target: "sub-libp2p", "🔍 Discovered new external address for our node: {}", new_addr);
522+
523+
// NOTE: we might re-discover the same address multiple times
524+
// in which case we just want to refrain from logging.
525+
if self.known_external_addresses.insert(new_addr.clone()) {
526+
info!(target: "sub-libp2p",
527+
"🔍 Discovered new external address for our node: {}",
528+
new_addr,
529+
);
530+
}
531+
511532
for k in self.kademlias.values_mut() {
512533
NetworkBehaviour::inject_new_external_addr(k, addr)
513534
}

client/network/src/protocol.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ use crate::{
2121
chain::{Client, FinalityProofProvider},
2222
config::{BoxFinalityProofRequestBuilder, ProtocolId, TransactionPool, TransactionImportFuture, TransactionImport},
2323
error,
24-
utils::interval
24+
utils::{interval, LruHashSet},
2525
};
2626

2727
use bytes::{Bytes, BytesMut};
@@ -60,11 +60,9 @@ use std::fmt::Write;
6060
use std::{cmp, io, num::NonZeroUsize, pin::Pin, task::Poll, time};
6161
use log::{log, Level, trace, debug, warn, error};
6262
use sc_client_api::{ChangesProof, StorageProof};
63-
use util::LruHashSet;
6463
use wasm_timer::Instant;
6564

6665
mod generic_proto;
67-
mod util;
6866

6967
pub mod message;
7068
pub mod event;

client/network/src/protocol/util.rs

Lines changed: 0 additions & 76 deletions
This file was deleted.

client/network/src/utils.rs

Lines changed: 68 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,74 @@
1414
// You should have received a copy of the GNU General Public License
1515
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
1616

17-
use std::time::Duration;
18-
use futures::{FutureExt, Stream, StreamExt, stream::unfold};
17+
use futures::{stream::unfold, FutureExt, Stream, StreamExt};
1918
use futures_timer::Delay;
19+
use linked_hash_set::LinkedHashSet;
20+
use std::time::Duration;
21+
use std::{hash::Hash, num::NonZeroUsize};
22+
23+
/// Creates a stream that returns a new value every `duration`.
24+
pub fn interval(duration: Duration) -> impl Stream<Item = ()> + Unpin {
25+
unfold((), move |_| Delay::new(duration).map(|_| Some(((), ())))).map(drop)
26+
}
27+
28+
/// Wrapper around `LinkedHashSet` with bounded growth.
29+
///
30+
/// In the limit, for each element inserted the oldest existing element will be removed.
31+
#[derive(Debug, Clone)]
32+
pub struct LruHashSet<T: Hash + Eq> {
33+
set: LinkedHashSet<T>,
34+
limit: NonZeroUsize,
35+
}
36+
37+
impl<T: Hash + Eq> LruHashSet<T> {
38+
/// Create a new `LruHashSet` with the given (exclusive) limit.
39+
pub fn new(limit: NonZeroUsize) -> Self {
40+
Self {
41+
set: LinkedHashSet::new(),
42+
limit,
43+
}
44+
}
45+
46+
/// Insert element into the set.
47+
///
48+
/// Returns `true` if this is a new element to the set, `false` otherwise.
49+
/// Maintains the limit of the set by removing the oldest entry if necessary.
50+
/// Inserting the same element will update its LRU position.
51+
pub fn insert(&mut self, e: T) -> bool {
52+
if self.set.insert(e) {
53+
if self.set.len() == usize::from(self.limit) {
54+
self.set.pop_front(); // remove oldest entry
55+
}
56+
return true;
57+
}
58+
false
59+
}
60+
}
61+
62+
#[cfg(test)]
63+
mod tests {
64+
use super::*;
65+
66+
#[test]
67+
fn maintains_limit() {
68+
let three = NonZeroUsize::new(3).unwrap();
69+
let mut set = LruHashSet::<u8>::new(three);
70+
71+
// First element.
72+
assert!(set.insert(1));
73+
assert_eq!(vec![&1], set.set.iter().collect::<Vec<_>>());
74+
75+
// Second element.
76+
assert!(set.insert(2));
77+
assert_eq!(vec![&1, &2], set.set.iter().collect::<Vec<_>>());
78+
79+
// Inserting the same element updates its LRU position.
80+
assert!(!set.insert(1));
81+
assert_eq!(vec![&2, &1], set.set.iter().collect::<Vec<_>>());
2082

21-
pub fn interval(duration: Duration) -> impl Stream<Item=()> + Unpin {
22-
unfold((), move |_| {
23-
Delay::new(duration).map(|_| Some(((), ())))
24-
}).map(drop)
83+
// We reached the limit. The next element forces the oldest one out.
84+
assert!(set.insert(3));
85+
assert_eq!(vec![&1, &3], set.set.iter().collect::<Vec<_>>());
86+
}
2587
}

0 commit comments

Comments
 (0)