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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
//  Copyright (C) 2017  The Duniter Project Developers.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

//! Provide wrappers around ed25519 keys and signatures
//!
//! Key pairs can be generated with [`KeyPairGenerator`].
//!
//! [`KeyPairGenerator`]: struct.KeyPairGenerator.html

use super::{PrivateKey as PrivateKeyMethods, PublicKey as PublicKeyMethods};
use crate::bases::*;
use base58::ToBase58;
use base64;
use crypto;
use serde::de::{Deserialize, Deserializer, Error, SeqAccess, Visitor};
use serde::ser::{Serialize, SerializeTuple, Serializer};
use std::collections::hash_map::DefaultHasher;
use std::fmt;
use std::fmt::{Debug, Display, Formatter};
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;

/// Size of a public key in bytes
pub static PUBKEY_SIZE_IN_BYTES: &'static usize = &32;
/// Size of a signature in bytes
pub static SIG_SIZE_IN_BYTES: &'static usize = &64;

/// Store a ed25519 signature.
#[derive(Clone, Copy)]
pub struct Signature(pub [u8; 64]);

impl Hash for Signature {
    fn hash<H: Hasher>(&self, _state: &mut H) {
        let mut hasher = DefaultHasher::new();
        Hash::hash_slice(&self.0, &mut hasher);
    }
}

impl Serialize for Signature {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut seq = serializer.serialize_tuple(self.0.len())?;
        for elem in &self.0[..] {
            seq.serialize_element(elem)?;
        }
        seq.end()
    }
}

impl<'de> Deserialize<'de> for Signature {
    fn deserialize<D>(deserializer: D) -> Result<Signature, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct ArrayVisitor {
            element: PhantomData<u8>,
        }

        impl<'de> Visitor<'de> for ArrayVisitor {
            type Value = Signature;

            fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
                formatter.write_str(concat!("an array of length ", 64))
            }

            fn visit_seq<A>(self, mut seq: A) -> Result<Signature, A::Error>
            where
                A: SeqAccess<'de>,
            {
                let mut arr = [0u8; 64];
                for (i, byte) in arr.iter_mut().take(64).enumerate() {
                    *byte = seq
                        .next_element()?
                        .ok_or_else(|| Error::invalid_length(i, &self))?;
                }
                Ok(Signature(arr))
            }
        }

        let visitor: ArrayVisitor = ArrayVisitor {
            element: PhantomData,
        };
        deserializer.deserialize_tuple(64, visitor)
    }
}

impl super::Signature for Signature {
    #[inline]
    fn from_base64(base64_data: &str) -> Result<Signature, BaseConvertionError> {
        Ok(Signature(b64::str_base64_to64bytes(base64_data)?))
    }

    fn to_bytes_vector(&self) -> Vec<u8> {
        self.0.to_vec()
    }

    fn to_base64(&self) -> String {
        base64::encode(&self.0[..]) // need to take a slice for required trait `AsRef<[u8]>`
    }
}

impl Display for Signature {
    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
        use super::Signature;

        write!(f, "{}", self.to_base64())
    }
}

impl Debug for Signature {
    // Signature { 1eubHHb... }
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        write!(f, "Signature {{ {} }}", self)
    }
}

impl PartialEq<Signature> for Signature {
    fn eq(&self, other: &Signature) -> bool {
        // No PartialEq for [u8;64], need to use 2 [u8;32]
        self.0[0..32] == other.0[0..32] && self.0[32..64] == other.0[32..64]
    }
}

impl Eq for Signature {}

/// Store a Ed25519 public key.
///
/// Can be generated with [`KeyPairGenerator`].
///
/// [`KeyPairGenerator`]: struct.KeyPairGenerator.html
#[derive(Copy, Clone, Deserialize, PartialEq, Eq, Hash, Serialize)]
pub struct PublicKey(pub [u8; 32]);

impl ToBase58 for PublicKey {
    fn to_base58(&self) -> String {
        self.0.to_base58()
    }
}

impl Display for PublicKey {
    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
        write!(f, "{}", self.to_base58())
    }
}

impl Debug for PublicKey {
    // PublicKey { DNann1L... }
    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
        write!(f, "PublicKey {{ {} }}", self)
    }
}

impl super::PublicKey for PublicKey {
    type Signature = Signature;

    #[inline]
    fn from_base58(base58_data: &str) -> Result<Self, BaseConvertionError> {
        Ok(PublicKey(b58::str_base58_to_32bytes(base58_data)?))
    }

    fn to_bytes_vector(&self) -> Vec<u8> {
        self.0.to_vec()
    }

    fn verify(&self, message: &[u8], signature: &Self::Signature) -> bool {
        crypto::ed25519::verify(message, &self.0, &signature.0)
    }
}

/// Store a Ed25519 private key.
///
/// Can be generated with [`KeyPairGenerator`].
///
/// [`KeyPairGenerator`]: struct.KeyPairGenerator.html
#[derive(Copy, Clone)]
pub struct PrivateKey(pub [u8; 64]);

impl ToBase58 for PrivateKey {
    fn to_base58(&self) -> String {
        self.0.to_base58()
    }
}

impl Display for PrivateKey {
    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
        write!(f, "{}", self.to_base58())
    }
}

impl Debug for PrivateKey {
    // PrivateKey { 468Q1XtT... }
    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
        write!(f, "PrivateKey {{ {} }}", self)
    }
}

impl PartialEq<PrivateKey> for PrivateKey {
    fn eq(&self, other: &PrivateKey) -> bool {
        // No PartialEq for [u8;64], need to use 2 [u8;32]
        self.0[0..32] == other.0[0..32] && self.0[32..64] == other.0[32..64]
    }
}

impl Eq for PrivateKey {}

impl super::PrivateKey for PrivateKey {
    type Signature = Signature;

    #[inline]
    fn from_base58(base58_data: &str) -> Result<Self, BaseConvertionError> {
        Ok(PrivateKey(b58::str_base58_to_64bytes(base58_data)?))
    }

    /// Sign a message with this private key.
    fn sign(&self, message: &[u8]) -> Self::Signature {
        Signature(crypto::ed25519::signature(message, &self.0))
    }
}

/// Store a ed25519 cryptographic key pair (`PublicKey` + `PrivateKey`)
#[derive(Debug, Copy, Clone, Eq)]
pub struct KeyPair {
    /// Store a Ed25519 public key.
    pub pubkey: PublicKey,
    /// Store a Ed25519 private key.
    pub privkey: PrivateKey,
}

impl Display for KeyPair {
    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
        write!(f, "({}, hidden)", self.pubkey.to_base58())
    }
}

impl PartialEq<KeyPair> for KeyPair {
    fn eq(&self, other: &KeyPair) -> bool {
        self.pubkey.eq(&other.pubkey) && self.privkey.eq(&other.privkey)
    }
}

impl super::KeyPair for KeyPair {
    type Signature = Signature;
    type PublicKey = PublicKey;
    type PrivateKey = PrivateKey;

    fn public_key(&self) -> PublicKey {
        self.pubkey
    }

    fn private_key(&self) -> PrivateKey {
        self.privkey
    }

    fn sign(&self, message: &[u8]) -> Signature {
        self.private_key().sign(message)
    }

    fn verify(&self, message: &[u8], signature: &Self::Signature) -> bool {
        self.public_key().verify(message, signature)
    }
}

/// Keypair generator with seed
#[derive(Debug, Copy, Clone)]
pub struct KeyPairFromSeedGenerator {}

impl KeyPairFromSeedGenerator {
    /// Create a keypair based on a given seed.
    ///
    /// The [`PublicKey`](struct.PublicKey.html) will be able to verify messaged signed with
    /// the [`PrivateKey`](struct.PrivateKey.html).
    pub fn generate(seed: &[u8; 32]) -> KeyPair {
        let (private, public) = crypto::ed25519::keypair(seed);
        KeyPair {
            pubkey: PublicKey(public),
            privkey: PrivateKey(private),
        }
    }
}

/// Keypair generator with given parameters for `scrypt` keypair function.
#[derive(Debug, Copy, Clone)]
pub struct KeyPairFromSaltedPasswordGenerator {
    /// The log2 of the Scrypt parameter `N`.
    log_n: u8,
    /// The Scrypt parameter `r`
    r: u32,
    /// The Scrypt parameter `p`
    p: u32,
}

impl KeyPairFromSaltedPasswordGenerator {
    /// Create a `KeyPairGenerator` with default arguments `(log_n: 12, r: 16, p: 1)`
    pub fn with_default_parameters() -> KeyPairFromSaltedPasswordGenerator {
        KeyPairFromSaltedPasswordGenerator {
            log_n: 12,
            r: 16,
            p: 1,
        }
    }

    /// Create a `KeyPairFromSaltedPasswordGenerator` with given arguments.
    ///
    /// # Arguments
    ///
    /// - log_n - The log2 of the Scrypt parameter N
    /// - r - The Scrypt parameter r
    /// - p - The Scrypt parameter p
    pub fn with_parameters(log_n: u8, r: u32, p: u32) -> KeyPairFromSaltedPasswordGenerator {
        KeyPairFromSaltedPasswordGenerator { log_n, r, p }
    }

    /// Create a seed based on a given password and salt.
    pub fn generate_seed(&self, password: &[u8], salt: &[u8]) -> [u8; 32] {
        let mut seed = [0u8; 32];

        crypto::scrypt::scrypt(
            salt,
            password,
            &crypto::scrypt::ScryptParams::new(self.log_n, self.r, self.p),
            &mut seed,
        );

        seed
    }

    /// Create a keypair based on a given password and salt.
    ///
    /// The [`PublicKey`](struct.PublicKey.html) will be able to verify messaged signed with
    /// the [`PrivateKey`](struct.PrivateKey.html).
    pub fn generate(&self, password: &[u8], salt: &[u8]) -> KeyPair {
        let seed: [u8; 32] = self.generate_seed(password, salt);
        KeyPairFromSeedGenerator::generate(&seed)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::keys::{KeyPair, Signature};
    use base58::FromBase58;

    #[test]
    fn base58_private_key() {
        let private58 =
            "468Q1XtTq7h84NorZdWBZFJrGkB18CbmbHr9tkp9snt5GiERP7ySs3wM8myLccbAAGejgMRC9r\
             qnXuW3iAfZACm7";
        let private_key = super::PrivateKey::from_base58(private58).unwrap();
        let private_raw = private58.from_base58().unwrap();

        for (key, raw) in private_key.0.iter().zip(private_raw.iter()) {
            assert_eq!(key, raw);
        }

        assert_eq!(private_key.to_base58(), private58);
        assert_eq!(
            private_key,
            super::PrivateKey::from_base58(private58).unwrap()
        );

        assert_eq!(
            super::PrivateKey::from_base58(
                "468Q1XtTq7h84NorZdWBZFJrGkB18CbmbHr9tkp9snt5GiERP7ySs3wM8myLccbAAGejgMRC9rqnXuW3iA\
                fZACm7djh",
            ).unwrap_err(),
            BaseConvertionError::InvalidLength { found: 67, expected: 64 }
        );
        assert_eq!(
            super::PrivateKey::from_base58(
                "468Q1XtTq7h84NorZdWBZFJrGkB18CbmbHr9tkp9snt5GiERP7ySs3wM8myLccbAAGejgMRC9",
            )
            .unwrap_err(),
            BaseConvertionError::InvalidLength {
                found: 53,
                expected: 64
            }
        );
        assert_eq!(
            super::PrivateKey::from_base58(
                "468Q1XtTq7h84NorZdWBZFJrGkB18CbmbHr9tkp9snt5GiERP7ySs3wM8myLccbAAGejgMRC9<<",
            )
            .unwrap_err(),
            BaseConvertionError::InvalidCharacter {
                character: '<',
                offset: 73
            }
        );
    }

    #[test]
    fn base58_public_key() {
        let public58 = "DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV";
        let public_key = super::PublicKey::from_base58(public58).unwrap();
        let public_raw = public58.from_base58().unwrap();

        for (key, raw) in public_key.0.iter().zip(public_raw.iter()) {
            assert_eq!(key, raw);
        }

        assert_eq!(public_key.to_base58(), public58);
        assert_eq!(public_key, super::PublicKey::from_base58(public58).unwrap());

        assert_eq!(
            super::PublicKey::from_base58("DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLVdjq")
                .unwrap_err(),
            BaseConvertionError::InvalidLength {
                found: 35,
                expected: 32
            }
        );
        assert_eq!(
            super::PublicKey::from_base58("DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQd")
                .unwrap_err(),
            BaseConvertionError::InvalidLength {
                found: 31,
                expected: 32
            }
        );
        assert_eq!(
            super::PublicKey::from_base58("DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQd<<")
                .unwrap_err(),
            BaseConvertionError::InvalidCharacter {
                character: '<',
                offset: 42
            }
        );
    }

    #[test]
    fn base64_signature() {
        let signature64 = "1eubHHbuNfilHMM0G2bI30iZzebQ2cQ1PC7uPAw08FG\
                           MMmQCRerlF/3pc4sAcsnexsxBseA/3lY03KlONqJBAg==";
        let signature = super::Signature::from_base64(signature64).unwrap();
        let signature_raw = base64::decode(signature64).unwrap();

        for (sig, raw) in signature.0.iter().zip(signature_raw.iter()) {
            assert_eq!(sig, raw);
        }

        assert_eq!(
            super::Signature::from_base64("YmhlaW9iaHNlcGlvaGVvaXNlcGl2ZXBvdm5pc2U=").unwrap_err(),
            BaseConvertionError::InvalidLength {
                found: 29,
                expected: 64
            }
        );
        assert_eq!(
            super::Signature::from_base64(
                "YmhlaW9iaHNlcGlvaGVvaXNlcGl2ZXBvdm5pc2V2c2JlaW9idmVpb3Zqc\
                 2V2Z3BpaHNlamVwZ25qZXNqb2dwZWpnaW9zZXNkdnNic3JicmJyZGJyZGI=",
            )
            .unwrap_err(),
            BaseConvertionError::InvalidLength {
                found: 86,
                expected: 64
            }
        );
        assert_eq!(
            super::Signature::from_base64(
                "1eubHHbuNfilHMM0G2bI30iZzebQ2cQ1PC7uPAw08FGMM\
                 mQCRerlF/3pc4sAcsnexsxBseA/3lY03KlONqJBAgdha<<",
            )
            .unwrap_err(),
            BaseConvertionError::InvalidCharacter {
                character: '<',
                offset: 89
            }
        );
    }

    #[test]
    fn message_sign_verify() {
        let pubkey =
            super::PublicKey::from_base58("DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV").unwrap();

        let prikey = super::PrivateKey::from_base58(
            "468Q1XtTq7h84NorZdWBZFJrGkB18CbmbHr9tkp9snt\
             5GiERP7ySs3wM8myLccbAAGejgMRC9rqnXuW3iAfZACm7",
        )
        .unwrap();

        let expected_signature = super::Signature::from_base64(
            "1eubHHbuNfilHMM0G2bI30iZzebQ2cQ1PC7uPAw08FG\
             MMmQCRerlF/3pc4sAcsnexsxBseA/3lY03KlONqJBAg==",
        )
        .unwrap();

        let message = "Version: 10
Type: Identity
Currency: duniter_unit_test_currency
Issuer: DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV
UniqueID: tic
Timestamp: 0-E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855
";

        let sig = prikey.sign(message.as_bytes());

        assert_eq!(sig, expected_signature);
        assert!(pubkey.verify(message.as_bytes(), &sig));
    }

    #[test]
    fn keypair_generate_() {
        let keypair = KeyPairFromSaltedPasswordGenerator::with_default_parameters().generate(
            "JhxtHB7UcsDbA9wMSyMKXUzBZUQvqVyB32KwzS9SWoLkjrUhHV".as_bytes(),
            "JhxtHB7UcsDbA9wMSyMKXUzBZUQvqVyB32KwzS9SWoLkjrUhHV_".as_bytes(),
        );

        assert_eq!(
            keypair.pubkey.to_string(),
            "7iMV3b6j2hSj5WtrfchfvxivS9swN3opDgxudeHq64fb"
        );
    }

    #[test]
    fn keypair_generate_sign_and_verify() {
        let keypair = KeyPairFromSaltedPasswordGenerator::with_default_parameters()
            .generate("password".as_bytes(), "salt".as_bytes());

        let message = "Version: 10
Type: Identity
Currency: duniter_unit_test_currency
Issuer: DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV
UniqueID: tic
Timestamp: 0-E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855
";

        let sig = keypair.sign(message.as_bytes());
        assert!(keypair.verify(message.as_bytes(), &sig));
    }
}