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
use message_io::network::Endpoint;
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, iter::Iterator, net::SocketAddr};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Message {
RetrievePubAddr(SocketAddr),
RetrievePeerList,
RespondToListQuery(Vec<SocketAddr>),
RequestRandomInfo(String),
}
enum NodeInfo {
OldInfo,
NewInfo(SocketAddr),
}
pub struct NodeAddr {
pub public: SocketAddr,
pub endpoint: Endpoint,
}
pub struct NodeMap {
map: HashMap<Endpoint, NodeInfo>,
self_pub_addr: SocketAddr,
}
impl NodeMap {
pub fn new(self_pub_addr: SocketAddr) -> Self {
Self {
map: HashMap::new(),
self_pub_addr,
}
}
pub fn add_old_one(&mut self, endpoint: Endpoint) {
self.map.insert(endpoint, NodeInfo::OldInfo);
}
pub fn add_new_one(&mut self, endpoint: Endpoint, pub_addr: SocketAddr) {
self.map.insert(endpoint, NodeInfo::NewInfo(pub_addr));
}
pub fn drop(&mut self, endpoint: Endpoint) {
self.map.remove(&endpoint);
}
pub fn get_peers_list(&self) -> Vec<SocketAddr> {
let mut list: Vec<SocketAddr> = Vec::with_capacity(self.map.len() + 1);
list.push(self.self_pub_addr);
self.map
.iter()
.map(|(endpoint, info)| match info {
NodeInfo::OldInfo => endpoint.addr(),
NodeInfo::NewInfo(public_addr) => *public_addr,
})
.for_each(|addr| {
list.push(addr);
});
list
}
pub fn fetch_receivers(&self) -> Vec<NodeAddr> {
self.map
.iter()
.map(|(endpoint, info)| {
let public = match info {
NodeInfo::OldInfo => endpoint.addr(),
NodeInfo::NewInfo(public_addr) => *public_addr,
};
NodeAddr {
endpoint: *endpoint,
public,
}
})
.collect()
}
pub fn get_pub_addr(&self, endpoint: &Endpoint) -> Option<SocketAddr> {
self.map.get(endpoint).map(|info| match info {
NodeInfo::OldInfo => endpoint.addr(),
NodeInfo::NewInfo(addr) => *addr,
})
}
}