Skip to content

Commit

Permalink
[aptos-keygen] Add seeds to be allowed everywhere
Browse files Browse the repository at this point in the history
  • Loading branch information
gregnazario authored and aptos-bot committed Jun 17, 2022
1 parent 4132cdc commit fc28e9f
Show file tree
Hide file tree
Showing 8 changed files with 64 additions and 14 deletions.
2 changes: 1 addition & 1 deletion crates/aptos-faucet/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ mod tests {
}

fn setup(maximum_amount: Option<u64>) -> (AccountStates, Arc<Service>) {
let mut keygen = KeyGen::from_os_rng();
let mut keygen = KeyGen::from_seed([0; 32]);
let (private_key, public_key) = keygen.generate_ed25519_keypair();
let account_address = AuthenticationKey::ed25519(&public_key).derived_address();

Expand Down
2 changes: 1 addition & 1 deletion crates/aptos-keygen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ impl KeyGen {
pub fn generate_x25519_private_key(
&mut self,
) -> Result<x25519::PrivateKey, CryptoMaterialError> {
let ed25519_private_key = Ed25519PrivateKey::generate(&mut self.0);
let ed25519_private_key = self.generate_ed25519_private_key();
x25519::PrivateKey::from_ed25519_private_bytes(&ed25519_private_key.to_bytes())
}
/// Generate a x25519 key pair.
Expand Down
9 changes: 6 additions & 3 deletions crates/aptos/src/common/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ use crate::common::{
types::{
account_address_from_public_key, CliCommand, CliConfig, CliError, CliTypedResult,
EncodingOptions, PrivateKeyInputOptions, ProfileConfig, ProfileOptions, PromptOptions,
RngArgs,
},
utils::{fund_account, prompt_yes_with_override, read_line},
};
use aptos_crypto::{ed25519::Ed25519PrivateKey, PrivateKey, ValidCryptoMaterialStringExt};
use aptos_keygen::KeyGen;
use async_trait::async_trait;
use clap::Parser;
use reqwest::Url;
Expand All @@ -31,6 +31,8 @@ pub struct InitTool {
#[clap(long)]
pub faucet_url: Option<Url>,
#[clap(flatten)]
pub rng_args: RngArgs,
#[clap(flatten)]
pub(crate) private_key_options: PrivateKeyInputOptions,
#[clap(flatten)]
pub(crate) profile_options: ProfileOptions,
Expand Down Expand Up @@ -134,8 +136,9 @@ impl CliCommand<()> for InitTool {
private_key
} else {
eprintln!("No key given, generating key...");
let mut keygen = KeyGen::from_os_rng();
keygen.generate_ed25519_private_key()
self.rng_args
.key_generator()?
.generate_ed25519_private_key()
}
} else {
Ed25519PrivateKey::from_encoded_string(input)
Expand Down
40 changes: 40 additions & 0 deletions crates/aptos/src/common/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,13 @@ use aptos_crypto::{
ed25519::{Ed25519PrivateKey, Ed25519PublicKey},
x25519, PrivateKey, ValidCryptoMaterial, ValidCryptoMaterialStringExt,
};
use aptos_keygen::KeyGen;
use aptos_logger::debug;
use aptos_rest_client::{aptos_api_types::WriteSetChange, Client, Transaction};
use aptos_types::{chain_id::ChainId, transaction::authenticator::AuthenticationKey};
use async_trait::async_trait;
use clap::{ArgEnum, Parser};
use hex::FromHexError;
use move_deps::move_core_types::account_address::AccountAddress;
use serde::{Deserialize, Serialize};
#[cfg(unix)]
Expand Down Expand Up @@ -123,6 +125,13 @@ impl From<aptos_crypto::CryptoMaterialError> for CliError {
CliError::UnexpectedError(e.to_string())
}
}

impl From<hex::FromHexError> for CliError {
fn from(e: FromHexError) -> Self {
CliError::UnexpectedError(e.to_string())
}
}

/// Config saved to `.aptos/config.yaml`
#[derive(Debug, Serialize, Deserialize)]
pub struct CliConfig {
Expand Down Expand Up @@ -355,6 +364,37 @@ impl EncodingType {
}
}

#[derive(Clone, Debug, Parser)]
pub struct RngArgs {
/// The seed used for key generation, should be a 64 character hex string and mainly used for testing
///
/// This field is hidden from the CLI input for now
#[clap(skip)]
random_seed: Option<String>,
}

impl RngArgs {
pub fn from_seed(seed: [u8; 32]) -> RngArgs {
RngArgs {
random_seed: Some(hex::encode(seed)),
}
}

/// Returns a key generator with the seed if given
pub fn key_generator(&self) -> CliTypedResult<KeyGen> {
if let Some(ref seed) = self.random_seed {
// Strip 0x
let seed = seed.strip_prefix("0x").unwrap_or(seed);
let mut seed_slice = [0u8; 32];

hex::decode_to_slice(seed, &mut seed_slice)?;
Ok(KeyGen::from_seed(seed_slice))
} else {
Ok(KeyGen::from_os_rng())
}
}
}

impl Default for EncodingType {
fn default() -> Self {
EncodingType::Hex
Expand Down
7 changes: 4 additions & 3 deletions crates/aptos/src/genesis/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

use crate::{
common::{
types::{CliError, CliTypedResult, PromptOptions},
types::{CliError, CliTypedResult, PromptOptions, RngArgs},
utils::{check_if_file_exists, read_from_file, write_to_user_only_file},
},
genesis::{
Expand All @@ -14,7 +14,6 @@ use crate::{
};
use aptos_config::{config::IdentityBlob, keys::ConfigKey};
use aptos_crypto::{ed25519::Ed25519PrivateKey, x25519, PrivateKey};
use aptos_keygen::KeyGen;
use aptos_types::transaction::authenticator::AuthenticationKey;
use async_trait::async_trait;
use clap::Parser;
Expand All @@ -31,6 +30,8 @@ const VFN_FILE: &str = "validator-full-node-identity.yaml";
pub struct GenerateKeys {
#[clap(flatten)]
pub(crate) prompt_options: PromptOptions,
#[clap(flatten)]
pub rng_args: RngArgs,
/// Output path for the three keys
#[clap(long, parse(from_os_str), default_value = ".")]
pub(crate) output_dir: PathBuf,
Expand All @@ -50,7 +51,7 @@ impl CliCommand<Vec<PathBuf>> for GenerateKeys {
check_if_file_exists(validator_file.as_path(), self.prompt_options)?;
check_if_file_exists(vfn_file.as_path(), self.prompt_options)?;

let mut keygen = KeyGen::from_os_rng();
let mut keygen = self.rng_args.key_generator()?;
let account_key = ConfigKey::new(keygen.generate_ed25519_private_key());
let consensus_key = ConfigKey::new(keygen.generate_ed25519_private_key());
let validator_network_key = ConfigKey::new(keygen.generate_x25519_private_key()?);
Expand Down
8 changes: 6 additions & 2 deletions crates/aptos/src/genesis/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
// SPDX-License-Identifier: Apache-2.0

use crate::{
common::{types::PromptOptions, utils::write_to_file},
common::{
types::{PromptOptions, RngArgs},
utils::write_to_file,
},
genesis::{
config::{HostAndPort, Layout},
git::{GitOptions, SetupGit},
Expand Down Expand Up @@ -31,7 +34,7 @@ async fn test_genesis_e2e_flow() {
let user_b = "user_b".to_string();
let chain_id = ChainId::test();

let mut keygen = KeyGen::from_os_rng();
let mut keygen = KeyGen::from_seed([0; 32]);

// First step is setup the local git repo
let root_private_key = keygen.generate_ed25519_private_key();
Expand Down Expand Up @@ -144,6 +147,7 @@ async fn generate_keys() -> TempPath {
dir.create_as_dir().unwrap();
let output_dir = PathBuf::from(dir.path());
let command = GenerateKeys {
rng_args: RngArgs::from_seed([0; 32]),
prompt_options: PromptOptions::yes(),
output_dir,
};
Expand Down
7 changes: 4 additions & 3 deletions crates/aptos/src/op/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,14 @@ use crate::{
common::{
types::{
CliError, CliTypedResult, EncodingOptions, EncodingType, ExtractPublicKey, KeyType,
PrivateKeyInputOptions, ProfileOptions, SaveFile,
PrivateKeyInputOptions, ProfileOptions, RngArgs, SaveFile,
},
utils::{append_file_extension, check_if_file_exists, write_to_file},
},
CliCommand, CliResult,
};
use aptos_config::config::{Peer, PeerRole};
use aptos_crypto::{ed25519, x25519, PrivateKey, ValidCryptoMaterial};
use aptos_keygen::KeyGen;
use aptos_types::account_address::{from_identity_public_key, AccountAddress};
use async_trait::async_trait;
use clap::{Parser, Subcommand};
Expand Down Expand Up @@ -104,6 +103,8 @@ pub struct GenerateKey {
#[clap(long, default_value_t = KeyType::Ed25519)]
key_type: KeyType,
#[clap(flatten)]
pub rng_args: RngArgs,
#[clap(flatten)]
save_params: SaveKey,
}

Expand All @@ -115,7 +116,7 @@ impl CliCommand<HashMap<&'static str, PathBuf>> for GenerateKey {

async fn execute(self) -> CliTypedResult<HashMap<&'static str, PathBuf>> {
self.save_params.check_key_file()?;
let mut keygen = KeyGen::from_os_rng();
let mut keygen = self.rng_args.key_generator()?;

match self.key_type {
KeyType::X25519 => {
Expand Down
3 changes: 2 additions & 1 deletion crates/aptos/src/test/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use crate::{
init::InitTool,
types::{
CliConfig, CliTypedResult, EncodingOptions, PrivateKeyInputOptions, ProfileOptions,
PromptOptions, RestOptions, WriteTransactionOptions,
PromptOptions, RestOptions, RngArgs, WriteTransactionOptions,
},
},
CliCommand,
Expand Down Expand Up @@ -134,6 +134,7 @@ impl CliTestFramework {
InitTool {
rest_url: Some(self.endpoint.clone()),
faucet_url: Some(self.faucet_endpoint.clone()),
rng_args: RngArgs::from_seed([0; 32]),
private_key_options: private_key_options(private_key),
profile_options: profile(index),
prompt_options: PromptOptions::yes(),
Expand Down

0 comments on commit fc28e9f

Please sign in to comment.