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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
use crate::{
    metrics::{Metrics, MetricsBackend},
    network::{
        client::ConnectHandle,
        p2p::comm::{Address, PeerComms, PeerInfo, PeerStats},
        security_params::NONCE_LEN,
    },
    topology::NodeId,
};
use chain_network::error::{Code as ErrorCode, Error as NetworkError};
use linked_hash_map::LinkedHashMap;
use lru::LruCache;
use rand::Rng;

/// Peer authentication is checked during the handshake. For client connections, we simply
/// do not add a peer to the map if the authentication fails.
/// On the server side instead, we need to keep track of in progress handshakes until we have
/// authenticated reliably a node by its id.
/// FIXME: In addition, until a better solution is implemented, a correspondence between addresses
/// and ids is needed to handle subscriptions. However, this is subject to ip spoofing
/// attacks and should not be used in an open network.
pub struct ClientAuth {
    // Limit the number of in progress handshakes to prevent SYN flood-like resource exhaustion attacks
    in_progress: LruCache<Address, [u8; NONCE_LEN]>,
    established: LinkedHashMap<Address, NodeId>,
}

impl Default for ClientAuth {
    fn default() -> Self {
        Self {
            in_progress: LruCache::new(ClientAuth::DEFAULT_OPEN_HANDSHAKED_LIMIT),
            established: LinkedHashMap::new(),
        }
    }
}

impl ClientAuth {
    const DEFAULT_OPEN_HANDSHAKED_LIMIT: usize = 128;

    pub fn generate_auth_nonce(&mut self, addr: Address) -> [u8; NONCE_LEN] {
        let mut nonce = [0u8; NONCE_LEN];
        rand::thread_rng().fill(&mut nonce[..]);

        self.established.remove(&addr);
        self.in_progress.put(addr, nonce);
        nonce
    }

    pub fn complete_handshake<F>(
        &mut self,
        addr: Address,
        id: NodeId,
        verify: F,
    ) -> Result<(), NetworkError>
    where
        F: FnOnce([u8; NONCE_LEN]) -> Result<(), NetworkError>,
    {
        if let Some(nonce) = self.in_progress.pop(&addr) {
            verify(nonce)?;
            self.established.insert(addr, id);
            Ok(())
        } else {
            Err(NetworkError::new(
                ErrorCode::FailedPrecondition,
                "nonce missing, perform handshake first",
            ))
        }
    }

    pub fn remove(&mut self, addr: Address) -> Option<NodeId> {
        self.established.remove(&addr)
    }

    pub fn client_id(&self, addr: Address) -> Option<&NodeId> {
        self.established.get(&addr)
    }
}

pub struct PeerMap {
    map: LinkedHashMap<NodeId, PeerData>,
    client_auth: ClientAuth,
    capacity: usize,
    stats_counter: Metrics,
}

struct PeerData {
    comms: PeerComms,
    stats: PeerStats,
    connecting: Option<ConnectHandle>,
}

pub enum CommStatus<'a> {
    Connecting(&'a mut PeerComms),
    Established(&'a mut PeerComms),
}

impl PeerData {
    fn new(remote_addr: Address) -> Self {
        Self {
            comms: PeerComms::new(remote_addr),
            stats: Default::default(),
            connecting: Default::default(),
        }
    }

    fn update_comm_status(&mut self) -> CommStatus<'_> {
        if let Some(ref mut handle) = self.connecting {
            match handle.try_complete() {
                Ok(None) => return CommStatus::Connecting(&mut self.comms),
                Ok(Some(comms)) => {
                    self.connecting = None;
                    self.comms.update(comms);
                }
                Err(_) => {
                    self.connecting = None;
                }
            }
        }
        CommStatus::Established(&mut self.comms)
    }

    fn server_comms(&mut self) -> &mut PeerComms {
        // This method is called when a handshake or subscription request is
        // received by the server, normally after when the peer connects
        // as a client. Cancel client connection if it is pending.
        //
        // TODO: remove client-server connection resolution logic
        // since we tabulate peer entries per address rather than node ID.
        self.connecting = None;
        self.comms.clear_pending();
        &mut self.comms
    }
}

impl<'a> CommStatus<'a> {
    fn comms(self) -> &'a mut PeerComms {
        match self {
            CommStatus::Connecting(comms) => comms,
            CommStatus::Established(comms) => comms,
        }
    }
}

impl PeerMap {
    pub fn new(capacity: usize, stats_counter: Metrics) -> Self {
        PeerMap {
            map: LinkedHashMap::new(),
            client_auth: ClientAuth::default(),
            capacity,
            stats_counter,
        }
    }

    pub fn entry(&mut self, id: NodeId) -> Option<Entry<'_>> {
        use linked_hash_map::Entry::*;

        match self.map.entry(id) {
            Vacant(_) => None,
            Occupied(entry) => {
                let auth_info = self
                    .client_auth
                    .established
                    .entry(entry.get().comms.remote_addr);
                Some(Entry {
                    inner: entry,
                    auth_info,
                    stats_counter: &self.stats_counter,
                })
            }
        }
    }

    /// for clearing the peer map
    pub fn clear(&mut self) {
        self.stats_counter.sub_peer_connected_cnt(self.map.len());
        self.map.clear()
    }

    /// Returns metadata of most recent peer interaction with given node
    pub fn refresh_peer(&mut self, id: &NodeId) -> Option<&mut PeerStats> {
        self.map.get_refresh(id).map(|data| &mut data.stats)
    }

    pub fn peer_comms(&mut self, id: &NodeId) -> Option<&mut PeerComms> {
        self.map
            .get_mut(id)
            .map(|data| data.update_comm_status().comms())
    }

    /// Inserts peer and returns associated metadata
    fn join_peer(&mut self, id: NodeId, remote_addr: Address) -> &mut PeerData {
        if !self.map.contains_key(&id) {
            self.evict_if_full();
            self.stats_counter.add_peer_connected_cnt(1);
        }
        self.map
            .entry(id)
            .or_insert_with(|| PeerData::new(remote_addr))
    }

    pub fn server_comms(&mut self, id: &NodeId) -> Option<&mut PeerComms> {
        self.map.get_mut(id).map(|peer| peer.server_comms())
    }

    pub fn generate_auth_nonce(&mut self, addr: Address) -> [u8; NONCE_LEN] {
        self.client_auth.generate_auth_nonce(addr)
    }

    pub fn client_id(&self, peer_addr: Address) -> Option<&NodeId> {
        self.client_auth.client_id(peer_addr)
    }

    pub fn complete_handshake<F>(
        &mut self,
        addr: Address,
        id: NodeId,
        verify: F,
    ) -> Result<(), NetworkError>
    where
        F: FnOnce([u8; NONCE_LEN]) -> Result<(), NetworkError>,
    {
        self.client_auth.complete_handshake(addr, id, verify)?;
        self.add_client(id, addr);
        Ok(())
    }

    // This is called when connecting as a client to another node
    pub fn add_connecting(
        &mut self,
        id: NodeId,
        remote_addr: Address,
        handle: ConnectHandle,
    ) -> &mut PeerComms {
        let data = self.join_peer(id, remote_addr);
        data.connecting = Some(handle);
        data.update_comm_status().comms()
    }

    // This is called when accepting client connections as a server
    pub fn add_client(&mut self, id: NodeId, remote_addr: Address) -> &mut PeerComms {
        let data = self.join_peer(id, remote_addr);
        data.update_comm_status().comms()
    }

    pub fn remove_peer(&mut self, id: &NodeId) -> Option<PeerComms> {
        self.map.remove(id).map(|mut data| {
            // A bit tricky here: use PeerData::update_comm_status for the
            // side effect, then return the up-to-date member.
            data.update_comm_status();
            self.stats_counter.sub_peer_connected_cnt(1);
            self.client_auth.remove(data.comms.remote_addr());
            data.comms
        })
    }

    pub fn next_peer_for_block_fetch(&mut self) -> Option<(NodeId, &mut PeerComms)> {
        let mut iter = self.map.iter_mut();
        while let Some((id, data)) = iter.next_back() {
            match data.update_comm_status() {
                CommStatus::Established(comms) => return Some((*id, comms)),
                CommStatus::Connecting(_) => {}
            };
        }
        None
    }

    pub fn infos(&self) -> Vec<PeerInfo> {
        self.map
            .iter()
            .map(|(&id, data)| PeerInfo {
                id,
                addr: Some(data.comms.remote_addr),
                stats: data.stats.clone(),
            })
            .collect()
    }

    pub fn evict_clients(&mut self, num: usize) {
        for entry in self
            .map
            .entries()
            .filter(|entry| entry.get().comms.has_client_subscriptions())
            .take(num)
        {
            entry.remove();
        }
    }

    fn evict_if_full(&mut self) {
        if self.map.len() >= self.capacity {
            if let Some((_, v)) = self.map.pop_front() {
                self.stats_counter.sub_peer_connected_cnt(1);
                self.client_auth.remove(v.comms.remote_addr());
            }
        }
    }
}

pub struct Entry<'a> {
    inner: linked_hash_map::OccupiedEntry<'a, NodeId, PeerData>,
    auth_info: linked_hash_map::Entry<'a, Address, NodeId>,
    stats_counter: &'a Metrics,
}

impl<'a> Entry<'a> {
    pub fn update_comm_status(&mut self) -> CommStatus<'_> {
        self.inner.get_mut().update_comm_status()
    }

    pub fn remove(self) {
        use linked_hash_map::Entry::*;
        self.inner.remove();
        self.stats_counter.sub_peer_connected_cnt(1);
        if let Occupied(entry) = self.auth_info {
            entry.remove();
        }
    }
}