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
// Copyright 2021 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.

use crate::node_ops::OutgoingMsg;
use crate::{utils, Config as NodeConfig, Error, Result};
use bytes::Bytes;
use ed25519_dalek::PublicKey as Ed25519PublicKey;

// TODO: use only sn_data_types
use bls::{PublicKeySet, PublicKeyShare as BlsPublicKeyShare};

use log::{debug, error};
use serde::Serialize;
use sn_data_types::{Error as DtError, PublicKey, Result as DtResult, Signature, SignatureShare};
use sn_messaging::{client::Message, Aggregation, DstLocation, Itinerary, SrcLocation};
use sn_routing::{
    Config as RoutingConfig, Error as RoutingError, EventStream, Routing as RoutingNode,
    SectionChain,
};
use std::sync::Arc;
use std::{collections::BTreeMap, net::SocketAddr};
use std::{collections::BTreeSet, path::PathBuf};
use xor_name::{Prefix, XorName};

///
#[derive(Clone)]
pub struct Network {
    routing: Arc<RoutingNode>,
}

#[allow(missing_docs)]
impl Network {
    pub async fn new(config: &NodeConfig) -> Result<(Self, EventStream)> {
        let node_config = RoutingConfig {
            first: config.is_first(),
            transport_config: config.network_config().clone(),
            ..Default::default()
        };
        let (routing, event_stream) = RoutingNode::new(node_config).await?;

        Ok((
            Self {
                routing: Arc::new(routing),
            },
            event_stream,
        ))
    }

    /// Sign with our node's ED25519 key
    pub async fn sign_as_node<T: Serialize>(&self, data: &T) -> Result<Signature> {
        let data = utils::serialise(data)?;
        let sig = self.routing.sign_as_node(&data).await;
        Ok(Signature::Ed25519(sig))
    }

    /// Sign with our BLS PK Share
    pub async fn sign_as_elder<T: Serialize>(&self, data: &T) -> Result<SignatureShare> {
        let bls_pk = self
            .routing
            .public_key_set()
            .await
            .map_err(|_| Error::NoSectionPublicKey)?
            .public_key();
        let share = self
            .routing
            .sign_as_elder(&utils::serialise(data)?, &bls_pk)
            .await
            .map_err(Error::Routing)?;
        Ok(SignatureShare {
            share,
            index: self
                .routing
                .our_index()
                .await
                .map_err(|_| Error::NoSectionPublicKey)?,
        })
    }

    /// Sign with our BLS PK Share
    pub async fn sign_as_elder_raw<T: Serialize>(&self, data: &T) -> Result<bls::SignatureShare> {
        let bls_pk = self
            .routing
            .public_key_set()
            .await
            .map_err(|_| Error::NoSectionPublicKey)?
            .public_key();
        let data = utils::serialise(data)?;
        let share = self
            .routing
            .sign_as_elder(&data, &bls_pk)
            .await
            .map_err(Error::Routing)?;
        Ok(share)
    }

    pub async fn age(&self) -> u8 {
        self.routing.age().await
    }

    pub async fn public_key(&self) -> Ed25519PublicKey {
        self.routing.public_key().await
    }

    pub async fn section_public_key(&self) -> Result<PublicKey> {
        Ok(PublicKey::Bls(
            self.routing
                .public_key_set()
                .await
                .map_err(|_| Error::NoSectionPublicKey)?
                .public_key(),
        ))
    }

    pub async fn sibling_public_key(&self) -> Option<PublicKey> {
        let sibling_prefix = self.our_prefix().await.sibling();
        self.routing
            .section_key(&sibling_prefix)
            .await
            .map(PublicKey::Bls)
    }

    pub async fn matching_section(&self, name: &XorName) -> Option<bls::PublicKey> {
        let (key, _) = self.routing.matching_section(&name).await;
        key
    }

    pub async fn our_public_key_set(&self) -> Result<PublicKeySet> {
        self.routing.public_key_set().await.map_err(Error::Routing)
    }

    pub async fn get_section_pk_by_name(&self, name: &XorName) -> Result<PublicKey> {
        let (pk, elders) = self.routing.matching_section(name).await;
        if let Some(pk) = pk {
            let pk = PublicKey::from(pk);
            Ok(pk)
        } else {
            Err(Error::NoSectionPublicKeyKnown(*name))
        }
    }

    pub async fn our_name(&self) -> XorName {
        self.routing.name().await
    }

    pub async fn our_age(&self) -> u8 {
        self.routing.age().await
    }

    pub fn our_connection_info(&self) -> SocketAddr {
        self.routing.our_connection_info()
    }

    pub async fn our_prefix(&self) -> Prefix {
        self.routing.our_prefix().await
    }

    pub async fn section_chain(&self) -> SectionChain {
        self.routing.section_chain().await
    }

    pub async fn matches_our_prefix(&self, name: XorName) -> bool {
        self.routing.matches_our_prefix(&XorName(name.0)).await
    }

    pub async fn send_message(
        &self,
        itinerary: Itinerary,
        content: Bytes,
    ) -> Result<(), RoutingError> {
        self.routing.send_message(itinerary, content, None).await
    }

    pub async fn set_joins_allowed(&mut self, joins_allowed: bool) -> Result<()> {
        self.routing
            .set_joins_allowed(joins_allowed)
            .await
            .map_err(Error::Routing)
    }

    /// Returns whether the node is Elder.
    pub async fn is_elder(&self) -> bool {
        self.routing.is_elder().await
    }

    /// get our PKshare
    pub async fn our_public_key_share(&self) -> Result<PublicKey> {
        let index = self.our_index().await?;
        Ok(PublicKey::from(
            self.our_public_key_set().await?.public_key_share(index),
        ))
    }

    /// BLS key index in routing for key shares
    pub async fn our_index(&self) -> Result<usize> {
        self.routing.our_index().await.map_err(Error::Routing)
    }

    pub async fn our_elder_names(&self) -> BTreeSet<XorName> {
        self.routing
            .our_elders()
            .await
            .iter()
            .map(|p2p_node| XorName(p2p_node.name().0))
            .collect::<BTreeSet<_>>()
    }

    pub async fn our_elder_addresses(&self) -> Vec<(XorName, SocketAddr)> {
        self.routing
            .our_elders()
            .await
            .iter()
            .map(|p2p_node| (XorName(p2p_node.name().0), *p2p_node.addr()))
            .collect::<Vec<_>>()
    }

    pub async fn our_elder_addresses_sorted_by_distance_to(
        &self,
        name: &XorName,
    ) -> Vec<(XorName, SocketAddr)> {
        self.routing
            .our_elders_sorted_by_distance_to(&XorName(name.0))
            .await
            .into_iter()
            .map(|p2p_node| (XorName(p2p_node.name().0), *p2p_node.addr()))
            .collect::<Vec<_>>()
    }

    pub async fn our_elder_names_sorted_by_distance_to(
        &self,
        name: &XorName,
        count: usize,
    ) -> Vec<XorName> {
        self.routing
            .our_elders_sorted_by_distance_to(&XorName(name.0))
            .await
            .into_iter()
            .take(count)
            .map(|p2p_node| XorName(p2p_node.name().0))
            .collect::<Vec<_>>()
    }

    pub async fn age_of_node(&self, node: XorName) -> Vec<XorName> {
        self.routing
            .our_adults_sorted_by_distance_to(&XorName::default())
            .await
            .into_iter()
            .take(u8::MAX as usize)
            .map(|p2p_node| XorName(p2p_node.name().0))
            .collect::<Vec<_>>()
    }

    pub async fn our_members(&self) -> BTreeMap<XorName, u8> {
        let elders: Vec<_> = self
            .routing
            .our_elders()
            .await
            .into_iter()
            .map(|peer| (*peer.name(), peer.age()))
            .collect();
        let adults: Vec<_> = self
            .routing
            .our_adults()
            .await
            .into_iter()
            .map(|peer| (*peer.name(), peer.age()))
            .collect();

        vec![elders, adults]
            .into_iter()
            .flatten()
            .collect::<BTreeMap<XorName, u8>>()
    }

    pub async fn our_adults(&self) -> Vec<XorName> {
        self.routing
            .our_adults()
            .await
            .into_iter()
            .map(|p2p_node| XorName(p2p_node.name().0))
            .collect::<Vec<_>>()
    }

    pub async fn our_adults_sorted_by_distance_to(
        &self,
        name: &XorName,
        count: usize,
    ) -> Vec<XorName> {
        self.routing
            .our_adults_sorted_by_distance_to(&XorName(name.0))
            .await
            .into_iter()
            .take(count)
            .map(|p2p_node| XorName(p2p_node.name().0))
            .collect::<Vec<_>>()
    }
}