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
// Copyright (c) 2021 Open Community Project Association https://ocpa.ch
// This software is published under the AGPLv3 license.

//! # Qaul Connections Modules
//!
//! The modules define how and where to connect to network interfaces.

pub mod ble;
pub mod events;
pub mod internet;
pub mod lan;

use libp2p::{
    noise::{Keypair, X25519Spec},
    Multiaddr,
};
use prost::Message;
use serde::{Deserialize, Serialize};

use crate::node::Node;
use crate::rpc::Rpc;
use crate::storage::configuration::Configuration;
use crate::storage::configuration::InternetPeer;
use ble::Ble;
use internet::Internet;
use lan::Lan;

/// Import protobuf message definition generated by
/// the rust module prost-build.
pub mod proto {
    include!("qaul.rpc.connections.rs");
}

/// enum with all connection modules
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(i32)]
pub enum ConnectionModule {
    /// This is a local user and does not need
    /// any further routing.
    Local,
    /// Lan module, for all kind of lan connections,
    /// neighbour nodes are found over mdns.
    Lan,
    /// Connect statically to remote nodes.
    Internet,
    /// BLE module
    Ble,
    /// no connection module known for this
    None,
}

impl ConnectionModule {
    /// String value of the enum field names used in the ProtoBuf definition.
    ///
    /// The values are not transformed in any way and thus are considered stable
    /// (if the ProtoBuf definition does not change) and safe for programmatic use.
    #[allow(dead_code)]
    pub fn as_str_name(&self) -> &'static str {
        match self {
            ConnectionModule::None => "NONE",
            ConnectionModule::Lan => "LAN",
            ConnectionModule::Internet => "INTERNET",
            ConnectionModule::Ble => "BLE",
            ConnectionModule::Local => "LOCAL",
        }
    }

    pub fn as_int(&self) -> i32 {
        match self {
            ConnectionModule::None => 0,
            ConnectionModule::Lan => 1,
            ConnectionModule::Internet => 2,
            ConnectionModule::Ble => 3,
            ConnectionModule::Local => 4,
        }
    }
}

/// Collection of all connections of libqaul
/// each collection is a libp2p swarm
pub struct Connections {
    pub lan: Option<Lan>,
    pub internet: Option<Internet>,
}

impl Connections {
    /// initialize connections
    pub async fn init() -> Connections {
        // create transport encryption keys for noise protocol
        let auth_keys = Keypair::<X25519Spec>::new()
            .into_authentic(Node::get_keys())
            .expect("can create auth keys");

        // initialize Lan module
        let lan = Lan::init(auth_keys.clone()).await;

        // initialize Internet overlay module
        let internet = Internet::init(auth_keys).await;

        // initialize BLE  module
        Ble::init();

        let conn = Connections {
            lan: Some(lan),
            internet: Some(internet),
        };

        conn
    }

    /// Process incoming RPC request messages
    pub fn rpc(data: Vec<u8>, internet_opt: Option<&mut Internet>) {
        match proto::Connections::decode(&data[..]) {
            Ok(connections) => {
                match connections.message {
                    Some(proto::connections::Message::InternetNodesRequest(
                        _internet_nodes_request,
                    )) => {
                        Self::rpc_send_node_list(proto::Info::Request);
                    }
                    Some(proto::connections::Message::InternetNodesAdd(nodes_entry)) => {
                        // check if we have a valid address
                        let mut valid = false;
                        let mut info = proto::Info::AddSuccess;

                        {
                            // get config
                            let mut config = Configuration::get_mut();

                            // add the node to config if the address is valid
                            let address_result: Result<Multiaddr, libp2p::multiaddr::Error> =
                                nodes_entry.address.clone().parse();
                            match address_result {
                                Ok(address) => {
                                    valid = true;

                                    // add to config
                                    config.internet.peers.push(InternetPeer {
                                        address: nodes_entry.address.clone(),
                                        enabled: true,
                                    });

                                    // connect to node
                                    if let Some(internet) = internet_opt {
                                        // if we already have connection history, we need to remove from banned list.
                                        if let Some(peer_id) = Internet::peerid_from_address(
                                            nodes_entry.address.clone(),
                                        ) {
                                            internet.swarm.unban_peer_id(peer_id);
                                        }
                                        Internet::peer_dial(address, &mut internet.swarm);
                                    }
                                }
                                Err(e) => {
                                    log::error!("Not a valid address: {:?}", e);
                                    info = proto::Info::AddErrorInvalid;
                                }
                            }
                        }

                        // save configuration
                        if valid {
                            Configuration::save();
                        }

                        // send response message
                        Self::rpc_send_node_list(info);
                    }
                    Some(proto::connections::Message::InternetNodesRemove(nodes_entry)) => {
                        let mut info = proto::Info::RemoveErrorNotFound;

                        {
                            let mut nodes: Vec<InternetPeer> = Vec::new();

                            // get config
                            let mut config = Configuration::get_mut();

                            // loop through addresses and remove the equal
                            for peer in &config.internet.peers {
                                if peer.address == nodes_entry.address {
                                    // address has been found and is
                                    // therefore removed.
                                    info = proto::Info::RemoveSuccess;
                                } else {
                                    // addresses do not match.
                                    // add this address to the new vector.
                                    nodes.push(peer.clone());
                                }
                            }
                            // add new nodes list to configuration
                            config.internet.peers = nodes;
                        }

                        // save configuration
                        Configuration::save();

                        // check connection and deactivate node
                        if let Some(_id) =
                            Internet::peerid_from_address(nodes_entry.address.clone())
                        {
                            Internet::change_connection(nodes_entry.address.clone(), false);
                        }

                        // send response
                        Self::rpc_send_node_list(info);
                    }
                    Some(proto::connections::Message::InternetNodesState(nodes_entry)) => {
                        let mut info = proto::Info::RemoveErrorNotFound;
                        let mut changed_state = false;

                        {
                            let mut nodes: Vec<InternetPeer> = Vec::new();

                            // get config
                            let mut config = Configuration::get_mut();

                            // loop through addresses and remove the equal
                            for peer in &config.internet.peers {
                                if peer.address == nodes_entry.address {
                                    // address has been found and is
                                    // therefore removed.
                                    nodes.push(InternetPeer {
                                        address: peer.address.clone(),
                                        enabled: nodes_entry.enabled,
                                    });
                                    info = proto::Info::StateSuccess;

                                    if peer.enabled != nodes_entry.enabled {
                                        changed_state = true;
                                    }
                                } else {
                                    // addresses do not match.
                                    // add this address to the new vector.
                                    nodes.push(peer.clone());
                                }
                            }
                            // add new nodes list to configuration
                            config.internet.peers = nodes;
                        }

                        // save configuration
                        Configuration::save();

                        if info == proto::Info::StateSuccess && changed_state == true {
                            // already has connection history, we simply handle banned peer list
                            if let Some(_) =
                                Internet::peerid_from_address(nodes_entry.address.clone())
                            {
                                Internet::change_connection(
                                    nodes_entry.address.clone(),
                                    nodes_entry.enabled,
                                );
                            } else if nodes_entry.enabled == true {
                                // already we don't have connection history and it's activate request.
                                // we redial connection
                                if let Some(internet) = internet_opt {
                                    let address_result: Result<
                                        Multiaddr,
                                        libp2p::multiaddr::Error,
                                    > = nodes_entry.address.clone().parse();
                                    let address = address_result.unwrap();
                                    Internet::peer_dial(address, &mut internet.swarm);
                                }
                            }
                        }

                        // send response
                        Self::rpc_send_node_list(info);
                    }
                    _ => {}
                }
            }
            Err(error) => {
                log::error!("{:?}", error);
            }
        }
    }

    /// create and send a node list message
    fn rpc_send_node_list(info: proto::Info) {
        let mut nodes: Vec<proto::InternetNodesEntry> = Vec::new();

        // get list of peer nodes from config
        let config = Configuration::get();

        // fill all the nodes
        for peer in &config.internet.peers {
            nodes.push(proto::InternetNodesEntry {
                address: peer.address.clone(),
                enabled: peer.enabled,
            });
        }

        // create the protobuf message
        let proto_message = proto::Connections {
            message: Some(proto::connections::Message::InternetNodesList(
                proto::InternetNodesList {
                    info: info as i32,
                    nodes,
                },
            )),
        };

        // send the message
        Self::rpc_send_message(proto_message);
    }

    /// encode and send connections RPC message to UI
    fn rpc_send_message(message: proto::Connections) {
        // encode message
        let mut buf = Vec::with_capacity(message.encoded_len());
        message
            .encode(&mut buf)
            .expect("Vec<u8> provides capacity as needed");

        // send message
        Rpc::send_message(
            buf,
            super::rpc::proto::Modules::Connections.into(),
            "".to_string(),
            Vec::new(),
        );
    }
}