centichain_keypair/
lib.rs

1use bip39::Mnemonic;
2use sp_core::{
3    ed25519::{self, Public, Signature},
4    Pair,
5};
6
7 pub struct CentichainKey;
8
9impl CentichainKey {
10    ///Generating Centichain network key pairs randomly
11    ///
12    ///The output is a tuple that contains seed phrase and public key
13    ///
14    /// ````
15    pub fn generate() -> (String, Public) {
16        let entropy = rand::random::<[u8; 32]>();
17        let mnemonic = Mnemonic::from_entropy_in(bip39::Language::English, &entropy)
18            .expect("Valid entropy should generate valid mnemonic");
19        let keypair = ed25519::Pair::from_phrase(&mnemonic.to_string(), None)
20            .expect("Valid mnemonic should generate valid keypair");
21        (mnemonic.to_string(), keypair.0.public())
22    }
23
24    ///Returning the public key by getting the seed phrase
25    /// ````
26    pub fn check_phrase<'a>(seed_phrase: &String) -> Result<Public, &'a str> {
27        let keypair = ed25519::Pair::from_phrase(seed_phrase, None);
28        match keypair {
29            Ok(pair) => Ok(pair.0.public()),
30            Err(_) => Err("Your seed phrase is wrong!"),
31        }
32    }
33
34    ///Taking input and returning a signature accepted by the Centichain network
35    /// ````
36    pub fn signing<'a>(seed_phrase: &String, message: &String) -> Result<Signature, &'a str> {
37        let keypair = ed25519::Pair::from_phrase(&seed_phrase, None);
38        match keypair {
39            Ok(pair) => Ok(pair.0.sign(message.as_bytes())),
40            Err(_) => Err("Your seed phrase is wrong!"),
41        }
42    }
43}