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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
// Copyright 2019 Conflux Foundation. All rights reserved.
// Conflux is free software and distributed under GNU General Public License.
// See http://www.gnu.org/licenses/

#![allow(deprecated)]
use cfxkey as keylib;
use io as iolib;
use keccak_hash as hash;

pub const PROTOCOL_ID_SIZE: usize = 3;
pub type ProtocolId = [u8; PROTOCOL_ID_SIZE];
pub type HandlerWorkType = u8;
pub type PeerId = usize;

mod connection;
mod discovery;
mod error;
mod handshake;
mod ip;
mod ip_utils;
mod node_database;
pub mod node_table;
pub mod service;
mod session;
mod session_manager;
pub mod throttling;

pub use crate::{
    error::{DisconnectReason, Error, ThrottlingReason},
    ip::SessionIpLimitConfig,
    node_table::Node,
    service::NetworkService,
    session::SessionDetails,
};
pub use io::TimerToken;

use crate::{
    node_table::NodeId,
    service::{
        ProtocolVersion, DEFAULT_CONNECTION_LIFETIME_FOR_PROMOTION,
        DEFAULT_DISCOVERY_REFRESH_TIMEOUT, DEFAULT_DISCOVERY_ROUND_TIMEOUT,
        DEFAULT_FAST_DISCOVERY_REFRESH_TIMEOUT, DEFAULT_HOUSEKEEPING_TIMEOUT,
        DEFAULT_NODE_TABLE_TIMEOUT,
    },
};
use cfx_addr::Network;
use diem_types::validator_config::{ConsensusPublicKey, ConsensusVRFPublicKey};
use ipnetwork::{IpNetwork, IpNetworkError};
use keylib::Secret;
use priority_send_queue::SendQueuePriority;
use rlp::{Decodable, DecoderError, Encodable, Rlp, RlpStream};
use serde_derive::{Deserialize, Serialize};
use std::{
    cmp::Ordering,
    net::{Ipv4Addr, SocketAddr, SocketAddrV4},
    str::{self, FromStr},
    sync::Arc,
    time::{Duration, SystemTime, UNIX_EPOCH},
};

pub const NODE_TAG_NODE_TYPE: &str = "node_type";
pub const NODE_TAG_ARCHIVE: &str = "archive";
pub const NODE_TAG_FULL: &str = "full";

#[derive(Debug, Clone, PartialEq)]
pub struct NetworkConfiguration {
    pub is_consortium: bool,
    /// Network identifier
    pub id: u64,
    network_type: Network,
    /// Directory path to store general network configuration. None means
    /// nothing will be saved
    pub config_path: Option<String>,
    pub listen_address: Option<SocketAddr>,
    /// IP address to advertise. Detected automatically if none.
    pub public_address: Option<SocketAddr>,
    pub udp_port: Option<u16>,
    /// Enable NAT configuration
    pub nat_enabled: bool,
    /// Enable discovery
    pub discovery_enabled: bool,
    pub boot_nodes: Vec<String>,
    /// Use provided node key instead of default
    pub use_secret: Option<Secret>,
    /// Maximum number of outgoing peers
    pub max_outgoing_peers: usize,
    /// Maximum number of outgoing connections to archive nodes. 0 represents
    /// not required to connect to archive nodes. E.g. light node or full node
    /// need not to connect to archive nodes.
    pub max_outgoing_peers_archive: usize,
    /// Maximum number of incoming peers
    pub max_incoming_peers: usize,
    /// Maximum number of ongoing handshakes
    pub max_handshakes: usize,
    /// List of reserved node addresses.
    pub reserved_nodes: Vec<String>,
    /// IP filter
    pub ip_filter: IpFilter,
    /// Timeout duration for initiating peer connection management
    pub housekeeping_timeout: Duration,
    /// Timeout duration for refreshing discovery protocol
    /// when there are enough outgoing connections
    pub discovery_refresh_timeout: Duration,
    /// Timeout duration for refreshing discovery protocol
    /// when there are NOT enough outgoing connections
    pub fast_discovery_refresh_timeout: Duration,
    /// Period between consecutive rounds of the same current discovery process
    pub discovery_round_timeout: Duration,
    /// Timeout duration for persisting node table
    pub node_table_timeout: Duration,
    /// Connection lifetime threshold for promotion
    pub connection_lifetime_for_promotion: Duration,
    pub test_mode: bool,
    /// Maximum number of P2P nodes for subnet B (ip/16).
    pub subnet_quota: usize,
    pub session_ip_limit_config: SessionIpLimitConfig,

    pub discovery_config: DiscoveryConfiguration,
}

impl NetworkConfiguration {
    pub fn new(id: u64, discovery_config: DiscoveryConfiguration) -> Self {
        let network_type = Self::network_id_to_known_cfx_network(id);

        NetworkConfiguration {
            is_consortium: false,
            id,
            network_type,
            config_path: Some("./net_config".to_string()),
            listen_address: None,
            public_address: None,
            udp_port: None,
            nat_enabled: true,
            discovery_enabled: false,
            boot_nodes: Vec::new(),
            use_secret: None,
            max_outgoing_peers: 0,
            max_outgoing_peers_archive: 0,
            max_incoming_peers: 0,
            max_handshakes: 0,
            reserved_nodes: Vec::new(),
            ip_filter: IpFilter::default(),
            housekeeping_timeout: DEFAULT_HOUSEKEEPING_TIMEOUT,
            discovery_refresh_timeout: DEFAULT_DISCOVERY_REFRESH_TIMEOUT,
            fast_discovery_refresh_timeout:
                DEFAULT_FAST_DISCOVERY_REFRESH_TIMEOUT,
            discovery_round_timeout: DEFAULT_DISCOVERY_ROUND_TIMEOUT,
            node_table_timeout: DEFAULT_NODE_TABLE_TIMEOUT,
            connection_lifetime_for_promotion:
                DEFAULT_CONNECTION_LIFETIME_FOR_PROMOTION,
            test_mode: false,
            subnet_quota: 32,
            session_ip_limit_config: SessionIpLimitConfig::default(),
            discovery_config,
        }
    }

    pub fn new_with_port(
        id: u64, port: u16, discovery_config: DiscoveryConfiguration,
    ) -> NetworkConfiguration {
        let mut config = NetworkConfiguration::new(id, discovery_config);
        config.listen_address = Some(SocketAddr::V4(SocketAddrV4::new(
            Ipv4Addr::new(0, 0, 0, 0),
            port,
        )));
        config
    }

    pub fn get_network_type(&self) -> &Network { &self.network_type }

    pub fn network_id_to_known_cfx_network(id: u64) -> Network {
        match id {
            1 => Network::Test,
            1029 => Network::Main,
            n => Network::Id(n),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Default)]
pub struct DiscoveryConfiguration {
    pub discover_node_count: u32,
    pub expire_time: Duration,
    pub find_node_timeout: Duration,
    pub max_nodes_ping: usize,
    pub ping_timeout: Duration,
    pub throttling_interval: Duration,
    pub throttling_limit_ping: usize,
    pub throttling_limit_find_nodes: usize,
}

impl DiscoveryConfiguration {
    fn expire_timestamp(&self) -> u64 {
        (SystemTime::now() + self.expire_time)
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs()
    }
}

/// Type of NAT resolving method
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum NatType {
    Nothing,
    Any,
    UPnP,
    NatPMP,
}

#[derive(Clone)]
pub enum NetworkIoMessage {
    Start,
    AddHandler {
        handler: Arc<dyn NetworkProtocolHandler + Sync>,
        protocol: ProtocolId,
        version: ProtocolVersion,
        callback: std::sync::mpsc::SyncSender<()>,
    },
    /// Register a new protocol timer
    AddTimer {
        /// Protocol Id.
        protocol: ProtocolId,
        /// Timer token.
        token: TimerToken,
        /// Timer delay.
        delay: Duration,
    },
    DispatchWork {
        /// Protocol Id.
        protocol: ProtocolId,
        /// Work type.
        work_type: HandlerWorkType,
    },
    HandleProtocolMessage {
        protocol: ProtocolId,
        peer: PeerId,
        node_id: NodeId,
        data: Vec<u8>,
    },
}

pub trait NetworkProtocolHandler: Sync + Send {
    fn minimum_supported_version(&self) -> ProtocolVersion;

    fn initialize(&self, _io: &dyn NetworkContext);

    fn on_message(
        &self, io: &dyn NetworkContext, node_id: &NodeId, data: &[u8],
    );

    fn on_peer_connected(
        &self, io: &dyn NetworkContext, node_id: &NodeId,
        peer_protocol_version: ProtocolVersion,
        pos_public_key: Option<(ConsensusPublicKey, ConsensusVRFPublicKey)>,
    );

    fn on_peer_disconnected(&self, io: &dyn NetworkContext, node_id: &NodeId);

    fn on_timeout(&self, io: &dyn NetworkContext, timer: TimerToken);

    fn send_local_message(&self, _io: &dyn NetworkContext, _message: Vec<u8>);

    fn on_work_dispatch(
        &self, _io: &dyn NetworkContext, _work_type: HandlerWorkType,
    );
}

#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub enum UpdateNodeOperation {
    Failure,
    Demotion,
    Remove,
}

pub trait NetworkContext {
    fn get_protocol(&self) -> ProtocolId;

    fn get_peer_connection_origin(&self, node_id: &NodeId) -> Option<bool>;

    fn send(
        &self, node_id: &NodeId, msg: Vec<u8>,
        min_protocol_version: ProtocolVersion,
        version_valid_till: ProtocolVersion, priority: SendQueuePriority,
    ) -> Result<(), Error>;

    fn disconnect_peer(
        &self, node_id: &NodeId, op: Option<UpdateNodeOperation>, reason: &str,
    );

    /// Register a new IO timer. 'IoHandler::timeout' will be called with the
    /// token.
    fn register_timer(
        &self, token: TimerToken, delay: Duration,
    ) -> Result<(), Error>;

    fn dispatch_work(&self, work_type: HandlerWorkType);

    fn insert_peer_node_tag(&self, peer: NodeId, key: &str, value: &str);

    fn is_peer_self(&self, _node_id: &NodeId) -> bool;

    fn self_node_id(&self) -> NodeId;
}

#[derive(Debug, Clone)]
pub struct SessionMetadata {
    pub id: Option<NodeId>,
    /// There won't be many protocols so it's faster to use Vec than Map.
    pub peer_protocols: Vec<ProtocolInfo>,
    pub originated: bool,
    /// Packet header version of the peer.
    pub peer_header_version: u8,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProtocolInfo {
    pub protocol: ProtocolId,
    pub version: ProtocolVersion,
}

impl Encodable for ProtocolInfo {
    fn rlp_append(&self, rlp: &mut RlpStream) {
        rlp.begin_list(2);
        rlp.append(&&self.protocol[..]);
        rlp.append(&self.version);
    }
}

impl Decodable for ProtocolInfo {
    fn decode(rlp: &Rlp) -> Result<Self, DecoderError> {
        let p: Vec<u8> = rlp.val_at(0)?;
        if p.len() != 3 {
            return Err(DecoderError::Custom(
                "Invalid subprotocol string length",
            ));
        }
        let mut protocol: ProtocolId = [0u8; 3];
        protocol.clone_from_slice(&p);
        Ok(ProtocolInfo {
            protocol,
            version: rlp.val_at(1)?,
        })
    }
}

impl PartialOrd for ProtocolInfo {
    fn partial_cmp(&self, other: &ProtocolInfo) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for ProtocolInfo {
    fn cmp(&self, other: &ProtocolInfo) -> Ordering {
        self.protocol.cmp(&other.protocol)
    }
}

#[derive(Serialize, Deserialize)]
pub struct PeerInfo {
    pub id: PeerId,
    pub addr: SocketAddr,
    pub nodeid: NodeId,
    pub protocols: Vec<ProtocolInfo>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IpFilter {
    pub predefined: AllowIP,
    pub custom_allow: Vec<IpNetwork>,
    pub custom_block: Vec<IpNetwork>,
}

impl Default for IpFilter {
    fn default() -> Self {
        IpFilter {
            predefined: AllowIP::All,
            custom_allow: vec![],
            custom_block: vec![],
        }
    }
}

impl IpFilter {
    /// Attempt to parse the peer mode from a string.
    pub fn parse(s: &str) -> Result<IpFilter, IpNetworkError> {
        let mut filter = IpFilter::default();
        for f in s.split_whitespace() {
            match f {
                "all" => filter.predefined = AllowIP::All,
                "private" => filter.predefined = AllowIP::Private,
                "public" => filter.predefined = AllowIP::Public,
                "none" => filter.predefined = AllowIP::None,
                custom => {
                    if custom.starts_with('-') {
                        filter.custom_block.push(IpNetwork::from_str(
                            &custom.to_owned().split_off(1),
                        )?)
                    } else {
                        filter.custom_allow.push(IpNetwork::from_str(custom)?)
                    }
                }
            }
        }
        Ok(filter)
    }
}

/// IP filter
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AllowIP {
    /// Connect to any address
    All,
    /// Connect to private network only
    Private,
    /// Connect to public network only
    Public,
    /// Block all addresses
    None,
}

pub fn parse_msg_id_leb128_2_bytes_at_most(msg: &mut &[u8]) -> u16 {
    let buf = *msg;

    let mut ret = 0;
    let mut pos = buf.len() - 1;

    let byte = buf[pos] as u16;
    ret |= byte & 0x7f;
    if byte & 0x80 != 0 {
        pos -= 1;
        let byte = buf[pos] as u16;
        ret |= (byte & 0x7f) << 7;
    }

    *msg = &buf[..pos];

    ret
}