Skip to content

Commit

Permalink
[cli] Add Task Scheduling Command and Refactor Wallet Context API (#2704
Browse files Browse the repository at this point in the history
)

* [cli] Implement rooch task schedule command

* [gas_market] Add exists_new_events to gas markent and use task schedule in testcase

* [CLI] Refactor wallet context password and sign API
  • Loading branch information
jolestar authored Sep 28, 2024
1 parent d3c6c4c commit 3628788
Show file tree
Hide file tree
Showing 23 changed files with 520 additions and 259 deletions.
26 changes: 9 additions & 17 deletions crates/rooch-faucet/src/faucet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use clap::Parser;
use move_core_types::language_storage::StructTag;
use moveos_types::transaction::MoveAction;
use prometheus::Registry;
use rooch_key::keystore::account_keystore::AccountKeystore;
use rooch_rpc_client::wallet_context::WalletContext;
use rooch_types::address::{MultiChainAddress, RoochAddress};
use rooch_types::authentication_key::AuthenticationKey;
Expand Down Expand Up @@ -55,7 +54,6 @@ impl Default for FaucetConfig {

struct State {
config: FaucetConfig,
wallet_pwd: Option<String>,
context: WalletContext,
// metrics: FaucetMetrics,
}
Expand All @@ -73,17 +71,16 @@ impl Faucet {
faucet_receiver: Receiver<FaucetRequest>,
faucet_error_sender: Sender<FaucetError>,
) -> Result<Self> {
let wallet = WalletContext::new(config.wallet_config_dir.clone()).unwrap();
let mut wallet = WalletContext::new(config.wallet_config_dir.clone()).unwrap();
let _metrics = FaucetMetrics::new(prometheus_registry);
let wallet_pwd = match env::var("ROOCH_FAUCET_PWD") {
Ok(val) => Some(val.parse::<String>().unwrap()),
_ => None,
};

wallet.set_password(wallet_pwd);
Ok(Self {
state: Arc::new(RwLock::new(State {
config,
wallet_pwd,
context: wallet,
})),
faucet_error_sender,
Expand Down Expand Up @@ -122,25 +119,20 @@ impl Faucet {
state: RwLockWriteGuard<'a, State>,
) -> Result<()> {
let sender: RoochAddress = state.context.client_config.active_address.unwrap();
let pwd = state.wallet_pwd.clone();
let tx_data = state
.context
.build_tx_data(sender, action, None)
.await
.map_err(FaucetError::internal)?;
let result = if let Some(session_key) = state.config.session_key.clone() {
let tx_data = state
.context
.build_tx_data(sender, action, None)
.await
.map_err(FaucetError::internal)?;
let tx = state
.context
.keystore
.sign_transaction_via_session_key(&sender, tx_data, &session_key, pwd)
.sign_transaction_via_session_key(&sender, tx_data, &session_key)
.map_err(|e| RoochError::SignMessageError(e.to_string()))
.map_err(FaucetError::internal)?;
state.context.execute(tx).await
} else {
state
.context
.sign_and_execute(sender, action, pwd, None)
.await
state.context.sign_and_execute(sender, tx_data).await
};

match result {
Expand Down
8 changes: 3 additions & 5 deletions crates/rooch-oracle/src/binance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,11 @@ pub struct Binance {

impl Binance {
pub async fn new(config: BinanceConfig) -> Self {
let wallet = WalletContext::new(config.binance_wallet_dir.clone()).unwrap();
let mut wallet = WalletContext::new(config.binance_wallet_dir.clone()).unwrap();
let wallet_pwd = config.binance_wallet_pwd.clone();
wallet.set_password(wallet_pwd);
Self {
wallet_state: Arc::new(RwLock::new(State {
wallet_pwd,
context: wallet,
})),
wallet_state: Arc::new(RwLock::new(State { context: wallet })),
binance_config: config,
}
}
Expand Down
8 changes: 2 additions & 6 deletions crates/rooch-oracle/src/data_process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,6 @@ pub async fn subscribe_http(url: String, tx: mpsc::Sender<Value>, interval: u64)
}

pub struct State {
pub(crate) wallet_pwd: Option<String>,
pub context: WalletContext,
}

Expand All @@ -99,11 +98,8 @@ pub async fn execute_transaction<'a>(
state: RwLockWriteGuard<'a, State>,
) -> Result<()> {
let sender: RoochAddress = state.context.client_config.active_address.unwrap();
let pwd = state.wallet_pwd.clone();
let result = state
.context
.sign_and_execute(sender, action, pwd, None)
.await;
let tx_data = state.context.build_tx_data(sender, action, None).await?;
let result = state.context.sign_and_execute(sender, tx_data).await;
match result {
Ok(tx) => match tx.execution_info.status {
KeptVMStatusView::Executed => {
Expand Down
8 changes: 3 additions & 5 deletions crates/rooch-oracle/src/okx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,11 @@ pub struct Okx {

impl Okx {
pub async fn new(config: OkxConfig) -> Self {
let wallet = WalletContext::new(config.okx_wallet_dir.clone()).unwrap();
let mut wallet = WalletContext::new(config.okx_wallet_dir.clone()).unwrap();
let wallet_pwd = config.okx_wallet_pwd.clone();
wallet.set_password(wallet_pwd);
Self {
wallet_state: Arc::new(RwLock::new(State {
wallet_pwd,
context: wallet,
})),
wallet_state: Arc::new(RwLock::new(State { context: wallet })),
okx_config: config,
}
}
Expand Down
8 changes: 3 additions & 5 deletions crates/rooch-oracle/src/pyth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,11 @@ pub struct Pyth {

impl Pyth {
pub async fn new(config: PythConfig) -> Self {
let wallet = WalletContext::new(config.pyth_wallet_dir.clone()).unwrap();
let mut wallet = WalletContext::new(config.pyth_wallet_dir.clone()).unwrap();
let wallet_pwd = config.pyth_wallet_pwd.clone();
wallet.set_password(wallet_pwd);
Self {
wallet_state: Arc::new(RwLock::new(State {
wallet_pwd,
context: wallet,
})),
wallet_state: Arc::new(RwLock::new(State { context: wallet })),
pyth_config: config,
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use moveos_types::function_return_value::{
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum VMStatusView {
Executed,
MoveAbort {
Expand Down
31 changes: 19 additions & 12 deletions crates/rooch-rpc-client/src/wallet_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use rooch_key::keystore::Keystore;
use rooch_rpc_api::jsonrpc_types::{ExecuteTransactionResponseView, KeptVMStatusView, TxOptions};
use rooch_types::address::RoochAddress;
use rooch_types::address::{BitcoinAddress, ParsedAddress};
use rooch_types::authentication_key::AuthenticationKey;
use rooch_types::bitcoin::network::Network;
use rooch_types::crypto::RoochKeyPair;
use rooch_types::error::{RoochError, RoochResult};
Expand Down Expand Up @@ -224,19 +225,27 @@ impl WalletContext {
Ok(tx_data)
}

pub async fn sign(
pub fn generate_session_key(&mut self, address: &RoochAddress) -> Result<AuthenticationKey> {
self.keystore
.generate_session_key(address, self.password.clone())
}

pub fn sign_transaction_via_session_key(
&self,
sender: RoochAddress,
action: MoveAction,
password: Option<String>,
max_gas_amount: Option<u64>,
signer: &RoochAddress,
tx_data: RoochTransactionData,
authentication_key: &AuthenticationKey,
) -> RoochResult<RoochTransaction> {
let tx_data = self.build_tx_data(sender, action, max_gas_amount).await?;
let tx = self.keystore.sign_transaction(&sender, tx_data, password)?;
let tx = self.keystore.sign_transaction_via_session_key(
signer,
tx_data,
authentication_key,
self.password.clone(),
)?;
Ok(tx)
}

pub async fn sign_transaction(
pub fn sign_transaction(
&self,
signer: RoochAddress,
tx_data: RoochTransactionData,
Expand Down Expand Up @@ -268,11 +277,9 @@ impl WalletContext {
pub async fn sign_and_execute(
&self,
sender: RoochAddress,
action: MoveAction,
password: Option<String>,
max_gas_amount: Option<u64>,
tx_data: RoochTransactionData,
) -> RoochResult<ExecuteTransactionResponseView> {
let tx = self.sign(sender, action, password, max_gas_amount).await?;
let tx = self.sign_transaction(sender, tx_data)?;
self.execute(tx).await
}

Expand Down
6 changes: 6 additions & 0 deletions crates/rooch-types/src/address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -987,6 +987,12 @@ pub enum ParsedAddress {
Bitcoin(BitcoinAddress),
}

impl Default for ParsedAddress {
fn default() -> Self {
Self::Named("default".to_string())
}
}

impl ParsedAddress {
pub fn into_rooch_address(
self,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ impl CommandAction<Option<MultisignAccountOutput>> for CreateMultisignCommand {
let tx_data = context
.build_tx_data(sender, action, self.tx_options.max_gas_amount)
.await?;
let signed_tx = context.sign_transaction(sender, tx_data).await?;
let signed_tx = context.sign_transaction(sender, tx_data)?;
let result = context.execute(signed_tx).await?;
context.assert_execute_success(result)?;
}
Expand Down
73 changes: 9 additions & 64 deletions crates/rooch/src/commands/account/commands/transfer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ use async_trait::async_trait;
use clap::Parser;
use move_command_line_common::types::ParsedStructType;
use move_core_types::u256::U256;
use rooch_key::key_derive::verify_password;
use rooch_key::keystore::account_keystore::AccountKeystore;
use rooch_rpc_api::jsonrpc_types::ExecuteTransactionResponseView;
use rooch_types::address::ParsedAddress;
use rooch_types::address::RoochAddress;
Expand All @@ -16,7 +14,6 @@ use rooch_types::{
error::{RoochError, RoochResult},
transaction::rooch::RoochTransaction,
};
use rpassword::prompt_password;

/// Transfer coins
#[derive(Debug, Parser)]
Expand Down Expand Up @@ -44,7 +41,7 @@ pub struct TransferCommand {
#[async_trait]
impl CommandAction<ExecuteTransactionResponseView> for TransferCommand {
async fn execute(self) -> RoochResult<ExecuteTransactionResponseView> {
let context = self.context.build()?;
let context = self.context.build_require_password()?;
let mapping = context.address_mapping();
let sender: RoochAddress = context.resolve_address(self.tx_options.sender)?.into();
let max_gas_amount: Option<u64> = self.tx_options.max_gas_amount;
Expand All @@ -53,75 +50,23 @@ impl CommandAction<ExecuteTransactionResponseView> for TransferCommand {
let action =
TransferModule::create_transfer_coin_action(coin_type, address_addr, self.amount);

let tx_data = context
.build_tx_data(sender, action, max_gas_amount)
.await?;
match (self.tx_options.authenticator, self.tx_options.session_key) {
(Some(authenticator), _) => {
let tx_data = context
.build_tx_data(sender, action, max_gas_amount)
.await?;
//TODO the authenticator usually is associated with the RoochTransactinData
//So we need to find a way to let user generate the authenticator based on the tx_data.
let tx = RoochTransaction::new(tx_data, authenticator.into());
context.execute(tx).await
}
(_, Some(session_key)) => {
let tx_data = context
.build_tx_data(sender, action, max_gas_amount)
.await?;
let tx = if context.keystore.get_if_password_is_empty() {
context
.keystore
.sign_transaction_via_session_key(&sender, tx_data, &session_key, None)
.map_err(|e| RoochError::SignMessageError(e.to_string()))?
} else {
let password =
prompt_password("Enter the password to run functions:").unwrap_or_default();
let is_verified = verify_password(
Some(password.clone()),
context.keystore.get_password_hash(),
)?;

if !is_verified {
return Err(RoochError::InvalidPasswordError(
"Password is invalid".to_owned(),
));
}

context
.keystore
.sign_transaction_via_session_key(
&sender,
tx_data,
&session_key,
Some(password),
)
.map_err(|e| RoochError::SignMessageError(e.to_string()))?
};
(_, Some(auth_key)) => {
let tx = context
.sign_transaction_via_session_key(&sender, tx_data, &auth_key)
.map_err(|e| RoochError::SignMessageError(e.to_string()))?;
context.execute(tx).await
}
(None, None) => {
if context.keystore.get_if_password_is_empty() {
context
.sign_and_execute(sender, action, None, max_gas_amount)
.await
} else {
let password =
prompt_password("Enter the password to run functions:").unwrap_or_default();
let is_verified = verify_password(
Some(password.clone()),
context.keystore.get_password_hash(),
)?;

if !is_verified {
return Err(RoochError::InvalidPasswordError(
"Password is invalid".to_owned(),
));
}

context
.sign_and_execute(sender, action, Some(password), max_gas_amount)
.await
}
}
(None, None) => context.sign_and_execute(sender, tx_data).await,
}
}
}
1 change: 1 addition & 0 deletions crates/rooch/src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ pub mod server;
pub mod session_key;
pub mod state;
pub mod statedb;
pub mod task;
pub mod transaction;
pub mod upgrade;
pub mod util;
Expand Down
Loading

0 comments on commit 3628788

Please sign in to comment.