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
//! This module provides the structs and traits for the generation of key pairs for
//! cryptographic operations.
//!

pub(crate) mod ed25519;
pub(crate) mod error;
#[cfg(feature = "secp256k1")]
pub(crate) mod secp256k1;

use std::io::Read;

use borsh::{BorshDeserialize, BorshSerialize};
use identifier::error::Error;

use base64::encode_config;
pub use ed25519::Ed25519KeyPair;
#[cfg(feature = "secp256k1")]
pub use secp256k1::Secp256k1KeyPair;
use serde::{Deserialize, Serialize};

use crate::identifier::{self, derive::KeyDerivator};

/// Asymmetric key pair
#[derive(Serialize, Deserialize, Debug)]
pub enum KeyPair {
    Ed25519(Ed25519KeyPair),
    #[cfg(feature = "secp256k1")]
    Secp256k1(Secp256k1KeyPair),
}

impl KeyPair {
    pub fn get_key_derivator(&self) -> KeyDerivator {
        match self {
            KeyPair::Ed25519(_) => KeyDerivator::Ed25519,
            KeyPair::Secp256k1(_) => KeyDerivator::Secp256k1,
        }
    }
}

/// Generate key pair
#[allow(dead_code)]
pub fn generate<T: KeyGenerator + DSA + Into<KeyPair>>(seed: Option<&[u8]>) -> KeyPair {
    T::from_seed(seed.map_or(vec![].as_slice(), |x| x)).into()
}

/// Base for asymmetric key pair
#[derive(Default, Debug, Clone, PartialEq)]
pub struct BaseKeyPair<P, K> {
    pub public_key: P,
    pub secret_key: Option<K>,
}

/// Represents asymetric key pair for storage (deprecated: KeyPair is serializable)
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CryptoBox {
    pub public_key: Vec<u8>,
    pub secret_key: Vec<u8>,
}

/// Return key material bytes
pub trait KeyMaterial {
    /// Returns the public key bytes as slice
    fn public_key_bytes(&self) -> Vec<u8>;

    /// Returns the secret key bytes as slice
    fn secret_key_bytes(&self) -> Vec<u8>;

    /// Returns bytes from key pair
    fn to_bytes(&self) -> Vec<u8>;

    /// Returns String from key pair encoded in base64
    fn to_str(&self) -> String {
        encode_config(self.to_bytes(), base64::URL_SAFE_NO_PAD)
    }
}

/// Collection of methods to initialize a key pair
/// using random or deterministic manner
pub trait KeyGenerator: KeyMaterial {
    /// Generates random keys
    fn new() -> Self
    where
        Self: Sized,
    {
        Self::from_seed(vec![].as_slice())
    }

    /// Generates keys deterministically using a given seed
    fn from_seed(seed: &[u8]) -> Self
    where
        Self: Sized;

    /// Generates keys from existing public key
    fn from_public_key(public_key: &[u8]) -> Self
    where
        Self: Sized;

    /// Generate keys from existing secret key
    fn from_secret_key(private_key: &[u8]) -> Self
    where
        Self: Sized;
}

/// Used for Digital Signature Algorithm (DSA)
pub trait DSA {
    /// Performs sign operation
    fn sign(&self, payload: Payload) -> Result<Vec<u8>, Error>;

    /// Performs verify operation
    fn verify(&self, payload: Payload, signature: &[u8]) -> Result<(), Error>;
}

/// Used for Diffie–Hellman key exchange operations
pub trait DHKE {
    /// Perform key exchange operation
    fn key_exchange(&self, their_public: &Self) -> Result<Vec<u8>, Error>;
}

/// Clone key pair
impl Clone for KeyPair {
    fn clone(&self) -> Self {
        match self {
            KeyPair::Ed25519(kp) => {
                KeyPair::Ed25519(Ed25519KeyPair::from_secret_key(&kp.secret_key_bytes()))
            }
            KeyPair::Secp256k1(kp) => {
                KeyPair::Secp256k1(Secp256k1KeyPair::from_secret_key(&kp.secret_key_bytes()))
            }
            // KeyPair::X25519(kp) => KeyPair::X25519(
            //     X25519KeyPair::from_secret_key(&kp.secret_key_bytes()),
            // ),
        }
    }
}

impl KeyMaterial for KeyPair {
    fn public_key_bytes(&self) -> Vec<u8> {
        match self {
            KeyPair::Ed25519(x) => x.public_key_bytes(),
            #[cfg(feature = "secp256k1")]
            KeyPair::Secp256k1(x) => x.public_key_bytes(),
            // #[cfg(feature = "x25519")]
            // KeyPair::X25519(x) => x.public_key_bytes(),
        }
    }

    fn secret_key_bytes(&self) -> Vec<u8> {
        match self {
            KeyPair::Ed25519(x) => x.secret_key_bytes(),
            #[cfg(feature = "secp256k1")]
            KeyPair::Secp256k1(x) => x.secret_key_bytes(),
            // #[cfg(feature = "x25519")]
            // KeyPair::X25519(x) => x.secret_key_bytes(),
        }
    }

    fn to_bytes(&self) -> Vec<u8> {
        match self {
            KeyPair::Ed25519(x) => x.to_bytes(),
            #[cfg(feature = "secp256k1")]
            KeyPair::Secp256k1(x) => x.to_bytes(),
            // #[cfg(feature = "x25519")]
            // KeyPair::X25519(x) => x.to_bytes(),
        }
    }
}

impl DSA for KeyPair {
    fn sign(&self, payload: Payload) -> Result<Vec<u8>, Error> {
        match self {
            KeyPair::Ed25519(x) => x.sign(payload),
            #[cfg(feature = "secp256k1")]
            KeyPair::Secp256k1(x) => x.sign(payload),
            // _ => Err(Error::KeyPairError(
            //     "DSA is not supported for this key type".to_owned(),
            // )),
        }
    }

    fn verify(&self, payload: Payload, signature: &[u8]) -> Result<(), Error> {
        match self {
            KeyPair::Ed25519(x) => x.verify(payload, signature),
            #[cfg(feature = "secp256k1")]
            KeyPair::Secp256k1(x) => x.verify(payload, signature),
            // #[cfg(feature = "x25519")]
            // KeyPair::X25519(_) => Err(Error::KeyPairError(
            //     "DSA is not supported for this key type".to_owned(),
            // )),
        }
    }
}

impl BorshSerialize for KeyPair {
    #[inline]
    fn serialize<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
        match &self {
            KeyPair::Ed25519(x) => {
                BorshSerialize::serialize(&0u8, writer)?;
                let a: [u8; 32] = x.secret_key_bytes().try_into().unwrap();
                BorshSerialize::serialize(&a, writer)
            }
            KeyPair::Secp256k1(x) => {
                BorshSerialize::serialize(&1u8, writer)?;
                let a: [u8; 32] = x.secret_key_bytes().try_into().unwrap();
                BorshSerialize::serialize(&a, writer)
            }
        }
    }
}

impl BorshDeserialize for KeyPair {
    #[inline]
    fn deserialize_reader<R: Read>(reader: &mut R) -> std::io::Result<Self> {
        let order: u8 = BorshDeserialize::deserialize_reader(reader)?;
        match order {
            0 => {
                let data: [u8; 32] = BorshDeserialize::deserialize_reader(reader)?;
                Ok(KeyPair::Ed25519(Ed25519KeyPair::from_secret_key(&data)))
            }
            1 => {
                let data: [u8; 32] = BorshDeserialize::deserialize_reader(reader)?;
                Ok(KeyPair::Secp256k1(Secp256k1KeyPair::from_secret_key(&data)))
            }
            _ => Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                format!("Invalid Value representation: {}", order),
            )),
        }
    }
}

// impl DHKE for KeyPair {
//     fn key_exchange(&self, key: &Self) -> Result<Vec<u8>, Error> {
//         match (self, key) {
//             #[cfg(feature = "x25519")]
//             (KeyPair::X25519(me), KeyPair::X25519(them)) => {
//                 me.key_exchange(them)
//             }
//             _ => Err(Error::KeyPairError(
//                 "DHKE is not supported for this key type".to_owned(),
//             )),
//         }
//     }
// }

/// Payloads
#[derive(Debug, Clone)]
pub enum Payload {
    Buffer(Vec<u8>),
    #[allow(dead_code)]
    BufferArray(Vec<Vec<u8>>),
}

/// Creates 32 bytes seed
pub fn create_seed(initial_seed: &[u8]) -> Result<[u8; 32], Error> {
    let mut seed = [0u8; 32];
    if initial_seed.is_empty() {
        getrandom::getrandom(&mut seed)
            .map_err(|_| Error::SeedError("couldn't generate random seed".to_owned()))?;
    } else if initial_seed.len() <= 32 {
        seed[..initial_seed.len()].copy_from_slice(initial_seed);
    } else {
        return Err(Error::SeedError("seed is greater than 32".to_owned()));
    }
    Ok(seed)
}

#[cfg(test)]
mod tests {

    use super::{create_seed, ed25519::Ed25519KeyPair, generate, Payload, DSA};

    #[cfg(feature = "secp256k1")]
    use super::secp256k1::Secp256k1KeyPair;

    #[test]
    fn test_create_seed() {
        assert!(create_seed(vec![].as_slice()).is_ok());
        let seed = "48s8j34fuadfeuijakqp93d56829ki21".as_bytes();
        assert!(create_seed(seed).is_ok());
        let seed = "witness".as_bytes();
        assert!(create_seed(seed).is_ok());
        let seed = "witnesssdfasfasfasfsafsafasfsafsa".as_bytes();
        assert!(create_seed(seed).is_err());
    }

    #[test]
    fn test_ed25519() {
        let key_pair = generate::<Ed25519KeyPair>(None);
        let message = b"secret message";
        let signature = key_pair.sign(Payload::Buffer(message.to_vec())).unwrap();
        println!("Tamaño: {}", signature.len());
        let valid = key_pair.verify(Payload::Buffer(message.to_vec()), &signature);
        matches!(valid, Ok(()));
    }

    #[test]
    #[cfg(feature = "secp256k1")]
    fn test_secp256k1() {
        let key_pair = generate::<Secp256k1KeyPair>(None);
        let message = b"secret message";
        let signature = key_pair.sign(Payload::Buffer(message.to_vec())).unwrap();
        println!("Tamaño: {}", signature.len());
        let valid = key_pair.verify(Payload::Buffer(message.to_vec()), &signature);
        matches!(valid, Ok(()));
    }

    // #[test]
    // #[cfg(feature = "bls12381")]
    // fn test_bls12381() {
    //     let key_pair = generate::<Bls12381KeyPair>(None);
    //     let messages = vec![
    //         b"secret message 1".to_vec(),
    //         b"secret message 2".to_vec(),
    //         b"secret message 3".to_vec(),
    //         b"secret message 4".to_vec(),
    //         b"secret message 5".to_vec(),
    //     ];
    //     let signature = key_pair
    //         .sign(Payload::BufferArray(messages.clone()))
    //         .unwrap();
    //     let valid =
    //         key_pair.verify(Payload::BufferArray(messages.clone()), &signature);

    //     matches!(valid, Ok(()));
    // }

    // #[test]
    // #[cfg(feature = "x25519")]
    // fn test_x25519() {
    //     let key_pair1 = generate::<X25519KeyPair>(None);
    //     let key_pair2 = generate::<X25519KeyPair>(None);
    //     let secret1 = key_pair1.key_exchange(&key_pair2).unwrap();
    //     let secret2 = key_pair2.key_exchange(&key_pair1).unwrap();
    //     assert_eq!(secret1, secret2);
    // }
}