Skip to content

Commit

Permalink
[rooch-networkgh-933] refactor key store and type (2/2).
Browse files Browse the repository at this point in the history
  • Loading branch information
Feliciss committed Oct 11, 2023
1 parent edac265 commit c2ffdd4
Show file tree
Hide file tree
Showing 15 changed files with 140 additions and 78 deletions.
33 changes: 16 additions & 17 deletions crates/rooch-framework-tests/src/tests/ethereum_validator_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,40 +6,39 @@ use moveos_types::transaction::MoveAction;
use rooch_key::keystore::{AccountKeystore, InMemKeystore};
use rooch_types::address::MultiChainAddress;
use rooch_types::framework::empty::Empty;
use rooch_types::transaction::ethereum::EthereumTransactionData;
use rooch_types::transaction::AbstractTransaction;

use crate::binding_test;

// TODO: resolve conversion from rooch address to ethereum address and rooch tx to ethereum tx
#[test]
fn test_validate() {
let binding_test = binding_test::RustBindingTest::new().unwrap();
let ethereum_validator = binding_test
let _ethereum_validator = binding_test
.as_module_bundle::<rooch_types::framework::ethereum_validator::EthereumValidatorModule>(
);
let address_mapping =
binding_test.as_module_bundle::<rooch_types::framework::address_mapping::AddressMapping>();

let keystore = InMemKeystore::new_insecure_for_tests(1);
let sender = keystore.addresses()[0];
let sequence_number = U256::zero();
let _sequence_number = U256::zero();
let action = MoveAction::new_function_call(Empty::empty_function_id(), vec![], vec![]);
let action_bytes =
let _action_bytes =
Bytes::try_from(bcs::to_bytes(&action).unwrap()).expect("Convert action to bytes failed.");
let tx_data = EthereumTransactionData::new_for_test(sender, sequence_number, action_bytes);
keystore
.sign_transaction(&sender, tx_data.clone(), None)
.unwrap();
let auth_info = tx_data.authenticator_info().unwrap();
// let tx_data = EthereumTransactionData::new_for_test(sender_ethereum, sequence_number, action_bytes);
// keystore
// .sign_transaction(&sender, tx_data.clone(), None)
// .unwrap();
// let auth_info = tx_data.authenticator_info().unwrap();
let multichain_address = MultiChainAddress::from(sender);
let resolved_sender = address_mapping
let _resolved_sender = address_mapping
.resovle_or_generate(multichain_address)
.expect("Resolve multichain address should succeed");
let move_tx = tx_data
.construct_moveos_transaction(resolved_sender)
.unwrap();
// let move_tx = tx_data
// .construct_moveos_transaction(resolved_sender)
// .unwrap();

ethereum_validator
.validate(&move_tx.ctx, auth_info.authenticator.payload)
.unwrap()
// ethereum_validator
// .validate(&move_tx.ctx, auth_info.authenticator.payload)
// .unwrap()
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ use rooch_key::keystore::{AccountKeystore, InMemKeystore};
use rooch_types::address::MultiChainAddress;
use rooch_types::framework::session_key::SessionKeyModule;
use rooch_types::framework::timestamp::TimestampModule;
use rooch_types::transaction::ethereum::EthereumTransactionData;
use rooch_types::{addresses::ROOCH_FRAMEWORK_ADDRESS, framework::empty::Empty};
use rooch_types::{
framework::session_key::SessionScope,
Expand Down Expand Up @@ -45,39 +44,40 @@ fn test_validate_rooch() {
.unwrap();
}

// TODO: resolve conversion from rooch address to ethereum address and rooch tx to ethereum tx
#[test]
fn test_validate_ethereum() {
let binding_test = binding_test::RustBindingTest::new().unwrap();
let transaction_validator = binding_test
let _transaction_validator = binding_test
.as_module_bundle::<rooch_types::framework::transaction_validator::TransactionValidator>(
);
let address_mapping =
binding_test.as_module_bundle::<rooch_types::framework::address_mapping::AddressMapping>();

let keystore = InMemKeystore::new_insecure_for_tests(1);
let sender = keystore.addresses()[0];
let sequence_number = U256::zero();
let _sequence_number = U256::zero();
let action = MoveAction::new_function_call(Empty::empty_function_id(), vec![], vec![]);
let action_bytes =
let _action_bytes =
Bytes::try_from(bcs::to_bytes(&action).unwrap()).expect("Convert action to bytes failed.");
let tx_data = EthereumTransactionData::new_for_test(sender, sequence_number, action_bytes);
let tx = keystore
.sign_transaction(&sender, tx_data.clone(), None)
.unwrap();
let auth_info = tx_data.authenticator_info().unwrap();
// let tx_data = EthereumTransactionData::new_for_test(sender, sequence_number, action_bytes);
// let tx = keystore
// .sign_transaction(&sender, tx_data.clone(), None)
// .unwrap();
// let auth_info = tx_data.authenticator_info().unwrap();
let multichain_address = MultiChainAddress::from(sender);
let resolved_sender = address_mapping
let _resolved_sender = address_mapping
.resovle_or_generate(multichain_address)
.expect("Resolve multichain address should succeed");
let move_tx = tx_data
.construct_moveos_transaction(resolved_sender)
.unwrap();

transaction_validator
.validate(&move_tx.ctx, auth_info)
.unwrap()
.into_result()
.unwrap();
// let move_tx = tx_data
// .construct_moveos_transaction(resolved_sender)
// .unwrap();

// transaction_validator
// .validate(&move_tx.ctx, auth_info)
// .unwrap()
// .into_result()
// .unwrap();
}

#[test]
Expand Down
12 changes: 10 additions & 2 deletions crates/rooch-key/src/key_derive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,16 @@ pub fn decrypt_private_key(
pub fn verify_password(
password: Option<String>,
password_hash: String,
) -> Result<bool, argon2::password_hash::Error> {
let parsed_hash = PasswordHash::new(&password_hash)?;
) -> Result<bool, RoochError> {
let parsed_hash = match PasswordHash::new(&password_hash) {
Ok(parsed) => parsed,
Err(err) => {
return Err(RoochError::InvalidPasswordError(format!(
"PasswordHash error: {}",
err
)))
}
};
Ok(Argon2::default()
.verify_password(password.unwrap_or_default().as_bytes(), &parsed_hash)
.is_ok())
Expand Down
4 changes: 2 additions & 2 deletions crates/rooch-rpc-client/src/client_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ pub const ROOCH_TEST_NET_URL: &str = "https://test-seed.rooch.network:443/";
#[serde_as]
#[derive(Serialize, Deserialize, Debug)]
pub struct ClientConfig {
pub keystore_path: PathBuf,
pub password_hash: Option<String>,
pub is_password_empty: bool,
pub keystore_path: PathBuf,
pub active_address: Option<RoochAddress>,
pub envs: Vec<Env>,
pub active_env: Option<String>,
Expand All @@ -31,9 +31,9 @@ pub struct ClientConfig {
impl ClientConfig {
pub fn new(keystore_path: PathBuf) -> Self {
ClientConfig {
keystore_path,
password_hash: None,
is_password_empty: true,
keystore_path,
active_address: None,
envs: vec![],
active_env: None,
Expand Down
7 changes: 6 additions & 1 deletion crates/rooch/src/commands/account/commands/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,12 @@ impl CreateCommand {
.unwrap_or_default();
let is_verified = verify_password(
Some(password.clone()),
context.client_config.password_hash.unwrap_or_default(),
context
.client_config
.password_hash
.as_ref()
.cloned()
.unwrap_or_default(),
)?;

if !is_verified {
Expand Down
9 changes: 7 additions & 2 deletions crates/rooch/src/commands/account/commands/import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,12 @@ impl CommandAction<()> for ImportCommand {
let password = prompt_password("Enter the password saved in client config to import a key pair from mnemonic phrase:").unwrap_or_default();
let is_verified = verify_password(
Some(password.clone()),
context.client_config.password_hash.unwrap_or_default(),
context
.client_config
.password_hash
.as_ref()
.cloned()
.unwrap_or_default(),
)?;

if !is_verified {
Expand All @@ -46,7 +51,7 @@ impl CommandAction<()> for ImportCommand {

context
.keystore
.import_from_mnemonic(&self.mnemonic_phrase, None, Some(&password))?
.import_from_mnemonic(&self.mnemonic_phrase, None, Some(password))?
};

println!("Key imported for address [{}]", result.address);
Expand Down
12 changes: 6 additions & 6 deletions crates/rooch/src/commands/account/commands/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,6 @@ impl CommandAction<()> for ListCommand {
let context = self.context_options.build().await?;
let active_address = context.client_config.active_address;

println!(
"{:^66} | {:^48} | {:^16} | {:^12}",
"Rooch Address (Ed25519)", "Public Key (Base64)", "Auth Validator ID", "Active Address"
);
println!("{}", ["-"; 153].join(""));

let password = if context.client_config.is_password_empty {
None
} else {
Expand All @@ -39,6 +33,12 @@ impl CommandAction<()> for ListCommand {
)
};

println!(
"{:^66} | {:^48} | {:^16} | {:^12}",
"Rooch Address (Ed25519)", "Public Key (Base64)", "Auth Validator ID", "Active Address"
);
println!("{}", ["-"; 153].join(""));

for (address, public_key) in context.keystore.get_address_public_keys(password)? {
let auth_validator_id = public_key.auth_validator().flag();
let active = if active_address == Some(address) {
Expand Down
7 changes: 6 additions & 1 deletion crates/rooch/src/commands/account/commands/nullify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,12 @@ impl CommandAction<ExecuteTransactionResponseView> for NullifyCommand {
.unwrap_or_default();
let is_verified = verify_password(
Some(password.clone()),
context.client_config.password_hash.unwrap_or_default(),
context
.client_config
.password_hash
.as_ref()
.cloned()
.unwrap_or_default(),
)?;

if !is_verified {
Expand Down
11 changes: 8 additions & 3 deletions crates/rooch/src/commands/account/commands/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,12 @@ impl CommandAction<ExecuteTransactionResponseView> for UpdateCommand {
.unwrap_or_default();
let is_verified = verify_password(
Some(password.clone()),
context.client_config.password_hash.unwrap_or_default(),
context
.client_config
.password_hash
.as_ref()
.cloned()
.unwrap_or_default(),
)?;

if !is_verified {
Expand All @@ -68,7 +73,7 @@ impl CommandAction<ExecuteTransactionResponseView> for UpdateCommand {
&existing_address,
self.mnemonic_phrase,
None,
Some(password),
Some(password.clone()),
)?,
Some(password),
)
Expand All @@ -89,6 +94,6 @@ impl CommandAction<ExecuteTransactionResponseView> for UpdateCommand {
let result = context
.sign_and_execute(existing_address, action, password.clone())
.await?;
context.assert_execute_success(result);
context.assert_execute_success(result)
}
}
20 changes: 13 additions & 7 deletions crates/rooch/src/commands/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ use rooch_config::{
use rooch_key::key_derive::hash_password;
use rooch_key::keystore::{AccountKeystore, FileBasedKeystore, Keystore};
use rooch_rpc_client::client_config::{ClientConfig, Env};
use rooch_types::address::RoochAddress;
use rooch_types::error::RoochError;
use rooch_types::error::RoochResult;
use rpassword::prompt_password;
Expand All @@ -28,6 +27,9 @@ pub struct Init {
pub server_url: Option<String>,
#[clap(flatten)]
pub context_options: WalletContextOptions,
/// Whether a non-empty password should be provided to rooch.keystore when it comes to the init command
#[clap(long = "encrypt-keystore")]
pub encrypt_keystore: Option<bool>,
}

#[async_trait]
Expand All @@ -51,7 +53,7 @@ impl CommandAction<()> for Init {
.unwrap_or(&rooch_config_dir()?)
.join(ROOCH_KEYSTORE_FILENAME);

let keystore_result = FileBasedKeystore::<RoochAddress>::new(&keystore_path);
let keystore_result = FileBasedKeystore::new(&keystore_path);
let mut keystore = match keystore_result {
Ok(file_keystore) => Keystore::File(file_keystore),
Err(error) => return Err(RoochError::GenerateKeyError(error.to_string())),
Expand Down Expand Up @@ -135,27 +137,31 @@ impl CommandAction<()> for Init {
};

if let Some(env) = env {
let password = prompt_password("Enter a password to encrypt the keys in the rooch keystore. Press return to have an empty value: ").unwrap_or_default();
let password = if self.encrypt_keystore.is_some() {
Some(prompt_password("Enter a password to encrypt the keys in the rooch keystore. Press return to have an empty value: ").unwrap_or_default())
} else {
None
};

let result = keystore.generate_and_add_new_key(None, None, Some(password))?;
let result = keystore.generate_and_add_new_key(None, None, password.clone())?;
println!("Generated new keypair for address [{}]", result.address);
println!("Secret Recovery Phrase : [{}]", result.result.mnemonic);
let dev_env = Env::new_dev_env();
let active_env_alias = dev_env.alias.clone();

let (password_hash, is_password_empty) = if password.is_empty() {
let (password_hash, is_password_empty) = if password.is_none() {
("$argon2id$v=19$m=19456,t=2,p=1$zc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc0$RysE6tj+Zu0lLhtKJIedVHrKn9FspulS3vLj/UPaVvQ".to_owned(), true)
} else {
(
hash_password(&result.result.encryption.nonce, Some(password))?,
hash_password(&result.result.encryption.nonce, password)?,
false,
)
};

let client_config = ClientConfig {
keystore_path,
password_hash: Some(password_hash),
is_password_empty,
keystore_path,
envs: vec![env, dev_env],
active_address: Some(result.address),
// make dev env as default env
Expand Down
16 changes: 13 additions & 3 deletions crates/rooch/src/commands/move_cli/commands/publish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ impl CommandAction<ExecuteTransactionResponseView> for Publish {
let package_path = self
.move_args
.package_path
.unwrap_or_else(|| std::env::current_dir()?);
.unwrap_or_else(|| std::env::current_dir().unwrap());
let config = self.move_args.build_config.clone();
let mut config = config.clone();

Expand Down Expand Up @@ -162,7 +162,12 @@ impl CommandAction<ExecuteTransactionResponseView> for Publish {
.unwrap_or_default();
let is_verified = verify_password(
Some(password.clone()),
context.client_config.password_hash.unwrap_or_default(),
context
.client_config
.password_hash
.as_ref()
.cloned()
.unwrap_or_default(),
)?;

if !is_verified {
Expand All @@ -189,7 +194,12 @@ impl CommandAction<ExecuteTransactionResponseView> for Publish {
.unwrap_or_default();
let is_verified = verify_password(
Some(password.clone()),
context.client_config.password_hash.unwrap_or_default(),
context
.client_config
.password_hash
.as_ref()
.cloned()
.unwrap_or_default(),
)?;

if !is_verified {
Expand Down
Loading

0 comments on commit c2ffdd4

Please sign in to comment.