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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
//! cryptographic keys and associated interfaces
//!
//! This module provides a wrapping around jormungandr's cryptographic
//! primitives and provide the appropriate trait implementation for
//! user interactions.
//!

use crate::crypto::serde as internal;
use chain_addr::{Address, Discrimination, Kind};
use chain_crypto::{
    bech32::Bech32, AsymmetricKey, AsymmetricPublicKey, Ed25519, PublicKey, SecretKey,
    SignatureFromStrError, SigningAlgorithm, VerificationAlgorithm,
};
use rand_core::{CryptoRng, RngCore};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::{fmt, str::FromStr};

/// a cryptographic identifier. Can be used to identify a signature
/// has been generated by its associated [`SigningKey`].
///
/// More info at the module documentation
///
/// [`SigningKey`]: ./struct.SigningKey.html
///
#[derive(Deserialize, Serialize)]
pub struct Identifier<A: AsymmetricPublicKey>(
    #[serde(
        deserialize_with = "internal::deserialize_public",
        serialize_with = "internal::serialize_public"
    )]
    PublicKey<A>,
);

/// A cryptographic signing key (or secret key). Can be used to
/// sign transaction, certificates or blocks.
///
/// A Signing key is always associated with its [`Identifier`]
/// which can be extracted from the `SigningKey`.
///
/// More info at the module documentation
///
/// [`Identifier`]: ./struct.Identifier.html

pub struct SigningKey<A: AsymmetricKey>(pub(crate) SecretKey<A>);

impl<A> Serialize for SigningKey<A>
where
    A: AsymmetricKey,
    SecretKey<A>: Bech32,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        internal::serialize_secret(&self.0, serializer)
    }
}

impl<'de, A> Deserialize<'de> for SigningKey<A>
where
    A: AsymmetricKey,
    SecretKey<A>: Bech32,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        internal::deserialize_secret(deserializer).map(Self)
    }
}

/// A key pair of the given cryptographic algorithm
///
/// it contains the [`SigningKey`] and the [`Identifier`].
///
/// More info at the module documentation
///
/// [`SigningKey`]: ./struct.SigningKey.html
/// [`Identifier`]: ./struct.Identifier.html
pub struct KeyPair<A: AsymmetricKey>(pub chain_crypto::KeyPair<A>);

impl<A: AsymmetricKey> KeyPair<A> {
    pub fn public_key(&self) -> &PublicKey<<A as AsymmetricKey>::PubAlg> {
        self.0.public_key()
    }
}

/// signature for the given cryptographic algorithm and associated type
/// It can be created from a [`SigningKey`] and a value of type `T` and
/// verified against an [`Identifier`] and the value of type `T`.
///
/// [`SigningKey`]: ./struct.SigningKey.html
/// [`Identifier`]: ./struct.Identifier.html
#[derive(Deserialize, Serialize)]
pub struct Signature<T, A: VerificationAlgorithm>(
    #[serde(
        deserialize_with = "internal::deserialize_signature",
        serialize_with = "internal::serialize_signature"
    )]
    chain_crypto::Signature<T, A>,
);

impl<A: AsymmetricKey> KeyPair<A> {
    /// generate a new key pair with the given Random Number Generator
    #[inline]
    pub fn generate<RNG>(mut rng: RNG) -> Self
    where
        RNG: RngCore + CryptoRng,
    {
        KeyPair(chain_crypto::KeyPair::generate(&mut rng))
    }

    /// retrieve the unique Identifier associated to this KeyPair
    #[inline]
    pub fn identifier(&self) -> Identifier<<A as AsymmetricKey>::PubAlg> {
        Identifier(self.0.public_key().clone())
    }

    /// retrieve the SigningKey
    #[inline]
    pub fn signing_key(&self) -> SigningKey<A> {
        SigningKey(self.0.private_key().clone())
    }
}

impl<A: AsymmetricPublicKey> Identifier<A> {
    #[inline]
    pub fn into_public_key(self) -> PublicKey<A> {
        self.0
    }

    /// encode the `Identifier` into a bech32 string.
    ///
    /// This is a human readable encoding that allows to check input validation.
    /// When displaying this identifier to the user it is preferable to provide
    /// the output of this function.
    ///
    /// Serde implementation of `Identifier` provides the bech32 string support.
    ///
    /// # Example
    ///
    /// ```
    /// # use jormungandr_lib::crypto::key::SigningKey;
    /// # use chain_crypto::Ed25519;
    /// # use rand::thread_rng;
    ///
    /// let key : SigningKey<Ed25519> = SigningKey::generate(thread_rng());
    /// let key = key.identifier();
    ///
    /// println!("key: {}", key.to_bech32_str());
    ///
    /// # assert!(key.to_bech32_str().starts_with("ed25519_pk"))
    /// ```
    ///
    #[inline]
    pub fn to_bech32_str(&self) -> String {
        use chain_crypto::bech32::Bech32 as _;
        self.0.to_bech32_str()
    }

    /// try to decode the given bech32 string into a valid Identifier
    #[inline]
    pub fn from_bech32_str(s: &str) -> Result<Self, chain_crypto::bech32::Error> {
        use chain_crypto::bech32::Bech32 as _;
        PublicKey::try_from_bech32_str(s).map(Identifier)
    }

    /// encode the `Identifier` into an hexadecimal string
    ///
    /// While this is still a human readable format. it is lesser than
    /// the output of [`Self::to_bech32_str`] as it does not provide user input
    /// verification.
    ///
    /// `Display` implementation of `Identifier` provides the hexadecimal string support.
    /// as well as the `FromStr` implementation.
    ///
    /// This format is, for example, used in the REST API.
    ///
    /// # Example
    ///
    /// ```
    /// # use jormungandr_lib::crypto::key::SigningKey;
    /// # use chain_crypto::Ed25519;
    /// # use rand::thread_rng;
    ///
    /// let key : SigningKey<Ed25519> = SigningKey::generate(thread_rng());
    /// let key = key.identifier();
    ///
    /// println!("key: {}", key.to_hex());
    ///
    /// # assert!(key.to_hex().chars().all(|c| "0123456789abcdef".contains(c)))
    /// ```
    ///
    #[inline]
    pub fn to_hex(&self) -> String {
        self.0.to_string()
    }

    /// try to decode the given hexadecimal string into a valid Identifier
    #[inline]
    pub fn from_hex(s: &str) -> Result<Self, chain_crypto::PublicKeyFromStrError> {
        s.parse().map(Identifier)
    }
}

impl Identifier<Ed25519> {
    /// construct a single address
    #[inline]
    pub fn to_single_address(&self, discrimination: Discrimination) -> Address {
        Address(discrimination, Kind::Single(self.0.clone()))
    }

    /// create a group address.
    #[inline]
    pub fn to_group_address(
        &self,
        discrimination: Discrimination,
        group: PublicKey<Ed25519>,
    ) -> Address {
        Address(discrimination, Kind::Group(self.0.clone(), group))
    }

    /// create an account address.
    #[inline]
    pub fn to_account_address(&self, discrimination: Discrimination) -> Address {
        Address(discrimination, Kind::Account(self.0.clone()))
    }
}

impl<A: SigningAlgorithm> SigningKey<A>
where
    <A as AsymmetricKey>::PubAlg: VerificationAlgorithm,
{
    #[inline]
    pub fn sign<T: AsRef<[u8]>>(&self, object: &T) -> Signature<T, <A as AsymmetricKey>::PubAlg> {
        Signature(self.0.sign(object))
    }
}

impl<A: AsymmetricKey> SigningKey<A> {
    #[inline]
    pub fn into_secret_key(self) -> SecretKey<A> {
        self.0
    }

    /// generate a new signing key
    #[inline]
    pub fn generate<RNG>(rng: RNG) -> Self
    where
        RNG: RngCore + CryptoRng,
    {
        SigningKey(SecretKey::generate(rng))
    }

    /// get the identifier associated to this key.
    #[inline]
    pub fn identifier(&self) -> Identifier<<A as AsymmetricKey>::PubAlg> {
        Identifier(self.0.to_public())
    }
}

impl<A> SigningKey<A>
where
    A: AsymmetricKey,
    SecretKey<A>: Bech32,
{
    /// encode the `SigningKey` into a bech32 string.
    ///
    /// This is a human readable encoding that allows to check input validation.
    /// When displaying this signing key to the user it is preferable to provide
    /// the output of this function.
    ///
    /// Serde implementation of `SigningKey` provides the bech32 string support.
    ///
    /// # Example
    ///
    /// ```
    /// # use jormungandr_lib::crypto::key::SigningKey;
    /// # use chain_crypto::Ed25519;
    /// # use rand::thread_rng;
    ///
    /// let key : SigningKey<Ed25519> = SigningKey::generate(thread_rng());
    ///
    /// println!("key: {}", key.to_bech32_str());
    ///
    /// # assert!(key.to_bech32_str().starts_with("ed25519_sk"))
    /// ```
    ///
    #[inline]
    pub fn to_bech32_str(&self) -> String {
        self.0.to_bech32_str()
    }

    /// try to decode the given bech32 string into a valid signing key
    #[inline]
    pub fn from_bech32_str(s: &str) -> Result<Self, chain_crypto::bech32::Error> {
        SecretKey::try_from_bech32_str(s).map(SigningKey)
    }
}

impl<T, A: VerificationAlgorithm> Signature<T, A> {
    /// encode the `Signature` into a bech32 string.
    ///
    /// This is a human readable encoding that allows to check input validation.
    /// When displaying this signing key to the user it is preferable to provide
    /// the output of this function.
    ///
    /// Serde implementation of `Signature` provides the bech32 string support.
    #[inline]
    pub fn to_bech32_str(&self) -> String {
        self.0.to_bech32_str()
    }

    /// try to decode the given bech32 string into a valid signature
    #[inline]
    pub fn from_bech32_str(s: &str) -> Result<Self, chain_crypto::bech32::Error> {
        chain_crypto::Signature::try_from_bech32_str(s).map(Signature::from)
    }

    #[inline]
    pub fn to_hex(&self) -> String {
        self.0.to_string()
    }

    #[inline]
    pub fn from_hex(s: &str) -> Result<Self, SignatureFromStrError> {
        s.parse().map(Signature)
    }

    #[inline]
    pub fn coerce<U>(self) -> Signature<U, A> {
        Signature(self.0.coerce())
    }
}

impl<A: VerificationAlgorithm, T: AsRef<[u8]>> Signature<T, A> {
    #[inline]
    pub fn verify(&self, identifier: &Identifier<A>, object: &T) -> chain_crypto::Verification {
        self.0.verify(identifier.as_ref(), object)
    }
}

/* ---------------- Display ------------------------------------------------ */

impl<A: AsymmetricPublicKey> fmt::Display for Identifier<A> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.to_bech32_str().fmt(f)
    }
}

impl<A: AsymmetricPublicKey> FromStr for Identifier<A> {
    type Err = chain_crypto::bech32::Error;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::from_bech32_str(s)
    }
}

impl<A: AsymmetricPublicKey> fmt::Debug for Identifier<A> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_tuple("Identifier").field(&self.0).finish()
    }
}

impl<A: AsymmetricKey> fmt::Debug for SigningKey<A> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("SigningKey").finish()
    }
}

impl<A: AsymmetricKey> fmt::Debug for KeyPair<A> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("KeyPair").field("0", &self.0).finish()
    }
}

impl<T, A: VerificationAlgorithm> fmt::Display for Signature<T, A> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.to_bech32_str().fmt(f)
    }
}

impl<T, A: VerificationAlgorithm> FromStr for Signature<T, A> {
    type Err = chain_crypto::bech32::Error;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::from_bech32_str(s)
    }
}

impl<T, A: VerificationAlgorithm> fmt::Debug for Signature<T, A> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_tuple("Signature").field(&self.0).finish()
    }
}

/* ---------------- AsRef -------------------------------------------------- */

impl<A: AsymmetricPublicKey> AsRef<PublicKey<A>> for Identifier<A> {
    fn as_ref(&self) -> &PublicKey<A> {
        &self.0
    }
}

impl<A: AsymmetricKey> AsRef<SecretKey<A>> for SigningKey<A> {
    fn as_ref(&self) -> &SecretKey<A> {
        &self.0
    }
}

impl<T, A: VerificationAlgorithm> AsRef<chain_crypto::Signature<T, A>> for Signature<T, A> {
    fn as_ref(&self) -> &chain_crypto::Signature<T, A> {
        &self.0
    }
}

/* ---------------- Conversion --------------------------------------------- */

impl<A: AsymmetricKey> From<SecretKey<A>> for SigningKey<A> {
    fn from(key: SecretKey<A>) -> Self {
        SigningKey(key)
    }
}

impl<A: AsymmetricKey> From<SigningKey<A>> for SecretKey<A> {
    fn from(key: SigningKey<A>) -> Self {
        key.0
    }
}

impl<A: AsymmetricPublicKey> From<PublicKey<A>> for Identifier<A> {
    fn from(key: PublicKey<A>) -> Self {
        Identifier(key)
    }
}

impl<T, A: VerificationAlgorithm> From<chain_crypto::Signature<T, A>> for Signature<T, A> {
    fn from(signature: chain_crypto::Signature<T, A>) -> Self {
        Signature(signature)
    }
}

/* ---------------- Equality ----------------------------------------------- */

impl<A: AsymmetricPublicKey> PartialEq<Identifier<A>> for Identifier<A> {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<A: AsymmetricPublicKey> Eq for Identifier<A> {}

impl<S, T, A: VerificationAlgorithm> PartialEq<Signature<S, A>> for Signature<T, A> {
    fn eq(&self, other: &Signature<S, A>) -> bool {
        self.0.as_ref() == other.0.as_ref()
    }
}

impl<T, A: VerificationAlgorithm> Eq for Signature<T, A> {}

/* ---------------- Comparison --------------------------------------------- */

impl<A: AsymmetricPublicKey> PartialOrd<Identifier<A>> for Identifier<A> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        self.0.partial_cmp(&other.0)
    }
}

impl<A: AsymmetricPublicKey> Ord for Identifier<A> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.0.cmp(&other.0)
    }
}

/* ---------------- Hash --------------------------------------------------- */

impl<A: AsymmetricPublicKey> std::hash::Hash for Identifier<A> {
    fn hash<H>(&self, state: &mut H)
    where
        H: std::hash::Hasher,
    {
        self.0.hash(state)
    }
}

impl<T, A: VerificationAlgorithm> std::hash::Hash for Signature<T, A> {
    fn hash<H>(&self, state: &mut H)
    where
        H: std::hash::Hasher,
    {
        self.0.as_ref().hash(state)
    }
}

/* ---------------- Clone -------------------------------------------------- */

impl<A: AsymmetricPublicKey> Clone for Identifier<A> {
    fn clone(&self) -> Self {
        Identifier(self.0.clone())
    }
}

impl<A: AsymmetricKey> Clone for SigningKey<A> {
    fn clone(&self) -> Self {
        SigningKey(self.0.clone())
    }
}

impl<A: AsymmetricKey> Clone for KeyPair<A> {
    fn clone(&self) -> Self {
        KeyPair(self.0.clone())
    }
}

impl<T, A: VerificationAlgorithm> Clone for Signature<T, A> {
    fn clone(&self) -> Self {
        Signature(self.0.clone())
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use quickcheck::{Arbitrary, Gen, TestResult};

    impl<A> Arbitrary for SigningKey<A>
    where
        <A as AsymmetricKey>::Secret: Send,
        A: AsymmetricKey + 'static,
    {
        fn arbitrary<G>(g: &mut G) -> Self
        where
            G: Gen,
        {
            SigningKey(SecretKey::arbitrary(g))
        }
    }

    impl<A> Arbitrary for KeyPair<A>
    where
        A: AsymmetricKey + 'static,
        A::Secret: Send,
        <A::PubAlg as AsymmetricPublicKey>::Public: Send,
    {
        fn arbitrary<G>(g: &mut G) -> Self
        where
            G: Gen,
        {
            KeyPair(Arbitrary::arbitrary(g))
        }
    }

    impl<T, A> Arbitrary for Signature<T, A>
    where
        A: VerificationAlgorithm + 'static,
        A::Signature: Send,
        T: Send + 'static,
    {
        fn arbitrary<G: Gen>(g: &mut G) -> Self {
            Signature(Arbitrary::arbitrary(g))
        }
    }

    // test to check that account identifier is encoded in hexadecimal
    // when we use the Display trait
    #[test]
    fn identifier_display() {
        const EXPECTED_IDENTIFIER_STR: &str =
            "ed25519_pk1yqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqyl7vm8";
        const IDENTIFIER_BYTES: [u8; 32] = [0x20; 32];

        let identifier: Identifier<Ed25519> =
            Identifier(PublicKey::from_binary(&IDENTIFIER_BYTES).unwrap());

        assert_eq!(identifier.to_string(), EXPECTED_IDENTIFIER_STR);
    }

    // check that the account identifier is encoded with bech32 when utilising
    // serde with a human readable output
    #[test]
    fn identifier_serde_human_readable() {
        const EXPECTED_IDENTIFIER_STR: &str =
            "---\ned25519_pk1yqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqyl7vm8\n";
        const IDENTIFIER_BYTES: [u8; 32] = [0x20; 32];

        let identifier: Identifier<Ed25519> =
            Identifier(PublicKey::from_binary(&IDENTIFIER_BYTES).unwrap());

        let identifier_str = serde_yaml::to_string(&identifier).unwrap();

        assert_eq!(identifier_str, EXPECTED_IDENTIFIER_STR);
    }

    // check that the account signing key is encoded with bech32 when utilising
    // serde with a human readable output
    #[test]
    fn signing_key_serde_human_readable() {
        const EXPECTED_SIGNING_KEY_STR: &str =
            "---\ned25519_sk1yqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsq8j4ww6\n";
        const SIGNING_KEY_BYTES: [u8; 32] = [0x20; 32];

        let signing_key: SigningKey<Ed25519> =
            SigningKey(SecretKey::from_binary(&SIGNING_KEY_BYTES).unwrap());

        let signing_key_str = serde_yaml::to_string(&signing_key).unwrap();

        assert_eq!(signing_key_str, EXPECTED_SIGNING_KEY_STR);
    }

    #[test]
    fn signature_display() {
        const EXPECTED_SIGNATURE_STR: &str =
            "ed25519_sig1yqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgqzlcn38";
        const SIGNATURE_BYTES: [u8; 64] = [0x20; 64];

        let signature: Signature<&'static [u8], Ed25519> =
            Signature(chain_crypto::Signature::from_binary(&SIGNATURE_BYTES).unwrap());

        assert_eq!(signature.to_string(), EXPECTED_SIGNATURE_STR);
    }

    #[test]
    fn signature_serde_human_readable() {
        const EXPECTED_SIGNATURE_STR: &str =
            "---\ned25519_sig1yqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgqzlcn38\n";
        const SIGNATURE_BYTES: [u8; 64] = [0x20; 64];

        let signature: Signature<&'static [u8], Ed25519> =
            Signature(chain_crypto::Signature::from_binary(&SIGNATURE_BYTES).unwrap());

        let signature_str = serde_yaml::to_string(&signature).unwrap();

        assert_eq!(signature_str, EXPECTED_SIGNATURE_STR);
    }

    quickcheck! {
        fn identifier_display_and_from_str(key_pair: KeyPair<Ed25519>) -> TestResult {
            let identifier = key_pair.identifier();
            let identifier_str = identifier.to_string();
            let identifier_dec = match Identifier::from_str(&identifier_str) {
                Err(error) => return TestResult::error(error.to_string()),
                Ok(identifier) => identifier,
            };

            TestResult::from_bool(identifier_dec == identifier)
        }

        fn identifier_serde_human_readable_encode_decode(key_pair: KeyPair<Ed25519>) -> TestResult {
            let identifier = key_pair.identifier();
            let identifier_str = serde_yaml::to_string(&identifier).unwrap();
            let identifier_dec : Identifier<Ed25519> = match serde_yaml::from_str(&identifier_str) {
                Err(error) => return TestResult::error(error.to_string()),
                Ok(identifier) => identifier,
            };

            TestResult::from_bool(identifier_dec == identifier)
        }

        fn signing_key_serde_human_readable_encode_decode(signing_key: SigningKey<Ed25519>) -> TestResult {
            let signing_key_str = serde_yaml::to_string(&signing_key).unwrap();
            let signing_key_dec : SigningKey<Ed25519> = match serde_yaml::from_str(&signing_key_str) {
                Err(error) => return TestResult::error(error.to_string()),
                Ok(signing_key) => signing_key,
            };

            // here we compare the identifiers as there is no other way to compare the
            // secret key (Eq is not implemented for secret -- with reason!).
            TestResult::from_bool(signing_key_dec.identifier() == signing_key.identifier())
        }

        fn identifier_serde_binary_readable_encode_decode(key_pair: KeyPair<Ed25519>) -> TestResult {
            let identifier = key_pair.identifier();
            let identifier_str = bincode::serialize(&identifier).unwrap();
            let identifier_dec : Identifier<Ed25519> = match bincode::deserialize(&identifier_str) {
                Err(error) => return TestResult::error(error.to_string()),
                Ok(identifier) => identifier,
            };

            TestResult::from_bool(identifier_dec == identifier)
        }

        fn signature_display_and_from_str(signature: Signature<&'static [u8], Ed25519>) -> TestResult {
            let signature_str = signature.to_string();
            let signature_dec : Signature<&'static [u8], Ed25519> = match Signature::from_str(&signature_str) {
                Err(error) => return TestResult::error(error.to_string()),
                Ok(signature) => signature,
            };

            TestResult::from_bool(signature_dec == signature)
        }

        fn signature_serde_human_readable_encode_decode(signature: Signature<&'static [u8], Ed25519>) -> TestResult {
            let signature_str = serde_yaml::to_string(&signature).unwrap();
            let signature_dec : Signature<&'static [u8], Ed25519> = match serde_yaml::from_str(&signature_str) {
                Err(error) => return TestResult::error(error.to_string()),
                Ok(signature) => signature,
            };

            // here we compare the identifiers as there is no other way to compare the
            // secret key (Eq is not implemented for secret -- with reason!).
            TestResult::from_bool(signature_dec == signature)
        }

        fn signature_binary_readable_encode_decode(signature: Signature<&'static [u8], Ed25519>) -> TestResult {
            let signature_str = bincode::serialize(&signature).unwrap();
            let signature_dec : Signature<&'static [u8], Ed25519> = match bincode::deserialize(&signature_str) {
                Err(error) => return TestResult::error(error.to_string()),
                Ok(signature) => signature,
            };

            TestResult::from_bool(signature_dec == signature)
        }

        fn sign_verify(data: (Vec<u8>, KeyPair<Ed25519>)) -> TestResult {
            let (data, key_pair) = data;
            let identifier = key_pair.identifier();
            let signing_key = key_pair.signing_key();

            let signature = signing_key.sign(&data);
            match signature.verify(&identifier, &data) {
                chain_crypto::Verification::Success => TestResult::passed(),
                chain_crypto::Verification::Failed => TestResult::error("signature verification failed"),
            }
        }
    }
}