ibc-relayer-cli 1.13.2

Hermes is an IBC Relayer written in Rust
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
use core::str::FromStr;
use std::{
    fs,
    path::{Path, PathBuf},
};

use abscissa_core::clap::Parser;
use abscissa_core::{Command, Runnable};

use eyre::eyre;
use hdpath::StandardHDPath;
use ibc_relayer::{
    chain::namada::wallet::CliWalletUtils,
    config::{ChainConfig, Config},
    keyring::{
        AnySigningKeyPair, KeyRing, NamadaKeyPair, Secp256k1KeyPair, SigningKeyPair,
        SigningKeyPairSized, Store,
    },
};
use ibc_relayer_types::core::ics24_host::identifier::ChainId;
use tracing::warn;

use crate::application::app_config;
use crate::conclude::Output;

/// The data structure that represents the arguments when invoking the `keys add` CLI command.
///
/// The command has one argument and two exclusive flags:
///
/// The command to add a key from a file:
///
/// `keys add [OPTIONS] --chain <CHAIN_ID> --key-file <KEY_FILE>`
///
/// The command to restore a key from a file containing its mnemonic:
///
/// `keys add [OPTIONS] --chain <CHAIN_ID> --mnemonic-file <MNEMONIC_FILE>`
///
/// On *nix platforms, both flags also accept `/dev/stdin` as a value, which will read the key or the mnemonic from stdin.
///
/// The `--key-file` and `--mnemonic-file` flags cannot both be provided at the same time, this will cause a terminating error.
///
/// If successful the key will be created or restored, depending on which flag was given.
#[derive(Clone, Command, Debug, Parser, PartialEq, Eq)]
#[clap(override_usage = "Add a key from a Comet keyring file:
        hermes keys add [OPTIONS] --chain <CHAIN_ID> --key-file <KEY_FILE>
    
    Add a key from a file containing its mnemonic:
        hermes keys add [OPTIONS] --chain <CHAIN_ID> --mnemonic-file <MNEMONIC_FILE>
    
    On *nix platforms, both flags also accept `/dev/stdin` as a value, which will read the key or the mnemonic from stdin.")]
pub struct KeysAddCmd {
    #[clap(
        long = "chain",
        required = true,
        help_heading = "FLAGS",
        help = "Identifier of the chain"
    )]
    chain_id: ChainId,

    #[clap(
        long = "key-file",
        required = true,
        value_name = "KEY_FILE",
        help_heading = "FLAGS",
        help = "Path to the key file, or /dev/stdin to read the content from stdin",
        group = "add-restore"
    )]
    key_file: Option<PathBuf>,

    #[clap(
        long = "mnemonic-file",
        required = true,
        value_name = "MNEMONIC_FILE",
        help_heading = "FLAGS",
        help = "Path to file containing the mnemonic to restore the key from, or /dev/stdin to read the mnemonic from stdin",
        group = "add-restore"
    )]
    mnemonic_file: Option<PathBuf>,

    #[clap(
        long = "key-name",
        value_name = "KEY_NAME",
        help = "Name of the key (defaults to the `key_name` defined in the config)"
    )]
    key_name: Option<String>,

    #[clap(
        long = "hd-path",
        value_name = "HD_PATH",
        help = "Derivation path for this key",
        default_value = "m/44'/118'/0'/0/0"
    )]
    hd_path: String,

    #[clap(
        long = "overwrite",
        help = "Overwrite the key if there is already one with the same key name"
    )]
    overwrite: bool,
}

impl KeysAddCmd {
    fn options(&self, config: &Config) -> eyre::Result<KeysAddOptions> {
        let chain_config = config
            .find_chain(&self.chain_id)
            .ok_or_else(|| eyre!("chain '{}' not found in configuration file", self.chain_id))?;

        let name = self
            .key_name
            .clone()
            .unwrap_or_else(|| chain_config.key_name().to_string());

        let hd_path = StandardHDPath::from_str(&self.hd_path)
            .map_err(|_| eyre!("invalid derivation path: {}", self.hd_path))?;

        Ok(KeysAddOptions {
            config: chain_config.clone(),
            name,
            hd_path,
        })
    }
}

#[derive(Clone, Debug)]
pub struct KeysAddOptions {
    pub name: String,
    pub config: ChainConfig,
    pub hd_path: StandardHDPath,
}

impl Runnable for KeysAddCmd {
    fn run(&self) {
        let config = app_config();

        let opts = match self.options(&config) {
            Err(err) => Output::error(err).exit(),
            Ok(result) => result,
        };

        // Check if --key-file or --mnemonic-file was given as input.
        match (self.key_file.clone(), self.mnemonic_file.clone()) {
            (Some(key_file), _) => {
                let key = add_key(
                    &opts.config,
                    &opts.name,
                    &key_file,
                    &opts.hd_path,
                    self.overwrite,
                );
                match key {
                    Ok(key) => Output::success_msg(format!(
                        "Added key '{}' ({}) on chain {}",
                        opts.name,
                        key.account(),
                        opts.config.id(),
                    ))
                    .exit(),
                    Err(e) => Output::error(format!(
                        "An error occurred adding the key on chain {} from file {:?}: {}",
                        self.chain_id, key_file, e
                    ))
                    .exit(),
                }
            }
            (_, Some(mnemonic_file)) => {
                let key = restore_key(
                    &mnemonic_file,
                    &opts.name,
                    &opts.hd_path,
                    &opts.config,
                    self.overwrite,
                );

                match key {
                    Ok(key) => Output::success_msg(format!(
                        "Restored key '{}' ({}) on chain {}",
                        opts.name,
                        key.account(),
                        opts.config.id()
                    ))
                    .exit(),
                    Err(e) => Output::error(format!(
                        "An error occurred restoring the key on chain {} from file {:?}: {}",
                        self.chain_id, mnemonic_file, e
                    ))
                    .exit(),
                }
            }
            // This case should never trigger.
            // The 'required' parameter for the flags will trigger an error if both flags have not been given.
            // And the 'group' parameter for the flags will trigger an error if both flags are given.
            _ => Output::error(
                "--mnemonic-file and --key-file can't both be set or both None".to_string(),
            )
            .exit(),
        }
    }
}

pub fn add_key(
    config: &ChainConfig,
    key_name: &str,
    file: &Path,
    hd_path: &StandardHDPath,
    overwrite: bool,
) -> eyre::Result<AnySigningKeyPair> {
    let key_pair = match config {
        ChainConfig::CosmosSdk(config) => {
            let mut keyring = KeyRing::new_secp256k1(
                Store::Test,
                &config.account_prefix,
                &config.id,
                &config.key_store_folder,
            )?;

            check_key_exists(&keyring, key_name, overwrite);

            let key_contents =
                fs::read_to_string(file).map_err(|_| eyre!("error reading the key file"))?;
            let key_pair = Secp256k1KeyPair::from_seed_file(&key_contents, hd_path)?;

            keyring.add_key(key_name, key_pair.clone())?;
            key_pair.into()
        }
        ChainConfig::Namada(config) => {
            let mut keyring =
                KeyRing::new_namada(Store::Test, &config.id, &config.key_store_folder)?;

            check_key_exists(&keyring, key_name, overwrite);

            let path = if file.is_file() {
                file.parent().ok_or(eyre!("invalid Namada wallet path"))?
            } else {
                file
            };
            let mut wallet = CliWalletUtils::new(path.to_path_buf());
            wallet
                .load()
                .map_err(|e| eyre!("error loading Namada wallet: {e}"))?;

            let secret_key = wallet
                .find_secret_key(key_name, None)
                .map_err(|e| eyre!("error loading the key from Namada wallet: {e}"))?;
            let address = wallet
                .find_address(key_name)
                .ok_or_else(|| eyre!("error loading the address from Namada wallet"))?;
            let namada_key = NamadaKeyPair {
                alias: key_name.to_string(),
                address: address.into_owned(),
                secret_key: secret_key.clone(),
            };
            keyring.add_key(key_name, namada_key.clone())?;
            namada_key.into()
        }
        ChainConfig::Penumbra(_) => unimplemented!("no key storage support for penumbra"),
    };

    Ok(key_pair)
}

pub fn restore_key(
    mnemonic: &Path,
    key_name: &str,
    hdpath: &StandardHDPath,
    config: &ChainConfig,
    overwrite: bool,
) -> eyre::Result<AnySigningKeyPair> {
    let mnemonic_content =
        fs::read_to_string(mnemonic).map_err(|_| eyre!("error reading the mnemonic file"))?;

    let key_pair = match config {
        ChainConfig::CosmosSdk(config) => {
            let mut keyring = KeyRing::new_secp256k1(
                Store::Test,
                &config.account_prefix,
                &config.id,
                &config.key_store_folder,
            )?;

            check_key_exists(&keyring, key_name, overwrite);

            let key_pair = Secp256k1KeyPair::from_mnemonic(
                &mnemonic_content,
                hdpath,
                &config.address_type,
                keyring.account_prefix(),
            )?;

            keyring.add_key(key_name, key_pair.clone())?;
            key_pair.into()
        }
        ChainConfig::Namada(_) => {
            return Err(eyre!(
                "Namada key can't be restored here. Use Namada wallet."
            ));
        }
        ChainConfig::Penumbra(_) => return Err(eyre!("no key storage support for penumbra")),
    };

    Ok(key_pair)
}

/// Check if the key with the given key name already exists.
/// If it already exists and overwrite is false, abort the command with an error.
/// If overwrite is true, output a warning message informing the key will be overwritten.
fn check_key_exists<S: SigningKeyPairSized>(keyring: &KeyRing<S>, key_name: &str, overwrite: bool) {
    if keyring.get_key(key_name).is_ok() {
        if overwrite {
            warn!("key {} will be overwritten", key_name);
        } else {
            Output::error(format!("A key with name '{key_name}' already exists")).exit();
        }
    }
}

#[cfg(test)]
mod tests {

    use super::KeysAddCmd;
    use std::path::PathBuf;

    use abscissa_core::clap::Parser;
    use ibc_relayer_types::core::ics24_host::identifier::ChainId;

    #[test]
    fn test_keys_add_key_file() {
        assert_eq!(
            KeysAddCmd {
                chain_id: ChainId::from_string("chain_id"),
                key_file: Some(PathBuf::from("key_file")),
                mnemonic_file: None,
                key_name: None,
                hd_path: "m/44'/118'/0'/0/0".to_string(),
                overwrite: false,
            },
            KeysAddCmd::parse_from(["test", "--chain", "chain_id", "--key-file", "key_file"])
        )
    }

    #[test]
    fn test_keys_add_mnemonic_file() {
        assert_eq!(
            KeysAddCmd {
                chain_id: ChainId::from_string("chain_id"),
                key_file: None,
                mnemonic_file: Some(PathBuf::from("mnemonic_file")),
                key_name: None,
                hd_path: "m/44'/118'/0'/0/0".to_string(),
                overwrite: false
            },
            KeysAddCmd::parse_from([
                "test",
                "--chain",
                "chain_id",
                "--mnemonic-file",
                "mnemonic_file"
            ])
        )
    }

    #[test]
    fn test_keys_add_key_file_overwrite() {
        assert_eq!(
            KeysAddCmd {
                chain_id: ChainId::from_string("chain_id"),
                key_file: Some(PathBuf::from("key_file")),
                mnemonic_file: None,
                key_name: None,
                hd_path: "m/44'/118'/0'/0/0".to_string(),
                overwrite: true,
            },
            KeysAddCmd::parse_from([
                "test",
                "--chain",
                "chain_id",
                "--key-file",
                "key_file",
                "--overwrite"
            ])
        )
    }

    #[test]
    fn test_keys_add_mnemonic_file_overwrite() {
        assert_eq!(
            KeysAddCmd {
                chain_id: ChainId::from_string("chain_id"),
                key_file: None,
                mnemonic_file: Some(PathBuf::from("mnemonic_file")),
                key_name: None,
                hd_path: "m/44'/118'/0'/0/0".to_string(),
                overwrite: true,
            },
            KeysAddCmd::parse_from([
                "test",
                "--chain",
                "chain_id",
                "--mnemonic-file",
                "mnemonic_file",
                "--overwrite"
            ])
        )
    }

    #[test]
    fn test_keys_add_no_file_nor_mnemonic() {
        assert!(KeysAddCmd::try_parse_from(["test", "--chain", "chain_id"]).is_err());
    }

    #[test]
    fn test_keys_add_key_and_mnemonic() {
        assert!(KeysAddCmd::try_parse_from([
            "test",
            "--chain",
            "chain_id",
            "--key-file",
            "key_file",
            "--mnemonic-file",
            "mnemonic_file"
        ])
        .is_err());
    }

    #[test]
    fn test_keys_add_no_chain() {
        assert!(KeysAddCmd::try_parse_from(["test", "--key-file", "key_file"]).is_err());
    }
}