Rewrite MetaAddr::sanitize so it's harder to misuse

`sanitize` could be misused in two ways:
* accidentally modifying the addresses in the address book itself
* forgetting to sanitize new fields added to `MetaAddr`

This change prevents accidental modification by taking `&self`, and
explicitly creates a new sanitized `MetaAddr` with all fields listed.
This commit is contained in:
teor 2021-03-25 17:47:25 +10:00
parent c5bad9fac2
commit e9cdc224a2
2 changed files with 14 additions and 6 deletions

View File

@ -70,7 +70,10 @@ impl AddressBook {
pub fn sanitized(&self) -> Vec<MetaAddr> {
use rand::seq::SliceRandom;
let _guard = self.span.enter();
let mut peers = self.peers().map(MetaAddr::sanitize).collect::<Vec<_>>();
let mut peers = self
.peers()
.map(|a| MetaAddr::sanitize(&a))
.collect::<Vec<_>>();
peers.shuffle(&mut rand::thread_rng());
peers
}

View File

@ -124,13 +124,18 @@ pub struct MetaAddr {
}
impl MetaAddr {
/// Sanitize this `MetaAddr` before sending it to a remote peer.
pub fn sanitize(mut self) -> MetaAddr {
/// Return a sanitized version of this `MetaAddr`, for sending to a remote peer.
pub fn sanitize(&self) -> MetaAddr {
let interval = crate::constants::TIMESTAMP_TRUNCATION_SECONDS;
let ts = self.last_seen.timestamp();
self.last_seen = Utc.timestamp(ts - ts.rem_euclid(interval), 0);
self.last_connection_state = Default::default();
self
let last_seen = Utc.timestamp(ts - ts.rem_euclid(interval), 0);
MetaAddr {
addr: self.addr,
services: self.services,
last_seen,
// the state isn't sent to the remote peer, but sanitize it anyway
last_connection_state: Default::default(),
}
}
}