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
//! command `key`
use crate::{keystore::key::Key as KeyT, result::Result};
use std::{fmt::Display, result::Result as StdResult, str::FromStr};
use structopt::StructOpt;
use subxt::{
    sp_core::{ecdsa, ed25519, sr25519, Pair},
    sp_runtime::traits::IdentifyAccount,
};

/// Cryptography scheme
#[derive(Debug)]
pub enum Scheme {
    Ecdsa,
    Ed25519,
    Sr25519,
}

impl FromStr for Scheme {
    type Err = &'static str;

    fn from_str(s: &str) -> StdResult<Self, Self::Err> {
        Ok(match s.to_ascii_lowercase().as_str() {
            "ecdsa" => Scheme::Ecdsa,
            "ed25519" => Scheme::Ed25519,
            _ => Scheme::Sr25519,
        })
    }
}

#[derive(Debug, StructOpt)]
pub enum Action {
    /// Generate a random account
    Generate,

    /// Generate a random node libp2p key
    #[cfg(feature = "node-key")]
    #[structopt(name = "generate-node-key")]
    GenerateNodeKey,

    /// Gets a public key and a SS58 address from the provided Secret URI
    Inspect {
        /// Secret URI of the key
        suri: String,
    },

    /// Print the peer ID corresponding to the node key in the given file
    #[cfg(feature = "node-key")]
    InspectNodeKey {
        /// Hex encoding of the secret key
        secret: String,
    },

    /// Sign a message, with a given (secret) key
    Sign {
        /// Secret URI of the key
        suri: String,
        /// Message to sign
        message: String,
    },

    /// Verify a signature for a message
    Verify {
        /// Signature to verify
        signature: String,
        /// Raw message
        message: String,
        /// Public key of the signer of this signature
        pubkey: String,
    },
}

/// Keypair utils
#[derive(Debug, StructOpt)]
pub struct Key {
    /// Cryptography scheme
    #[structopt(short, long, default_value = "sr25519")]
    scheme: Scheme,
    /// Key actions
    #[structopt(subcommand)]
    action: Action,
}

macro_rules! match_scheme {
    ($scheme:expr, $op:tt ($($arg:ident),*), $res:ident, $repeat:expr) => {
        match $scheme {
            Scheme::Ecdsa => {
                let $res = KeyT::$op::<ecdsa::Pair>($($arg),*)?;
                $repeat
            }
            Scheme::Ed25519 => {
                let $res = KeyT::$op::<ed25519::Pair>($($arg),*)?;
                $repeat
            }
            Scheme::Sr25519 => {
                let $res = KeyT::$op::<sr25519::Pair>($($arg),*)?;
                $repeat
            }
        }
    };
}

impl Key {
    /// # NOTE
    ///
    /// Reserved the `passwd` for getting suri from cache.
    pub fn exec(&self, passwd: Option<&str>) -> Result<()> {
        match &self.action {
            Action::Generate => self.generate(passwd)?,
            #[cfg(feature = "node-key")]
            Action::GenerateNodeKey => Self::generate_node_key(),
            Action::Inspect { suri } => self.inspect(suri, passwd)?,
            #[cfg(feature = "node-key")]
            Action::InspectNodeKey { secret } => Self::inspect_node_key(secret)?,
            Action::Sign { suri, message } => self.sign(suri, message, passwd)?,
            Action::Verify {
                signature,
                message,
                pubkey,
            } => self.verify(signature, message, pubkey)?,
        }

        Ok(())
    }

    fn generate(&self, passwd: Option<&str>) -> Result<()> {
        match_scheme!(self.scheme, generate_with_phrase(passwd), res, {
            let (pair, phrase, seed) = res;
            let signer = pair.signer();

            Self::info(&format!("Secret Phrase `{}`", phrase), signer, Some(seed));
        });

        Ok(())
    }

    #[cfg(feature = "node-key")]
    fn generate_node_key() {
        let key = crate::keystore::node::generate();

        println!("Secret:  0x{}", hex::encode(key.0.secret().as_ref()));
        println!("Peer ID: {}", key.1)
    }

    fn info<P>(title: &str, signer: &P, seed: Option<Vec<u8>>)
    where
        P: Pair,
        <P as Pair>::Public: IdentifyAccount,
        <<P as Pair>::Public as IdentifyAccount>::AccountId: Display,
    {
        let ss = if let Some(seed) = seed {
            seed
        } else {
            signer.to_raw_vec()
        };

        println!("{title} is account:");
        println!("\tSecret Seed:  0x{}", hex::encode(&ss[..32]));
        println!("\tPublic key:   0x{}", hex::encode(signer.public()));
        println!("\tSS58 Address: {}", signer.public().into_account());
    }

    fn inspect(&self, suri: &str, passwd: Option<&str>) -> Result<()> {
        let key = KeyT::from_string(suri);
        let key_ref = &key;
        match_scheme!(self.scheme, pair(key_ref, passwd), pair, {
            Self::info(
                &format!("Secret Key URI `{}`", suri),
                pair.0.signer(),
                pair.1,
            )
        });

        Ok(())
    }

    #[cfg(feature = "node-key")]
    fn inspect_node_key(secret: &str) -> Result<()> {
        let data = hex::decode(secret.trim_start_matches("0x"))?;
        let key = crate::keystore::node::inspect(data)?;

        println!("Peer ID: {}", key.1);
        Ok(())
    }

    fn sign(&self, suri: &str, message: &str, passwd: Option<&str>) -> Result<()> {
        let key = KeyT::from_string(suri);
        let key_ref = &key;

        match_scheme!(self.scheme, pair(key_ref, passwd), pair, {
            let signer = pair.0.signer();
            let sig = signer.sign(message.as_bytes());

            println!("Message: {}", message);
            println!("Signature: {}", hex::encode::<&[u8]>(sig.as_ref()));
            Self::info("The signer of this signature", signer, pair.1)
        });

        Ok(())
    }

    fn verify(&self, sig: &str, message: &str, pubkey: &str) -> Result<()> {
        let arr = [sig, pubkey]
            .iter()
            .map(|i| hex::decode(i.trim_start_matches("0x")))
            .collect::<StdResult<Vec<Vec<u8>>, hex::FromHexError>>()?;
        let [sig, msg, pubkey] = [&arr[0], message.as_bytes(), &arr[1]];

        match_scheme!(self.scheme, verify(sig, msg, pubkey), res, {
            println!("Result: {}", res);
        });

        Ok(())
    }
}