use sc_network::ReputationChange;
use sc_network_types::PeerId;
use sp_runtime::traits::{Block, NumberFor, Zero};
use std::collections::{HashMap, VecDeque};
#[derive(Debug, PartialEq)]
pub struct PeerReport {
pub who: PeerId,
pub cost_benefit: ReputationChange,
}
struct PeerData<B: Block> {
last_voted_on: NumberFor<B>,
}
impl<B: Block> Default for PeerData<B> {
fn default() -> Self {
PeerData { last_voted_on: Zero::zero() }
}
}
pub struct KnownPeers<B: Block> {
live: HashMap<PeerId, PeerData<B>>,
}
impl<B: Block> KnownPeers<B> {
pub fn new() -> Self {
Self { live: HashMap::new() }
}
pub fn note_vote_for(&mut self, peer: PeerId, round: NumberFor<B>) {
let data = self.live.entry(peer).or_default();
data.last_voted_on = round.max(data.last_voted_on);
}
pub fn remove(&mut self, peer: &PeerId) {
self.live.remove(peer);
}
pub fn further_than(&self, block: NumberFor<B>) -> VecDeque<PeerId> {
self.live
.iter()
.filter_map(|(k, v)| (v.last_voted_on > block).then_some(k))
.cloned()
.collect()
}
pub fn contains(&self, peer: &PeerId) -> bool {
self.live.contains_key(peer)
}
pub fn len(&self) -> usize {
self.live.len()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn should_track_known_peers_progress() {
let (alice, bob, charlie) = (PeerId::random(), PeerId::random(), PeerId::random());
let mut peers = KnownPeers::<sc_network_test::Block>::new();
assert!(peers.live.is_empty());
peers.note_vote_for(bob, 5);
peers.note_vote_for(charlie, 10);
assert_eq!(peers.live.len(), 2);
assert!(!peers.contains(&alice));
assert!(peers.contains(&bob));
assert!(peers.contains(&charlie));
let further_than_4 = peers.further_than(4);
assert_eq!(further_than_4.len(), 2);
assert!(further_than_4.contains(&bob));
assert!(further_than_4.contains(&charlie));
peers.note_vote_for(alice, 10);
let further_than_9 = peers.further_than(9);
assert_eq!(further_than_9.len(), 2);
assert!(further_than_9.contains(&charlie));
assert!(further_than_9.contains(&alice));
peers.remove(&alice);
assert_eq!(peers.live.len(), 2);
assert!(!peers.contains(&alice));
let further_than_9 = peers.further_than(9);
assert_eq!(further_than_9.len(), 1);
assert!(further_than_9.contains(&charlie));
}
}