Do not return peers with only expired addresses. (#325)

This commit is contained in:
Toralf Wittner 2018-07-18 14:37:01 +02:00 committed by Pierre Krieger
parent cbc845d345
commit bd169a5a4b
3 changed files with 20 additions and 7 deletions

View File

@ -91,7 +91,10 @@ impl<'a> Peerstore for &'a JsonPeerstore {
}); });
let list = query let list = query
.filter_map(|(key, _)| { .filter_map(|(key, info)| {
if info.addrs().count() == 0 {
return None // all addresses are expired
}
// We filter out invalid elements. This can happen if the JSON storage file was // We filter out invalid elements. This can happen if the JSON storage file was
// corrupted or manually modified by the user. // corrupted or manually modified by the user.
PeerId::from_bytes(bs58::decode(key).into_vec().ok()?).ok() PeerId::from_bytes(bs58::decode(key).into_vec().ok()?).ok()

View File

@ -75,7 +75,14 @@ impl<'a> Peerstore for &'a MemoryPeerstore {
fn peers(self) -> Self::PeersIter { fn peers(self) -> Self::PeersIter {
let lock = self.store.lock().unwrap(); let lock = self.store.lock().unwrap();
lock.keys().cloned().collect::<Vec<_>>().into_iter() lock.iter()
.filter_map(|(id, info)| {
if info.addrs().count() == 0 {
return None // all addresses are expired
}
Some(id.clone())
})
.collect::<Vec<_>>().into_iter()
} }
} }

View File

@ -52,13 +52,16 @@ impl PeerInfo {
/// ///
/// > **Note**: Keep in mind that this function is racy because addresses can expire between /// > **Note**: Keep in mind that this function is racy because addresses can expire between
/// > the moment when you get them and the moment when you process them. /// > the moment when you get them and the moment when you process them.
// TODO: use -> impl Iterator eventually
#[inline] #[inline]
pub fn addrs<'a>(&'a self) -> Box<Iterator<Item = &'a Multiaddr> + 'a> { pub fn addrs<'a>(&'a self) -> impl Iterator<Item = &'a Multiaddr> + 'a {
let now = SystemTime::now(); let now = SystemTime::now();
Box::new(self.addrs.iter().filter_map( self.addrs.iter().filter_map(move |(addr, expires)| {
move |&(ref addr, ref expires)| if *expires >= now { Some(addr) } else { None }, if *expires >= now {
)) Some(addr)
} else {
None
}
})
} }
/// Sets the list of addresses and their time-to-live. /// Sets the list of addresses and their time-to-live.