parsec/id.rs
1// Copyright 2018 MaidSafe.net limited.
2//
3// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
4// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
5// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
6// KIND, either express or implied. Please review the Licences for the specific language governing
7// permissions and limitations relating to use of the SAFE Network Software.
8
9use serde::{de::DeserializeOwned, Serialize};
10use std::{fmt::Debug, hash::Hash};
11
12/// The public identity of a node. It provides functionality to allow it to be used as an
13/// asymmetric signing public key.
14pub trait PublicId: Clone + Eq + Ord + Hash + Serialize + DeserializeOwned + Debug {
15 /// The signature type associated with the chosen asymmetric key scheme.
16 type Signature: Clone + Eq + Ord + Hash + Serialize + DeserializeOwned + Debug;
17 /// Verifies `signature` against `data` using this `PublicId`. Returns `true` if valid.
18 fn verify_signature(&self, signature: &Self::Signature, data: &[u8]) -> bool;
19}
20
21/// The secret identity of a node. It provides functionality to allow it to be used as an
22/// asymmetric signing secret key and to also yield the associated public identity.
23pub trait SecretId {
24 /// The associated public identity type.
25 type PublicId: PublicId;
26
27 /// Returns the associated public identity.
28 fn public_id(&self) -> &Self::PublicId;
29
30 /// Creates a detached `Signature` of `data`.
31 fn sign_detached(&self, data: &[u8]) -> <Self::PublicId as PublicId>::Signature;
32
33 /// Creates a `Proof` of `data`.
34 fn create_proof(&self, data: &[u8]) -> Proof<Self::PublicId> {
35 Proof {
36 public_id: self.public_id().clone(),
37 signature: self.sign_detached(data),
38 }
39 }
40
41 /// Encrypts the message using own Rng to `to`
42 fn encrypt<M: AsRef<[u8]>>(&self, to: &Self::PublicId, msg: M) -> Option<Vec<u8>>;
43 /// Decrypt message from `from`.
44 fn decrypt(&self, from: &Self::PublicId, ct: &[u8]) -> Option<Vec<u8>>;
45}
46
47/// A basic helper to carry a given [`Signature`](trait.PublicId.html#associatedtype.Signature)
48/// along with the signer's [`PublicId`](trait.PublicId.html).
49#[serde(bound = "")]
50#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Debug)]
51pub struct Proof<P: PublicId> {
52 pub(super) public_id: P,
53 pub(super) signature: P::Signature,
54}
55
56impl<P: PublicId> Proof<P> {
57 /// Returns the associated public identity.
58 pub fn public_id(&self) -> &P {
59 &self.public_id
60 }
61
62 /// Returns the associated signature.
63 pub fn signature(&self) -> &P::Signature {
64 &self.signature
65 }
66
67 /// Verifies this `Proof` against `data`. Returns `true` if valid.
68 pub fn is_valid(&self, data: &[u8]) -> bool {
69 self.public_id.verify_signature(&self.signature, data)
70 }
71}