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
// Copyright 2020 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under the MIT license <LICENSE-MIT
// https://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD
// https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied,
// modified, or distributed except according to those terms. Please review the Licences for the
// specific language governing permissions and limitations relating to use of the SAFE Network
// Software.

use crate::{AdultDuties, Duty, ElderDuties, PublicKey, Result, Signature, SignatureShare};
use ed25519_dalek::PublicKey as Ed25519PublicKey;
use ed25519_dalek::Signature as Ed25519Signature;
use hex_fmt::HexFmt;
use serde::{Deserialize, Serialize};
use signature::Verifier;
use std::{
    fmt::{self, Debug, Display, Formatter},
    hash::Hash,
};
use threshold_crypto::{
    PublicKey as BlsPublicKey, PublicKeySet as BlsPublicKeySet,
    PublicKeyShare as BlsPublicKeyShare, Signature as BlsSignature,
    SignatureShare as BlsSignatureShare,
};
pub use xor_name::Prefix;
use xor_name::{XorName, XOR_NAME_LEN};

/// A msg sender in the larger network (clients + nodes),
/// provides its identification by specifying type of entity,
/// and providing a signature over it.
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub struct MsgSender {
    entity: Entity,
    sig: Option<EntitySignature>,
}

/// An identifier of a section, as
/// of a specific Elder constellation, thereby making it transient.
#[derive(Eq, PartialEq, Clone, Serialize, Deserialize)]
pub struct TransientSectionKey {
    /// The group sig related id.
    pub bls_key: BlsPublicKey,
}

impl Debug for TransientSectionKey {
    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
        write!(formatter, "TransientSectionKey::")?;
        write!(
            formatter,
            "Bls({:<8})",
            HexFmt(&self.bls_key.to_bytes()[..XOR_NAME_LEN])
        )
    }
}

impl Display for TransientSectionKey {
    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
        Debug::fmt(self, formatter)
    }
}

/// An identifier of an Elder, as
/// of a specific Elder constellation, thereby making it transient.
#[derive(Eq, PartialEq, Clone, Serialize, Deserialize)]
pub struct TransientElderKey {
    /// The xorspace related id for the node.
    pub node_id: Ed25519PublicKey,
    /// Part of the group sig related id.
    pub bls_key: BlsPublicKeyShare,
    /// Part of the group sig related id.
    pub bls_share_index: usize,
    /// Part of the group sig related id.
    pub bls_public_key_set: BlsPublicKeySet,
}

impl Debug for TransientElderKey {
    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
        write!(formatter, "TransientElderKey::")?;
        write!(
            formatter,
            "Ed25519({:<8})",
            HexFmt(&self.node_id.to_bytes())
        )?;
        write!(
            formatter,
            "BlsShare({:<8})",
            HexFmt(&self.bls_key.to_bytes()[..XOR_NAME_LEN])
        )
    }
}

impl Display for TransientElderKey {
    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
        Debug::fmt(self, formatter)
    }
}

/// An entity in the messaging ecosystem.
/// It has an address that can be used for messaging.
#[derive(Eq, PartialEq, Clone, Serialize, Deserialize)]
pub enum Entity {
    ///
    Client(PublicKey),
    /// Elder, Adult, or any other sort of node.
    AnyNode(Ed25519PublicKey, Duty),
    ///
    AdultNode(Ed25519PublicKey, AdultDuties),
    ///
    ElderNode(TransientElderKey, ElderDuties),
    ///
    Section(TransientSectionKey, ElderDuties),
}

impl Debug for Entity {
    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
        write!(formatter, "Entity::")?;
        match self {
            Self::Client(key) => Debug::fmt(key, formatter),
            Self::AnyNode(key, duty) => {
                write!(formatter, "Ed25519({:<8})", HexFmt(&key.to_bytes()))?;
                write!(formatter, "AnyNode({:?})", duty)
            }
            Self::AdultNode(key, duty) => {
                write!(formatter, "Ed25519({:<8})", HexFmt(&key.to_bytes()))?;
                write!(formatter, "AdultNode({:?})", duty)
            }
            Self::ElderNode(key, duty) => {
                Debug::fmt(key, formatter)?;
                write!(formatter, "ElderNode({:?})", duty)
            }
            Self::Section(key, duty) => {
                Debug::fmt(key, formatter)?;
                write!(formatter, "Section({:?})", duty)
            }
        }
    }
}

impl Display for Entity {
    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
        Debug::fmt(self, formatter)
    }
}

///
pub enum EntityId {
    /// Not an xorspace id.
    Client(PublicKey),
    /// An xorspace id.
    Node(Ed25519PublicKey),
    /// Not an xorspace id.
    Section(BlsPublicKey),
}

impl Debug for EntityId {
    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
        write!(formatter, "EntityId::")?;
        match self {
            Self::Client(pub_key) => Debug::fmt(pub_key, formatter),
            Self::Node(pub_key) => write!(formatter, "Ed25519({:<8})", HexFmt(&pub_key.to_bytes())),
            Self::Section(pub_key) => write!(
                formatter,
                "Bls({:<8})",
                HexFmt(&pub_key.to_bytes()[..XOR_NAME_LEN])
            ),
        }
    }
}

impl Display for EntityId {
    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
        Debug::fmt(self, formatter)
    }
}

#[derive(Eq, PartialEq, Clone, Serialize, Deserialize)]
pub enum EntitySignature {
    /// Any constellation.
    Client(Signature),
    /// When acting individually.
    Node(Ed25519Signature),
    /// Elders acting in group.
    Elder(BlsSignatureShare),
    /// The group.
    Section(BlsSignature),
}

impl Debug for EntitySignature {
    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
        write!(formatter, "EntitySignature::")?;
        match self {
            Self::Client(sig) => {
                write!(formatter, "Client::")?;
                Debug::fmt(sig, formatter)
            }
            Self::Node(_) => {
                write!(formatter, "Node::")?;
                write!(formatter, "Ed25519(..)")
            }
            Self::Elder(_) => {
                write!(formatter, "Elder::")?;
                write!(formatter, "BlsShare(..)")
            }
            Self::Section(_) => {
                write!(formatter, "Section::")?;
                write!(formatter, "Bls(..)")
            }
        }
    }
}

impl Display for EntitySignature {
    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
        Debug::fmt(self, formatter)
    }
}

///
#[derive(Debug, Hash, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub enum Address {
    ///
    Client(XorName),
    ///
    Node(XorName),
    ///
    Section(XorName),
}

impl Address {
    /// Extracts the underlying XorName.
    pub fn xorname(&self) -> XorName {
        use Address::*;
        match self {
            Client(xorname) | Node(xorname) | Section(xorname) => *xorname,
        }
    }
}

impl EntityId {
    ///
    pub fn public_key(&self) -> PublicKey {
        match self {
            Self::Client(key) => *key,
            Self::Node(key) => PublicKey::Ed25519(*key),
            Self::Section(key) => PublicKey::Bls(*key),
        }
    }
}

impl MsgSender {
    ///
    pub fn client(key: PublicKey, sig: Signature) -> Result<Self> {
        Ok(Self {
            entity: Entity::Client(key),
            sig: Some(EntitySignature::Client(sig)),
        })
    }

    ///
    pub fn any_node(key: Ed25519PublicKey, duty: Duty, sig: Ed25519Signature) -> Result<Self> {
        Ok(Self {
            entity: Entity::AnyNode(key, duty),
            sig: Some(EntitySignature::Node(sig)),
        })
    }

    ///
    pub fn adult(key: Ed25519PublicKey, duty: AdultDuties, sig: Ed25519Signature) -> Result<Self> {
        Ok(Self {
            entity: Entity::AdultNode(key, duty),
            sig: Some(EntitySignature::Node(sig)),
        })
    }

    ///
    pub fn elder(
        key: TransientElderKey,
        duty: ElderDuties,
        sig: BlsSignatureShare,
    ) -> Result<Self> {
        Ok(Self {
            entity: Entity::ElderNode(key, duty),
            sig: Some(EntitySignature::Elder(sig)),
        })
    }

    ///
    pub fn section(key: TransientSectionKey, duty: ElderDuties) -> Result<Self> {
        Ok(Self {
            entity: Entity::Section(key, duty),
            sig: None,
        })
    }

    /// The id of the sender.
    pub fn id(&self) -> EntityId {
        self.entity.id()
    }

    /// The network address of the sender.
    pub fn address(&self) -> Address {
        self.entity.address()
    }

    /// The duty under which the sender operated.
    pub fn duty(&self) -> Option<Duty> {
        use Entity::*;
        match self.entity {
            Client(_) => None,
            AnyNode(_, duty) => Some(duty),
            AdultNode(_, duty) => Some(Duty::Adult(duty)),
            ElderNode(_, duty) | Section(_, duty) => Some(Duty::Elder(duty)),
        }
    }

    /// Verifies a payload as sent by this sender.
    pub fn verify(&self, payload: &[u8]) -> bool {
        self.entity.try_verify(self.sig.clone(), payload)
    }

    /// If sender is Elder
    pub fn group_key_set(&self) -> Option<BlsPublicKeySet> {
        if let Entity::ElderNode(key, _) = &self.entity {
            Some(key.bls_public_key_set.clone())
        } else {
            None
        }
    }

    /// If sender is Elder
    pub fn group_sig_share(&self) -> Option<SignatureShare> {
        if let Entity::ElderNode(key, _) = &self.entity {
            if let Some(EntitySignature::Elder(sig)) = &self.sig {
                return Some(SignatureShare {
                    index: key.bls_share_index,
                    share: sig.clone(),
                });
            } else {
                unreachable!("Should not be possible to instantiate such a combination.")
            }
        }
        None
    }

    ///
    pub fn is_client(&self) -> bool {
        matches!(self.entity, Entity::Client(_))
    }

    ///
    pub fn is_any_node(&self) -> bool {
        matches!(self.entity, Entity::AnyNode { .. })
    }

    ///
    pub fn is_adult(&self) -> bool {
        matches!(self.entity, Entity::AdultNode { .. })
    }

    ///
    pub fn is_elder(&self) -> bool {
        matches!(self.entity, Entity::ElderNode { .. })
    }

    ///
    pub fn is_section(&self) -> bool {
        matches!(self.entity, Entity::Section { .. })
    }
}

impl Entity {
    /// The id of the entity.
    pub fn id(&self) -> EntityId {
        use Entity::*;
        match self {
            Client(key) => EntityId::Client(*key),
            AnyNode(node_id, ..) | AdultNode(node_id, ..) => EntityId::Node(*node_id),
            ElderNode(key, ..) => EntityId::Node(key.node_id),
            Section(key, ..) => EntityId::Section(key.bls_key),
        }
    }

    /// The address of the entity,
    /// used to send messages to it.
    pub fn address(&self) -> Address {
        use Entity::*;
        match self {
            Client(key) => Address::Client((*key).into()),
            AnyNode(key, ..) | AdultNode(key, ..) => Address::Node(PublicKey::Ed25519(*key).into()),
            ElderNode(key, ..) => Address::Node(PublicKey::Ed25519(key.node_id).into()),
            Section(key, ..) => Address::Section(PublicKey::Bls(key.bls_key).into()),
        }
    }

    ///
    pub fn try_verify(&self, sig: Option<EntitySignature>, data: &[u8]) -> bool {
        use Entity::*;
        match self {
            Client(key) => {
                if let Some(EntitySignature::Client(sig)) = sig {
                    key.verify(&sig, data).is_ok()
                } else {
                    false
                }
            }
            AnyNode(key, ..) | AdultNode(key, ..) => {
                if let Some(EntitySignature::Node(sig)) = sig {
                    key.verify(data, &sig).is_ok()
                } else {
                    false
                }
            }
            ElderNode(key, ..) => {
                if let Some(EntitySignature::Elder(sig)) = sig {
                    key.bls_key.verify(&sig, data)
                } else if let Some(EntitySignature::Node(sig)) = sig {
                    key.node_id.verify(data, &sig).is_ok()
                } else {
                    false
                }
            }
            Section(..) => true,
        }
    }
}