Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 13 additions & 9 deletions cli/src/benchmark/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,7 @@ use crate::{
command_utils::get_worker_api_direct,
get_layer_two_nonce,
trusted_cli::TrustedCli,
trusted_command_utils::{
decode_balance, get_identifiers, get_keystore_path, get_pair_from_str,
},
trusted_command_utils::{get_identifiers, get_keystore_path, get_pair_from_str},
trusted_operation::{get_json_request, get_state, perform_trusted_operation, wait_until},
Cli, CliResult, CliResultOk, SR25519_KEY_TYPE,
};
Expand Down Expand Up @@ -289,13 +287,8 @@ fn get_nonce(
);

let getter_start_timer = Instant::now();
let getter_result = get_state(direct_client, shard, &getter).unwrap_or_default();
let nonce = get_state::<Index>(direct_client, shard, &getter).ok().unwrap_or_default();
let getter_execution_time = getter_start_timer.elapsed().as_millis();

let nonce = match getter_result {
Some(encoded_nonce) => Index::decode(&mut encoded_nonce.as_slice()).unwrap(),
None => Default::default(),
};
info!("Nonce getter execution took {} ms", getter_execution_time,);
debug!("Retrieved {:?} nonce for {:?}", nonce, account.public());
nonce
Expand Down Expand Up @@ -375,3 +368,14 @@ fn is_submitted(s: TrustedOperationStatus) -> bool {
fn is_sidechain_block(s: TrustedOperationStatus) -> bool {
matches!(s, InSidechainBlock(_))
}

fn decode_balance(maybe_encoded_balance: Option<Vec<u8>>) -> Option<Balance> {
maybe_encoded_balance.and_then(|encoded_balance| {
if let Ok(vd) = Balance::decode(&mut encoded_balance.as_slice()) {
Some(vd)
} else {
warn!("Could not decode balance. maybe hasn't been set? {:x?}", encoded_balance);
None
}
})
}
2 changes: 1 addition & 1 deletion cli/src/evm/commands/evm_call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ impl EvmCallCommands {
)
.sign(&KeyPair::Sr25519(Box::new(sender)), nonce, &mrenclave, &shard)
.into_trusted_operation(trusted_args.direct);
Ok(perform_trusted_operation(cli, trusted_args, &function_call)
Ok(perform_trusted_operation::<()>(cli, trusted_args, &function_call)
.map(|_| CliResultOk::None)?)
}
}
2 changes: 1 addition & 1 deletion cli/src/evm/commands/evm_create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ impl EvmCreateCommands {
.sign(&from.into(), nonce, &mrenclave, &shard)
.into_trusted_operation(trusted_args.direct);

let _ = perform_trusted_operation(cli, trusted_args, &top)?;
let _ = perform_trusted_operation::<()>(cli, trusted_args, &top)?;

let execution_address = evm_create_address(sender_evm_acc, evm_account_nonce);
info!("trusted call evm_create executed");
Expand Down
21 changes: 8 additions & 13 deletions cli/src/evm/commands/evm_read.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,20 +56,15 @@ impl EvmReadCommands {
TrustedGetter::evm_account_storages(sender_acc, execution_address, H256::zero())
.sign(&KeyPair::Sr25519(Box::new(sender))),
));
let res = perform_trusted_operation(cli, trusted_args, &top)?;

debug!("received result for balance");
if let Some(v) = res {
if let Ok(vd) = H256::decode(&mut v.as_slice()) {
match perform_trusted_operation::<H256>(cli, trusted_args, &top) {
Ok(hash) => {
println!("{:?}", vd);
Ok(CliResultOk::H256 { hash: vd })
} else {
error!("could not decode value. {:x?}", v);
Err(CliError::EvmRead { msg: format!("could not decode value. {:x?}", v) })
}
} else {
error!("Nothing in state!");
Err(CliError::EvmRead { msg: "Nothing in state!".to_string() })
Ok(CliResultOk::H256 { hash })
},
Err(e) => {
error!("Nothing in state! Reason: {:?} !", e);
Err(CliError::EvmRead { msg: "Nothing in state!".to_string() })
},
}
}
}
1 change: 0 additions & 1 deletion cli/src/trusted_base_cli/commands/nonce.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ use crate::{
get_layer_two_nonce, trusted_cli::TrustedCli, trusted_command_utils::get_pair_from_str,
trusted_operation::perform_trusted_operation, Cli, CliResult, CliResultOk,
};
use codec::Decode;
use ita_stf::Index;
use itp_stf_primitives::types::{KeyPair, TrustedOperation};
use log::*;
Expand Down
3 changes: 1 addition & 2 deletions cli/src/trusted_base_cli/commands/set_balance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ use crate::{
trusted_operation::perform_trusted_operation,
Cli, CliResult, CliResultOk,
};
use codec::Decode;
use ita_stf::{Getter, Index, TrustedCall, TrustedCallSigned};
use itp_stf_primitives::{
traits::TrustedCallSigning,
Expand Down Expand Up @@ -60,6 +59,6 @@ impl SetBalanceCommand {
)
.sign(&KeyPair::Sr25519(Box::new(signer)), nonce, &mrenclave, &shard)
.into_trusted_operation(trusted_args.direct);
Ok(perform_trusted_operation(cli, trusted_args, &top).map(|_| CliResultOk::None)?)
Ok(perform_trusted_operation::<()>(cli, trusted_args, &top).map(|_| CliResultOk::None)?)
}
}
4 changes: 2 additions & 2 deletions cli/src/trusted_base_cli/commands/transfer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ use crate::{
trusted_operation::perform_trusted_operation,
Cli, CliResult, CliResultOk,
};
use codec::Decode;
use ita_stf::{Getter, Index, TrustedCall, TrustedCallSigned};
use itp_stf_primitives::{
traits::TrustedCallSigning,
Expand Down Expand Up @@ -65,7 +64,8 @@ impl TransferCommand {
TrustedCall::balance_transfer(from.public().into(), to, self.amount)
.sign(&KeyPair::Sr25519(Box::new(from)), nonce, &mrenclave, &shard)
.into_trusted_operation(trusted_args.direct);
let res = perform_trusted_operation(cli, trusted_args, &top).map(|_| CliResultOk::None)?;
let res =
perform_trusted_operation::<()>(cli, trusted_args, &top).map(|_| CliResultOk::None)?;
info!("trusted call transfer executed");
Ok(res)
}
Expand Down
3 changes: 1 addition & 2 deletions cli/src/trusted_base_cli/commands/unshield_funds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ use crate::{
trusted_operation::perform_trusted_operation,
Cli, CliResult, CliResultOk,
};
use codec::Decode;
use ita_stf::{Getter, Index, TrustedCall, TrustedCallSigned};
use itp_stf_primitives::{
traits::TrustedCallSigning,
Expand Down Expand Up @@ -64,6 +63,6 @@ impl UnshieldFundsCommand {
TrustedCall::balance_unshield(from.public().into(), to, self.amount, shard)
.sign(&KeyPair::Sr25519(Box::new(from)), nonce, &mrenclave, &shard)
.into_trusted_operation(trusted_args.direct);
Ok(perform_trusted_operation(cli, trusted_args, &top).map(|_| CliResultOk::None)?)
Ok(perform_trusted_operation::<()>(cli, trusted_args, &top).map(|_| CliResultOk::None)?)
}
}
23 changes: 4 additions & 19 deletions cli/src/trusted_command_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,9 @@ macro_rules! get_layer_two_nonce {
.sign(&KeyPair::Sr25519(Box::new($signer_pair.clone()))),
));
// final nonce = current system nonce + pending tx count, panic early
let res = perform_trusted_operation($cli, $trusted_args, &top).unwrap_or_default();
let nonce = match res {
Some(n) => Index::decode(&mut n.as_slice()).unwrap_or(0),
None => 0,
};
let nonce = perform_trusted_operation::<Index>($cli, $trusted_args, &top)
.ok()
.unwrap_or_default();
debug!("got system nonce: {:?}", nonce);
let pending_tx_count =
get_pending_trusted_calls_for($cli, $trusted_args, &$signer_pair.public().into()).len();
Expand All @@ -69,20 +67,7 @@ pub(crate) fn get_balance(cli: &Cli, trusted_args: &TrustedCli, arg_who: &str) -
let top = TrustedOperation::<TrustedCallSigned, Getter>::get(Getter::trusted(
TrustedGetter::free_balance(who.public().into()).sign(&KeyPair::Sr25519(Box::new(who))),
));
let res = perform_trusted_operation(cli, trusted_args, &top).unwrap_or(None);
debug!("received result for balance");
decode_balance(res)
}

pub(crate) fn decode_balance(maybe_encoded_balance: Option<Vec<u8>>) -> Option<Balance> {
maybe_encoded_balance.and_then(|encoded_balance| {
if let Ok(vd) = Balance::decode(&mut encoded_balance.as_slice()) {
Some(vd)
} else {
warn!("Could not decode balance. maybe hasn't been set? {:x?}", encoded_balance);
None
}
})
perform_trusted_operation::<Balance>(cli, trusted_args, &top).ok()
}

pub(crate) fn get_keystore_path(trusted_args: &TrustedCli) -> PathBuf {
Expand Down
69 changes: 48 additions & 21 deletions cli/src/trusted_operation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use crate::{
Cli,
};
use base58::{FromBase58, ToBase58};
use codec::{Decode, Encode};
use codec::{Decode, Encode, Input};
use enclave_bridge_primitives::Request;
use ita_stf::{Getter, TrustedCallSigned};
use itc_rpc_client::direct_client::{DirectApi, DirectClient};
Expand All @@ -37,6 +37,7 @@ use my_node_runtime::{Hash, RuntimeEvent};
use pallet_enclave_bridge::Event as EnclaveBridgeEvent;
use sp_core::H256;
use std::{
fmt::Debug,
result::Result as StdResult,
sync::mpsc::{channel, Receiver},
time::Instant,
Expand All @@ -54,35 +55,36 @@ pub(crate) enum TrustedOperationError {
Default { msg: String },
}

pub(crate) type TrustedOpResult = StdResult<Option<Vec<u8>>, TrustedOperationError>;
pub(crate) type TrustedOpResult<T> = StdResult<T, TrustedOperationError>;

pub(crate) fn perform_trusted_operation(
pub(crate) fn perform_trusted_operation<T: Decode + Debug>(
cli: &Cli,
trusted_args: &TrustedCli,
top: &TrustedOperation<TrustedCallSigned, Getter>,
) -> TrustedOpResult {
) -> TrustedOpResult<T> {
match top {
TrustedOperation::indirect_call(_) => send_indirect_request(cli, trusted_args, top),
TrustedOperation::direct_call(_) => send_direct_request(cli, trusted_args, top),
TrustedOperation::get(getter) => execute_getter_from_cli_args(cli, trusted_args, getter),
TrustedOperation::indirect_call(_) => send_indirect_request::<T>(cli, trusted_args, top),
TrustedOperation::direct_call(_) => send_direct_request::<T>(cli, trusted_args, top),
TrustedOperation::get(getter) =>
execute_getter_from_cli_args::<T>(cli, trusted_args, getter),
}
}

fn execute_getter_from_cli_args(
fn execute_getter_from_cli_args<T: Decode + Debug>(
cli: &Cli,
trusted_args: &TrustedCli,
getter: &Getter,
) -> TrustedOpResult {
) -> TrustedOpResult<T> {
let shard = read_shard(trusted_args).unwrap();
let direct_api = get_worker_api_direct(cli);
get_state(&direct_api, shard, getter)
}

pub(crate) fn get_state(
pub(crate) fn get_state<T: Decode + Debug>(
direct_api: &DirectClient,
shard: ShardIdentifier,
getter: &Getter,
) -> TrustedOpResult {
) -> TrustedOpResult<T> {
// Compose jsonrpc call.
let data = Request { shard, cyphertext: getter.encode() };
let rpc_method = "state_executeGetter".to_owned();
Expand All @@ -108,21 +110,27 @@ pub(crate) fn get_state(
})
}

let maybe_state = Option::decode(&mut rpc_return_value.value.as_slice())
let maybe_state: Option<Vec<u8>> = Option::decode(&mut rpc_return_value.value.as_slice())
// Replace with `inspect_err` once it's stable.
.map_err(|err| {
error!("Failed to decode return value: {:?}", err);
TrustedOperationError::Default { msg: "Option::decode".to_string() }
})?;

Ok(maybe_state)
match maybe_state {
Some(state) => {
let decoded = decode_response_value(&mut state.as_slice())?;
Ok(decoded)
},
None => Err(TrustedOperationError::Default { msg: "Value not present".to_string() }),
}
}

fn send_indirect_request(
fn send_indirect_request<T: Decode + Debug>(
cli: &Cli,
trusted_args: &TrustedCli,
trusted_operation: &TrustedOperation<TrustedCallSigned, Getter>,
) -> TrustedOpResult {
) -> TrustedOpResult<T> {
let mut chain_api = get_chain_api(cli);
let encryption_key = get_shielding_key(cli).unwrap();
let call_encrypted = encryption_key.encrypt(&trusted_operation.encode()).unwrap();
Expand Down Expand Up @@ -188,7 +196,10 @@ fn send_indirect_request(
};

if confirmed_block_hash == block_hash {
return Ok(Some(block_hash.encode()))
// encode and decode to target type, this should probably read value from parachain event and
// return that result instead of block hash
let value = decode_response_value(&mut block_hash.encode().as_slice())?;
return Ok(value)
}
}
}
Expand Down Expand Up @@ -235,11 +246,11 @@ pub fn read_shard(trusted_args: &TrustedCli) -> StdResult<ShardIdentifier, codec
}

/// sends a rpc watch request to the worker api server
fn send_direct_request(
fn send_direct_request<T: Decode + Debug>(
cli: &Cli,
trusted_args: &TrustedCli,
operation_call: &TrustedOperation<TrustedCallSigned, Getter>,
) -> TrustedOpResult {
) -> TrustedOpResult<T> {
let encryption_key = get_shielding_key(cli).unwrap();
let shard = read_shard(trusted_args).unwrap();
let jsonrpc_call: String = get_json_request(shard, operation_call, encryption_key);
Expand Down Expand Up @@ -280,19 +291,27 @@ fn send_direct_request(
}
if connection_can_be_closed(status) {
direct_api.close().unwrap();
return Ok(None)
let value =
decode_response_value(&mut return_value.value.as_slice())?;
return Ok(value)
}
},
DirectRequestStatus::Ok => {
debug!("request status is ignored");
direct_api.close().unwrap();
return Ok(None)
let value = decode_response_value(&mut return_value.value.as_slice())?;
return Ok(value)
},
}
if !return_value.do_watch {
debug!("do watch is false, closing connection");
direct_api.close().unwrap();
return Ok(None)
let value = T::decode(&mut return_value.value.as_slice()).map_err(|e| {
TrustedOperationError::Default {
msg: format!("Could not decode result value: {:?}", e),
}
})?;
return Ok(value)
}
};
},
Expand All @@ -307,6 +326,14 @@ fn send_direct_request(
}
}

fn decode_response_value<T: Decode, I: Input>(
value: &mut I,
) -> StdResult<T, TrustedOperationError> {
T::decode(value).map_err(|e| TrustedOperationError::Default {
msg: format!("Could not decode result value: {:?}", e),
})
}

pub(crate) fn get_json_request(
shard: ShardIdentifier,
operation_call: &TrustedOperation<TrustedCallSigned, Getter>,
Expand Down