forc_crypto/keys/
new_key.rs1use super::KeyType;
2use anyhow::Result;
3use fuel_core_types::{
4 fuel_crypto::{
5 rand::{prelude::StdRng, SeedableRng},
6 SecretKey,
7 },
8 fuel_tx::Input,
9};
10use libp2p_identity::{secp256k1, Keypair, PeerId};
11use serde_json::json;
12use std::ops::Deref;
13
14forc_util::cli_examples! {
15 crate::Command {
16 [ Creates a new key default for block production => "forc crypto new-key" ]
17 [ Creates a new key for peering => "forc crypto new-key -k peering" ]
18 [ Creates a new key for block production => "forc crypto new-key -k block-production" ]
19 }
20}
21
22#[derive(Debug, clap::Args)]
24#[clap(version, after_help = help())]
25pub struct Arg {
26 #[clap(
28 long = "key-type",
29 short = 'k',
30 value_enum,
31 default_value = <&'static str>::from(KeyType::BlockProduction),
32 )]
33 key_type: KeyType,
34}
35
36pub fn handler(arg: Arg) -> Result<serde_json::Value> {
37 let mut rng = StdRng::from_entropy();
38 let secret = SecretKey::random(&mut rng);
39 let public_key = secret.public_key();
40 let secret_str = secret.to_string();
41
42 let output = match arg.key_type {
43 KeyType::BlockProduction => {
44 let address = Input::owner(&public_key);
45 json!({
46 "secret": secret_str,
47 "address": address,
48 "type": <KeyType as std::convert::Into<&'static str>>::into(KeyType::BlockProduction),
49 })
50 }
51 KeyType::Peering => {
52 let mut bytes = *secret.deref();
53 let p2p_secret = secp256k1::SecretKey::try_from_bytes(&mut bytes)
54 .expect("Should be a valid private key");
55 let p2p_keypair = secp256k1::Keypair::from(p2p_secret);
56 let libp2p_keypair = Keypair::from(p2p_keypair);
57 let peer_id = PeerId::from_public_key(&libp2p_keypair.public());
58 json!({
59 "secret": secret_str,
60 "peer_id": peer_id.to_string(),
61 "type": <KeyType as std::convert::Into<&'static str>>::into(KeyType::Peering),
62 })
63 }
64 };
65 Ok(output)
66}