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
//! # Account Signing Key and Identifier
//!
//! While managing account there are a couple of items the user will
//! need to manage. The first one being their [`SigningKey`]. This is
//! the key that will be used to sign transactions. Owning this key
//! means that any value associated to this **Account** can be spent.
//!
//! From the [`SigningKey`] we can extract the public [`Identifier`].
//! This is the data that will be used to publicly represent our
//! **Account** on the blockchain.
//!
//! # Example
//!
//! ```
//! # use chain_addr::{Discrimination, AddressReadable};
//! # use jormungandr_lib::crypto::account::{SigningKey, Identifier};
//! # use rand::thread_rng;
//!
//! // generate a signing key
//! let signing_key = SigningKey::generate(thread_rng());
//!
//! // extract the associated identifier
//! let identifier = signing_key.identifier();
//!
//! // get the address to this account:
//! let address = identifier.to_address(Discrimination::Test);
//!
//! println!(
//!   "Please, send money to my account: {}",
//!   AddressReadable::from_address("ca", &address)
//! );
//! ```
//!
//! [`Identifier`]: ./struct.Identifier.html
//! [`SigningKey`]: ./struct.SigningKey.html
//!

use crate::crypto::key;
use chain_addr::{Address, Discrimination};
use chain_crypto::{AsymmetricKey, Ed25519, Ed25519Extended, SecretKey};
use chain_impl_mockchain::{
    account,
    key::{AccountPublicKey, EitherEd25519SecretKey},
};
use rand_core::{CryptoRng, RngCore};
use serde::{Deserialize, Serialize};
use std::{fmt, str::FromStr};
use thiserror::Error;

/// Account identifier, used to identify an account. Cryptographically linked
/// to the account [`SigningKey`].
///
/// [`SigningKey`]: ./struct.SigningKey.html
#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
pub struct Identifier(key::Identifier<account::AccountAlg>);

/// account Singing key. Used to sign transaction. Any owner of this key can
/// utilise the associated values or stake.
///
#[derive(Clone)]
pub struct SigningKey(EitherEd25519SecretKey);

#[derive(Debug, Error)]
pub enum SigningKeyParseError {
    #[error("Invalid bech32: {0}")]
    InvalidBech32Encoding(#[from] bech32::Error),
    #[error("Invalid secret key: {0}")]
    InvalidSecretKey(#[from] chain_crypto::bech32::Error),
    #[error("Unexpected key '{hrp}'. Expected either ed25519 or ed25519extended")]
    UnexpectedHrp { hrp: String },
}

impl Identifier {
    /// get the address associated to this account identifier
    #[inline]
    pub fn to_address(&self, discrimination: Discrimination) -> Address {
        self.0.to_account_address(discrimination)
    }

    /// retrieve the underlying account identifer as used in the library
    /// so you can perform the relevant operations on transaction or the
    /// ledger.
    #[inline]
    pub fn to_inner(&self) -> account::Identifier {
        account::Identifier::from(self.as_ref().clone())
    }

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

    #[inline]
    pub fn from_bech32_str(s: &str) -> Result<Self, chain_crypto::bech32::Error> {
        key::Identifier::from_bech32_str(s).map(Identifier)
    }

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

    #[inline]
    pub fn from_hex(s: &str) -> Result<Self, chain_crypto::PublicKeyFromStrError> {
        key::Identifier::from_hex(s).map(Identifier)
    }
}

impl SigningKey {
    /// get the identifier associated to this key.
    #[inline]
    pub fn identifier(&self) -> Identifier {
        Identifier(self.0.to_public().into())
    }

    /// generate a new _Account_ `SigningKey`
    ///
    /// This function will generate a _normal_ Ed25519 secret key. If you wished to use
    /// an Ed25519Extended secret key, use `generate_extended`.
    #[inline]
    pub fn generate<RNG>(rng: RNG) -> Self
    where
        RNG: RngCore + CryptoRng,
    {
        SigningKey(EitherEd25519SecretKey::Normal(SecretKey::generate(rng)))
    }

    /// generate a new _Account_ `SigningKey`
    ///
    /// This function will generate an _extended_ Ed25519 secret key. If you wished to use
    /// an Ed25519 secret key, use `generate`.
    #[inline]
    pub fn generate_extended<RNG>(rng: RNG) -> Self
    where
        RNG: RngCore + CryptoRng,
    {
        SigningKey(EitherEd25519SecretKey::Extended(SecretKey::generate(rng)))
    }

    #[inline]
    pub fn to_bech32_str(&self) -> String {
        use chain_crypto::bech32::Bech32 as _;
        match &self.0 {
            EitherEd25519SecretKey::Normal(ed25519_key) => ed25519_key.to_bech32_str(),
            EitherEd25519SecretKey::Extended(ed25519e_key) => ed25519e_key.to_bech32_str(),
        }
    }

    #[inline]
    pub fn to_hex(&self) -> String {
        match &self.0 {
            EitherEd25519SecretKey::Normal(ed25519_key) => {
                hex::encode(ed25519_key.clone().leak_secret().as_ref())
            }
            EitherEd25519SecretKey::Extended(ed25519e_key) => {
                hex::encode(ed25519e_key.clone().leak_secret().as_ref())
            }
        }
    }

    #[inline]
    pub fn from_bech32_str(s: &str) -> Result<Self, SigningKeyParseError> {
        use chain_crypto::bech32::Bech32 as _;

        let (hrp, _, _variant) = bech32::decode(s)?;

        let key = match hrp.as_ref() {
            Ed25519::SECRET_BECH32_HRP => SigningKey(EitherEd25519SecretKey::Normal(
                SecretKey::try_from_bech32_str(s)?,
            )),
            Ed25519Extended::SECRET_BECH32_HRP => SigningKey(EitherEd25519SecretKey::Extended(
                SecretKey::try_from_bech32_str(s)?,
            )),
            _ => return Err(SigningKeyParseError::UnexpectedHrp { hrp }),
        };

        Ok(key)
    }
}

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

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

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

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

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

impl AsRef<AccountPublicKey> for Identifier {
    fn as_ref(&self) -> &AccountPublicKey {
        self.0.as_ref()
    }
}

impl AsRef<EitherEd25519SecretKey> for SigningKey {
    fn as_ref(&self) -> &EitherEd25519SecretKey {
        &self.0
    }
}

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

impl From<SecretKey<Ed25519>> for SigningKey {
    fn from(key: SecretKey<Ed25519>) -> Self {
        SigningKey(EitherEd25519SecretKey::Normal(key))
    }
}

impl From<SecretKey<Ed25519Extended>> for SigningKey {
    fn from(key: SecretKey<Ed25519Extended>) -> Self {
        SigningKey(EitherEd25519SecretKey::Extended(key))
    }
}

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

impl From<account::Identifier> for Identifier {
    fn from(identifier: account::Identifier) -> Self {
        Identifier(key::Identifier::from(identifier.as_ref().clone()))
    }
}

impl From<key::Identifier<account::AccountAlg>> for Identifier {
    fn from(identifier: key::Identifier<account::AccountAlg>) -> Self {
        Identifier(identifier)
    }
}

/* ------------------- Serde ----------------------------------------------- */

impl Serialize for SigningKey {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::ser::Serializer,
    {
        if serializer.is_human_readable() {
            self.to_bech32_str().serialize(serializer)
        } else {
            unimplemented!()
        }
    }
}

impl<'de> Deserialize<'de> for SigningKey {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::de::Deserializer<'de>,
    {
        if deserializer.is_human_readable() {
            let s = String::deserialize(deserializer)?;
            SigningKey::from_bech32_str(&s).map_err(<D::Error as serde::de::Error>::custom)
        } else {
            unimplemented!()
        }
    }
}

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

    impl Arbitrary for SigningKey {
        fn arbitrary<G>(g: &mut G) -> Self
        where
            G: Gen,
        {
            if bool::arbitrary(g) {
                let key: key::SigningKey<Ed25519> = key::SigningKey::arbitrary(g);
                SigningKey(EitherEd25519SecretKey::Normal(key.0))
            } else {
                let key: key::SigningKey<Ed25519Extended> = key::SigningKey::arbitrary(g);
                SigningKey(EitherEd25519SecretKey::Extended(key.0))
            }
        }
    }

    impl Arbitrary for Identifier {
        fn arbitrary<G>(g: &mut G) -> Self
        where
            G: Gen,
        {
            SigningKey::arbitrary(g).identifier()
        }
    }

    // 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(
            AccountPublicKey::from_binary(&IDENTIFIER_BYTES)
                .unwrap()
                .into(),
        );

        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(
            AccountPublicKey::from_binary(&IDENTIFIER_BYTES)
                .unwrap()
                .into(),
        );

        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 =
            "---\ned25519e_sk1yqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgq4hu79f\n";
        const SIGNING_KEY_BYTES: [u8; 64] = [0x20; 64];

        let signing_key = SigningKey(EitherEd25519SecretKey::Extended(
            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);
    }

    quickcheck! {
        fn identifier_display_and_from_str(identifier: Identifier) -> TestResult {
            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(identifier: Identifier) -> TestResult {
            let identifier_str = serde_yaml::to_string(&identifier).unwrap();
            let identifier_dec : Identifier = 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) -> TestResult {
            let signing_key_str = serde_yaml::to_string(&signing_key).unwrap();
            let signing_key_dec : SigningKey = 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())
        }
    }
}