diff --git a/scripts/launch-local-binary.sh b/scripts/launch-local-binary.sh index f7a48c8d18..ed5272ac64 100755 --- a/scripts/launch-local-binary.sh +++ b/scripts/launch-local-binary.sh @@ -116,8 +116,8 @@ if [[ -z "${NODE_ENV}" ]]; then else echo "NODE_ENV=${NODE_ENV}" > .env fi -pnpm install -pnpm run register-parathread 2>&1 | tee "$LITENTRY_PARACHAIN_DIR/register-parathread.log" +corepack pnpm install +corepack pnpm run register-parathread 2>&1 | tee "$LITENTRY_PARACHAIN_DIR/register-parathread.log" print_divider echo "upgrade parathread to parachain now ..." @@ -129,8 +129,8 @@ if [[ -z "${NODE_ENV}" ]]; then else echo "NODE_ENV=${NODE_ENV}" > .env fi -pnpm install -pnpm run upgrade-parathread 2>&1 | tee "$LITENTRY_PARACHAIN_DIR/upgrade-parathread.log" +corepack pnpm install +corepack pnpm run upgrade-parathread 2>&1 | tee "$LITENTRY_PARACHAIN_DIR/upgrade-parathread.log" print_divider echo "done. please check $LITENTRY_PARACHAIN_DIR for generated files if need" diff --git a/tee-worker/Cargo.lock b/tee-worker/Cargo.lock index e2a44e297f..db3fc0d7d9 100644 --- a/tee-worker/Cargo.lock +++ b/tee-worker/Cargo.lock @@ -6861,6 +6861,7 @@ dependencies = [ "itp-time-utils", "itp-types", "itp-utils", + "lc-credentials", "litentry-primitives", "log 0.4.20", "pallet-balances", diff --git a/tee-worker/app-libs/stf/src/trusted_call_result.rs b/tee-worker/app-libs/stf/src/trusted_call_result.rs index 5dcd282117..a6dfab766c 100644 --- a/tee-worker/app-libs/stf/src/trusted_call_result.rs +++ b/tee-worker/app-libs/stf/src/trusted_call_result.rs @@ -24,7 +24,7 @@ use itp_types::H256; use litentry_primitives::AesOutput; use std::vec::Vec; -#[derive(Encode, Decode)] +#[derive(Encode, Decode, Debug)] pub enum TrustedCallResult { #[codec(index = 0)] Empty, diff --git a/tee-worker/cli/Cargo.toml b/tee-worker/cli/Cargo.toml index 2f3d0b77d2..ec426c6ac2 100644 --- a/tee-worker/cli/Cargo.toml +++ b/tee-worker/cli/Cargo.toml @@ -48,6 +48,7 @@ itp-stf-primitives = { path = "../core-primitives/stf-primitives" } itp-time-utils = { path = "../core-primitives/time-utils" } itp-types = { path = "../core-primitives/types" } itp-utils = { path = "../core-primitives/utils" } +lc-credentials = { path = "../litentry/core/credentials" } # litentry frame-metadata = "15.0.0" diff --git a/tee-worker/cli/demo_shielding_unshielding.sh b/tee-worker/cli/demo_shielding_unshielding.sh index 1460b984e2..30b0072828 100755 --- a/tee-worker/cli/demo_shielding_unshielding.sh +++ b/tee-worker/cli/demo_shielding_unshielding.sh @@ -245,7 +245,7 @@ echo "✔ ok" echo "" echo "* Send a 2 UNIT balance Transfer Bob -> Charlie (that will fail)" -$CLIENT trusted --direct --mrenclave ${MRENCLAVE} transfer ${ICGACCOUNTBOB} ${ICGACCOUNTCHARLIE} ${AMOUNT_TRANSFER} +$CLIENT trusted --direct --mrenclave ${MRENCLAVE} transfer ${ICGACCOUNTBOB} ${ICGACCOUNTCHARLIE} ${AMOUNT_TRANSFER} || true echo "" echo "* Assert Bob's incognito nonce..." diff --git a/tee-worker/cli/src/benchmark/mod.rs b/tee-worker/cli/src/benchmark/mod.rs index 853b8f8455..43935897b1 100644 --- a/tee-worker/cli/src/benchmark/mod.rs +++ b/tee-worker/cli/src/benchmark/mod.rs @@ -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, wait_until}, Cli, CliResult, CliResultOk, SR25519_KEY_TYPE, }; @@ -368,3 +366,14 @@ fn is_submitted(s: TrustedOperationStatus) -> bool { fn is_sidechain_block(s: TrustedOperationStatus) -> bool { matches!(s, InSidechainBlock(_)) } + +fn decode_balance(maybe_encoded_balance: Option>) -> Option { + 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 + } + }) +} diff --git a/tee-worker/cli/src/error.rs b/tee-worker/cli/src/error.rs index 973aa1cbb8..ad64fb4ca1 100644 --- a/tee-worker/cli/src/error.rs +++ b/tee-worker/cli/src/error.rs @@ -16,9 +16,6 @@ use itp_node_api::api_client::ApiClientError; use itp_types::parentchain::{BlockHash, BlockNumber}; -use std::result::Result as StdResult; - -pub type Result = StdResult; #[derive(Debug, thiserror::Error)] pub enum Error { diff --git a/tee-worker/cli/src/evm/commands/evm_call.rs b/tee-worker/cli/src/evm/commands/evm_call.rs index f35fdb4c73..5eecc6b49a 100644 --- a/tee-worker/cli/src/evm/commands/evm_call.rs +++ b/tee-worker/cli/src/evm/commands/evm_call.rs @@ -22,7 +22,6 @@ use crate::{ trusted_operation::perform_trusted_operation, Cli, CliResult, CliResultOk, }; -use codec::Decode; use ita_stf::{Index, TrustedCall, TrustedGetter, TrustedOperation}; use itp_stf_primitives::types::KeyPair; use itp_types::AccountId; @@ -80,7 +79,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)?) } } diff --git a/tee-worker/cli/src/evm/commands/evm_command_utils.rs b/tee-worker/cli/src/evm/commands/evm_command_utils.rs index b752891312..7d38607fd8 100644 --- a/tee-worker/cli/src/evm/commands/evm_command_utils.rs +++ b/tee-worker/cli/src/evm/commands/evm_command_utils.rs @@ -20,11 +20,8 @@ macro_rules! get_layer_two_evm_nonce { let top: TrustedOperation = TrustedGetter::evm_nonce($signer_pair.public().into()) .sign(&KeyPair::Sr25519(Box::new($signer_pair.clone()))) .into(); - 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::($cli, $trusted_args, &top).unwrap_or_default(); debug!("got evm nonce: {:?}", nonce); nonce }}; diff --git a/tee-worker/cli/src/evm/commands/evm_create.rs b/tee-worker/cli/src/evm/commands/evm_create.rs index f8aa7ab39b..a994057ca9 100644 --- a/tee-worker/cli/src/evm/commands/evm_create.rs +++ b/tee-worker/cli/src/evm/commands/evm_create.rs @@ -22,7 +22,6 @@ use crate::{ trusted_operation::perform_trusted_operation, Cli, CliResult, CliResultOk, }; -use codec::Decode; use ita_stf::{ evm_helpers::evm_create_address, Index, TrustedCall, TrustedGetter, TrustedOperation, }; @@ -80,7 +79,7 @@ impl EvmCreateCommands { .sign(&from.into(), nonce, &mrenclave, &shard) .into_trusted_operation(trusted_args.direct); - let _ = perform_trusted_operation(cli, trusted_args, &top)?; + 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"); diff --git a/tee-worker/cli/src/evm/commands/evm_read.rs b/tee-worker/cli/src/evm/commands/evm_read.rs index 51e3427e7f..a57ab68015 100644 --- a/tee-worker/cli/src/evm/commands/evm_read.rs +++ b/tee-worker/cli/src/evm/commands/evm_read.rs @@ -17,9 +17,8 @@ use crate::{ trusted_cli::TrustedCli, trusted_command_utils::get_pair_from_str, - trusted_operation::perform_trusted_operation, Cli, CliError, CliResult, CliResultOk, + trusted_operation::perform_trusted_operation, Cli, CliResult, CliResultOk, }; -use codec::Decode; use ita_stf::{TrustedGetter, TrustedOperation}; use itp_stf_primitives::types::KeyPair; use itp_types::AccountId; @@ -56,20 +55,7 @@ impl EvmReadCommands { TrustedGetter::evm_account_storages(sender_acc.into(), execution_address, H256::zero()) .sign(&KeyPair::Sr25519(Box::new(sender))) .into(); - 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()) { - 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() }) - } + let hash = perform_trusted_operation::(cli, trusted_args, &top)?; + Ok(CliResultOk::H256 { hash }) } } diff --git a/tee-worker/cli/src/trusted_base_cli/commands/litentry/id_graph.rs b/tee-worker/cli/src/trusted_base_cli/commands/litentry/id_graph.rs index 2373584cce..e75483a39f 100644 --- a/tee-worker/cli/src/trusted_base_cli/commands/litentry/id_graph.rs +++ b/tee-worker/cli/src/trusted_base_cli/commands/litentry/id_graph.rs @@ -18,7 +18,6 @@ use crate::{ trusted_cli::TrustedCli, trusted_command_utils::get_pair_from_str, trusted_operation::perform_trusted_operation, Cli, CliResult, CliResultOk, }; -use codec::Decode; use ita_stf::{IDGraph, Runtime, TrustedGetter, TrustedOperation}; use itp_stf_primitives::types::KeyPair; use litentry_primitives::Identity; @@ -45,9 +44,8 @@ impl IDGraphCommand { let top: TrustedOperation = TrustedGetter::id_graph(id).sign(&KeyPair::Sr25519(Box::new(alice))).into(); - let idgraph = perform_trusted_operation(cli, trusted_cli, &top) - .map(|v| IDGraph::::decode(&mut v.unwrap().as_slice()).ok()); - println!("{:?}", idgraph.unwrap().unwrap()); + let idgraph = perform_trusted_operation::>(cli, trusted_cli, &top); + println!("{:?}", idgraph.unwrap()); Ok(CliResultOk::None) } diff --git a/tee-worker/cli/src/trusted_base_cli/commands/litentry/id_graph_stats.rs b/tee-worker/cli/src/trusted_base_cli/commands/litentry/id_graph_stats.rs index 926b6c7ad5..38a75c5232 100644 --- a/tee-worker/cli/src/trusted_base_cli/commands/litentry/id_graph_stats.rs +++ b/tee-worker/cli/src/trusted_base_cli/commands/litentry/id_graph_stats.rs @@ -18,7 +18,6 @@ use crate::{ trusted_cli::TrustedCli, trusted_command_utils::get_pair_from_str, trusted_operation::perform_trusted_operation, Cli, CliError, CliResult, CliResultOk, }; -use codec::Decode; use ita_stf::{TrustedGetter, TrustedOperation}; use itp_stf_primitives::types::KeyPair; use litentry_primitives::ParentchainAccountId; @@ -38,25 +37,17 @@ impl IDGraphStats { let top: TrustedOperation = TrustedGetter::id_graph_stats(who.public().into()) .sign(&KeyPair::Sr25519(Box::new(who))) .into(); - let id_graph_stats = perform_trusted_operation(cli, trusted_cli, &top) - .map(|v| IDGraphStatsVec::decode(&mut v.unwrap().as_slice()).ok()); - + let id_graph_stats = perform_trusted_operation::(cli, trusted_cli, &top); println!("IDGraph stats:"); match id_graph_stats { Ok(id_graph_stats) => { - let total_number = id_graph_stats - .map(|stats| { - let mut total_number = 0_u32; - - stats.iter().for_each(|item| { - total_number += item.1; + let mut total_number = 0_u32; - println!("{:?} -> {}", item.0, item.1); - }); + id_graph_stats.iter().for_each(|item| { + total_number += item.1; - total_number - }) - .unwrap(); + println!("{:?} -> {}", item.0, item.1); + }); println!("Total number: {}", total_number); Ok(CliResultOk::None) diff --git a/tee-worker/cli/src/trusted_base_cli/commands/litentry/link_identity.rs b/tee-worker/cli/src/trusted_base_cli/commands/litentry/link_identity.rs index e348756c97..b57cd597a4 100644 --- a/tee-worker/cli/src/trusted_base_cli/commands/litentry/link_identity.rs +++ b/tee-worker/cli/src/trusted_base_cli/commands/litentry/link_identity.rs @@ -22,11 +22,9 @@ use crate::{ Cli, CliResult, CliResultOk, }; use clap::Parser; -use codec::Decode; use ita_stf::{Index, TrustedCall, TrustedOperation}; use itp_stf_primitives::types::KeyPair; use litentry_primitives::{Identity, Web3Network}; -use log::*; use sp_core::Pair; // usage exmaple: @@ -79,6 +77,6 @@ impl LinkIdentityCommand { ) .sign(&KeyPair::Sr25519(Box::new(alice)), nonce, &mrenclave, &shard) .into_trusted_operation(trusted_cli.direct); - Ok(perform_trusted_operation(cli, trusted_cli, &top).map(|_| CliResultOk::None)?) + Ok(perform_trusted_operation::<()>(cli, trusted_cli, &top).map(|_| CliResultOk::None)?) } } diff --git a/tee-worker/cli/src/trusted_base_cli/commands/litentry/request_vc.rs b/tee-worker/cli/src/trusted_base_cli/commands/litentry/request_vc.rs index 9406684e52..dd5ab97c7e 100644 --- a/tee-worker/cli/src/trusted_base_cli/commands/litentry/request_vc.rs +++ b/tee-worker/cli/src/trusted_base_cli/commands/litentry/request_vc.rs @@ -21,18 +21,17 @@ use crate::{ trusted_operation::perform_trusted_operation, Cli, CliResult, CliResultOk, }; -use codec::Decode; -use ita_stf::{Index, TrustedCall, TrustedOperation}; +use ita_stf::{trusted_call_result::RequestVCResult, Index, TrustedCall, TrustedOperation}; use itp_stf_primitives::types::KeyPair; use itp_utils::hex::decode_hex; +use lc_credentials::Credential; use litentry_primitives::{ - AchainableAmount, AchainableAmountHolding, AchainableAmountToken, AchainableAmounts, - AchainableBasic, AchainableBetweenPercents, AchainableClassOfYear, AchainableDate, - AchainableDateInterval, AchainableDatePercent, AchainableParams, AchainableToken, Assertion, - GenericDiscordRoleType, Identity, OneBlockCourseType, ParameterString, SoraQuizType, - Web3Network, + aes_decrypt, AchainableAmount, AchainableAmountHolding, AchainableAmountToken, + AchainableAmounts, AchainableBasic, AchainableBetweenPercents, AchainableClassOfYear, + AchainableDate, AchainableDateInterval, AchainableDatePercent, AchainableParams, + AchainableToken, Assertion, GenericDiscordRoleType, Identity, OneBlockCourseType, + ParameterString, RequestAesKey, SoraQuizType, Web3Network, REQUEST_AES_KEY_LEN, }; -use log::*; use sp_core::Pair; // usage example (you can always use --help on subcommands to see more details) @@ -412,13 +411,34 @@ impl RequestVcCommand { }, }; - let top: TrustedOperation = - TrustedCall::request_vc(alice.public().into(), id, assertion, None, Default::default()) - .sign(&KeyPair::Sr25519(Box::new(alice)), nonce, &mrenclave, &shard) - .into_trusted_operation(trusted_cli.direct); + let key = Self::random_aes_key(); - // TODO: P-177, print actual VC content to stdout - let _vc = perform_trusted_operation(cli, trusted_cli, &top).unwrap(); + let top: TrustedOperation = TrustedCall::request_vc( + alice.public().into(), + id, + assertion, + Some(key), + Default::default(), + ) + .sign(&KeyPair::Sr25519(Box::new(alice)), nonce, &mrenclave, &shard) + .into_trusted_operation(trusted_cli.direct); + + match perform_trusted_operation::(cli, trusted_cli, &top) { + Ok(mut vc) => { + let decrypted = aes_decrypt(&key, &mut vc.vc_payload).unwrap(); + let credential: Credential = serde_json::from_slice(&decrypted).unwrap(); + println!("----Generated VC-----"); + println!("{:?}", credential); + }, + Err(e) => { + println!("{:?}", e); + }, + } Ok(CliResultOk::None) } + + fn random_aes_key() -> RequestAesKey { + let random: Vec = (0..REQUEST_AES_KEY_LEN).map(|_| rand::random::()).collect(); + random[0..REQUEST_AES_KEY_LEN].try_into().unwrap() + } } diff --git a/tee-worker/cli/src/trusted_base_cli/commands/litentry/request_vc_direct.rs b/tee-worker/cli/src/trusted_base_cli/commands/litentry/request_vc_direct.rs index 0b733b6435..aef665b036 100644 --- a/tee-worker/cli/src/trusted_base_cli/commands/litentry/request_vc_direct.rs +++ b/tee-worker/cli/src/trusted_base_cli/commands/litentry/request_vc_direct.rs @@ -22,17 +22,17 @@ use crate::{ trusted_operation::perform_direct_operation, Cli, CliResult, CliResultOk, }; -use codec::Decode; -use ita_stf::{Index, TrustedCall, TrustedOperation}; +use ita_stf::{trusted_call_result::RequestVCResult, Index, TrustedCall, TrustedOperation}; use itp_stf_primitives::types::KeyPair; use itp_utils::hex::decode_hex; +use lc_credentials::Credential; use litentry_primitives::{ - AchainableAmount, AchainableAmountHolding, AchainableAmountToken, AchainableAmounts, - AchainableBasic, AchainableBetweenPercents, AchainableClassOfYear, AchainableDate, - AchainableDateInterval, AchainableDatePercent, AchainableParams, AchainableToken, Assertion, - GenericDiscordRoleType, Identity, OneBlockCourseType, RequestAesKey, SoraQuizType, Web3Network, + aes_decrypt, AchainableAmount, AchainableAmountHolding, AchainableAmountToken, + AchainableAmounts, AchainableBasic, AchainableBetweenPercents, AchainableClassOfYear, + AchainableDate, AchainableDateInterval, AchainableDatePercent, AchainableParams, + AchainableToken, Assertion, GenericDiscordRoleType, Identity, OneBlockCourseType, + RequestAesKey, SoraQuizType, Web3Network, }; -use log::*; use sp_core::Pair; // usage example (you can always use --help on subcommands to see more details) @@ -253,7 +253,17 @@ impl RequestVcDirectCommand { .into_trusted_operation(trusted_cli.direct); // This should contain the AES Key for AESRequest - let _vc = perform_direct_operation(cli, trusted_cli, &top, key).unwrap(); + match perform_direct_operation::(cli, trusted_cli, &top, key) { + Ok(mut vc) => { + let decrypted = aes_decrypt(&key, &mut vc.vc_payload).unwrap(); + let credential: Credential = serde_json::from_slice(&decrypted).unwrap(); + println!("----Generated VC-----"); + println!("{:?}", credential); + }, + Err(e) => { + println!("{:?}", e); + }, + } Ok(CliResultOk::None) } } diff --git a/tee-worker/cli/src/trusted_base_cli/commands/litentry/send_erroneous_parentchain_call.rs b/tee-worker/cli/src/trusted_base_cli/commands/litentry/send_erroneous_parentchain_call.rs index 4ec70ca3a7..960c510ae5 100644 --- a/tee-worker/cli/src/trusted_base_cli/commands/litentry/send_erroneous_parentchain_call.rs +++ b/tee-worker/cli/src/trusted_base_cli/commands/litentry/send_erroneous_parentchain_call.rs @@ -21,10 +21,8 @@ use crate::{ trusted_operation::perform_trusted_operation, Cli, CliResult, CliResultOk, }; -use codec::Decode; use ita_stf::{Index, TrustedCall, TrustedOperation}; use itp_stf_primitives::types::KeyPair; -use log::*; use sp_core::Pair; #[derive(Parser)] @@ -41,6 +39,6 @@ impl SendErroneousParentchainCallCommand { TrustedCall::send_erroneous_parentchain_call(root.public().into()) .sign(&KeyPair::Sr25519(Box::new(root)), nonce, &mrenclave, &shard) .into_trusted_operation(trusted_cli.direct); - Ok(perform_trusted_operation(cli, trusted_cli, &top).map(|_| CliResultOk::None)?) + Ok(perform_trusted_operation::<()>(cli, trusted_cli, &top).map(|_| CliResultOk::None)?) } } diff --git a/tee-worker/cli/src/trusted_base_cli/commands/set_balance.rs b/tee-worker/cli/src/trusted_base_cli/commands/set_balance.rs index 635345b88a..aa1bd18f8c 100644 --- a/tee-worker/cli/src/trusted_base_cli/commands/set_balance.rs +++ b/tee-worker/cli/src/trusted_base_cli/commands/set_balance.rs @@ -22,7 +22,6 @@ use crate::{ trusted_operation::perform_trusted_operation, Cli, CliResult, CliResultOk, }; -use codec::Decode; use ita_stf::{Index, TrustedCall, TrustedOperation}; use itp_stf_primitives::types::KeyPair; use litentry_primitives::ParentchainBalance as Balance; @@ -57,6 +56,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)?) } } diff --git a/tee-worker/cli/src/trusted_base_cli/commands/transfer.rs b/tee-worker/cli/src/trusted_base_cli/commands/transfer.rs index 1905291032..e544857356 100644 --- a/tee-worker/cli/src/trusted_base_cli/commands/transfer.rs +++ b/tee-worker/cli/src/trusted_base_cli/commands/transfer.rs @@ -22,7 +22,6 @@ use crate::{ trusted_operation::perform_trusted_operation, Cli, CliResult, CliResultOk, }; -use codec::Decode; use ita_stf::{Index, TrustedCall, TrustedOperation}; use itp_stf_primitives::types::KeyPair; use litentry_primitives::ParentchainBalance as Balance; @@ -62,7 +61,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) } diff --git a/tee-worker/cli/src/trusted_base_cli/commands/unshield_funds.rs b/tee-worker/cli/src/trusted_base_cli/commands/unshield_funds.rs index 81b7c6b263..94fc779493 100644 --- a/tee-worker/cli/src/trusted_base_cli/commands/unshield_funds.rs +++ b/tee-worker/cli/src/trusted_base_cli/commands/unshield_funds.rs @@ -22,11 +22,9 @@ use crate::{ trusted_operation::perform_trusted_operation, Cli, CliResult, CliResultOk, }; -use codec::Decode; use ita_stf::{Index, TrustedCall, TrustedOperation}; use itp_stf_primitives::types::KeyPair; use litentry_primitives::ParentchainBalance as Balance; -use log::*; use sp_core::{crypto::Ss58Codec, Pair}; use std::boxed::Box; @@ -62,6 +60,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)?) } } diff --git a/tee-worker/cli/src/trusted_command_utils.rs b/tee-worker/cli/src/trusted_command_utils.rs index c8edbbdf1a..60a951cd3c 100644 --- a/tee-worker/cli/src/trusted_command_utils.rs +++ b/tee-worker/cli/src/trusted_command_utils.rs @@ -50,18 +50,15 @@ macro_rules! get_layer_two_nonce { let getter = Getter::public(PublicGetter::nonce(Identity::Substrate($signer_pair.public().into()))); - let getter_result = execute_getter_from_cli_args($cli, $trusted_args, &getter); + let getter_result = execute_getter_from_cli_args::($cli, $trusted_args, &getter); let nonce = match getter_result { - Ok(Some(encoded_nonce)) => Index::decode(&mut encoded_nonce.as_slice()).unwrap(), - Ok(None) => Default::default(), + Ok(nonce) => nonce, Err(_) => todo!(), }; - debug!("got system nonce: {:?}", nonce); let pending_tx_count = get_pending_trusted_calls_for($cli, $trusted_args, &$signer_pair.public().into()).len(); let pending_tx_count = Index::try_from(pending_tx_count).unwrap(); - debug!("got pending tx count: {:?}", pending_tx_count); nonce + pending_tx_count }}; } @@ -74,20 +71,7 @@ pub(crate) fn get_balance(cli: &Cli, trusted_args: &TrustedCli, arg_who: &str) - let top: TrustedOperation = TrustedGetter::free_balance(who.public().into()) .sign(&KeyPair::Sr25519(Box::new(who))) .into(); - 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>) -> Option { - 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::(cli, trusted_args, &top).ok() } pub(crate) fn get_keystore_path(trusted_args: &TrustedCli, cli: &Cli) -> PathBuf { diff --git a/tee-worker/cli/src/trusted_operation.rs b/tee-worker/cli/src/trusted_operation.rs index 37175b4b62..577dfddf10 100644 --- a/tee-worker/cli/src/trusted_operation.rs +++ b/tee-worker/cli/src/trusted_operation.rs @@ -17,13 +17,13 @@ use crate::{ command_utils::{get_chain_api, get_pair_from_str, get_shielding_key, get_worker_api_direct}, - error::{Error, Result}, + error::Error, trusted_cli::TrustedCli, Cli, }; use base58::{FromBase58, ToBase58}; use codec::{Decode, Encode}; -use ita_stf::{Getter, TrustedCall, TrustedOperation}; +use ita_stf::{Getter, StfError, TrustedCall, TrustedOperation}; use itc_rpc_client::direct_client::{DirectApi, DirectClient}; use itp_node_api::api_client::{ParentchainApi, TEEREX}; use itp_rpc::{RpcRequest, RpcResponse, RpcReturnValue}; @@ -39,7 +39,8 @@ use my_node_runtime::RuntimeEvent; use pallet_teerex::Event as TeerexEvent; use sp_core::H256; use std::{ - result::Result as StdResult, + fmt::Debug, + result::Result, sync::mpsc::{channel, Receiver}, time::Instant, }; @@ -56,13 +57,13 @@ pub(crate) enum TrustedOperationError { Default { msg: String }, } -pub(crate) type TrustedOpResult = StdResult>, TrustedOperationError>; +pub(crate) type TrustedOpResult = Result; -pub(crate) fn perform_trusted_operation( +pub(crate) fn perform_trusted_operation( cli: &Cli, trusted_args: &TrustedCli, top: &TrustedOperation, -) -> TrustedOpResult { +) -> TrustedOpResult { match top { TrustedOperation::indirect_call(_) => send_indirect_request(cli, trusted_args, top), TrustedOperation::direct_call(_) => send_direct_request(cli, trusted_args, top), @@ -70,12 +71,12 @@ pub(crate) fn perform_trusted_operation( } } -pub(crate) fn perform_direct_operation( +pub(crate) fn perform_direct_operation( cli: &Cli, trusted_args: &TrustedCli, top: &TrustedOperation, key: RequestAesKey, -) -> TrustedOpResult { +) -> TrustedOpResult { match top { TrustedOperation::direct_call(call) => match call.call { TrustedCall::request_vc(..) => send_direct_vc_request(cli, trusted_args, top, key), @@ -86,21 +87,21 @@ pub(crate) fn perform_direct_operation( } } -pub(crate) fn execute_getter_from_cli_args( +pub(crate) fn execute_getter_from_cli_args( cli: &Cli, trusted_args: &TrustedCli, getter: &Getter, -) -> TrustedOpResult { +) -> TrustedOpResult { let shard = read_shard(trusted_args, cli).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( direct_api: &DirectClient, shard: ShardIdentifier, getter: &Getter, -) -> TrustedOpResult { +) -> TrustedOpResult { // Compose jsonrpc call. let data = RsaRequest::new(shard, getter.encode()); let rpc_method = "state_executeGetter".to_owned(); @@ -126,21 +127,32 @@ pub(crate) fn get_state( }) } - let maybe_state = Option::decode(&mut rpc_return_value.value.as_slice()) + let maybe_state: Option> = 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 = T::decode(&mut state.as_slice()).map_err(|err| { + error!("Failed to decode requested type: {:?}", err); + TrustedOperationError::Default { + msg: "Failed at decoding to requested type".to_string(), + } + })?; + Ok(decoded) + }, + None => Err(TrustedOperationError::Default { msg: "Value not present".to_string() }), + } } -fn send_indirect_request( +fn send_indirect_request( cli: &Cli, trusted_args: &TrustedCli, trusted_operation: &TrustedOperation, -) -> TrustedOpResult { +) -> TrustedOpResult { 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(); @@ -204,7 +216,14 @@ 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 = T::decode(&mut block_hash.encode().as_slice()).map_err(|e| { + TrustedOperationError::Default { + msg: format!("Could not decode result value: {:?}", e), + } + })?; + return Ok(value) } } } @@ -216,7 +235,7 @@ fn check_if_received_event_exceeds_expected( block_hash: Hash, confirmed_block_hash: Hash, confirmed_block_number: BlockNumber, -) -> Result<()> { +) -> Result<(), Error> { let block_number = chain_api.get_header(Some(block_hash))?.ok_or(Error::MissingBlock)?.number; info!("Expected block Number: {:?}", block_number); @@ -232,10 +251,7 @@ fn check_if_received_event_exceeds_expected( Ok(()) } -pub fn read_shard( - trusted_args: &TrustedCli, - cli: &Cli, -) -> StdResult { +pub fn read_shard(trusted_args: &TrustedCli, cli: &Cli) -> Result { match &trusted_args.shard { Some(s) => match s.from_base58() { Ok(s) => ShardIdentifier::decode(&mut &s[..]), @@ -262,11 +278,11 @@ pub fn read_shard( } /// sends a rpc watch request to the worker api server -fn send_direct_request( +fn send_direct_request( cli: &Cli, trusted_args: &TrustedCli, operation_call: &TrustedOperation, -) -> TrustedOpResult { +) -> TrustedOpResult { let encryption_key = get_shielding_key(cli).unwrap(); let shard = read_shard(trusted_args, cli).unwrap(); let jsonrpc_call: String = get_json_request(shard, operation_call, encryption_key); @@ -285,7 +301,6 @@ fn send_direct_request( debug!("received response"); let response: RpcResponse = serde_json::from_str(&response).unwrap(); if let Ok(return_value) = RpcReturnValue::from_hex(&response.result) { - debug!("successfully decoded rpc response: {:?}", return_value); match return_value.status { DirectRequestStatus::Error => { debug!("request status is error"); @@ -299,25 +314,41 @@ fn send_direct_request( }, DirectRequestStatus::TrustedOperationStatus(status, top_hash) => { debug!("request status is: {:?}, top_hash: {:?}", status, top_hash); + + if matches!(status, TrustedOperationStatus::Invalid) { + let error = StfError::decode(&mut return_value.value.as_slice()) + .map_err(|e| TrustedOperationError::Default { + msg: format!("Could not decode error value: {:?}", e), + })?; + return Err(TrustedOperationError::Default { + msg: format!( + "[Error] Error occurred while executing trusted call: {:?}", + error + ), + }) + } if let Ok(value) = Hash::decode(&mut return_value.value.as_slice()) { println!("Trusted call {:?} is {:?}", value, status); } - if connection_can_be_closed(status) { + if !return_value.do_watch { 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) } }, DirectRequestStatus::Ok => { debug!("request status is ignored"); direct_api.close().unwrap(); - return Ok(None) + return Err(TrustedOperationError::Default { + msg: "Unexpected status: DirectRequestStatus::Ok".to_string(), + }) }, } - if !return_value.do_watch { - debug!("do watch is false, closing connection"); - direct_api.close().unwrap(); - return Ok(None) - } }; }, Err(e) => { @@ -331,12 +362,12 @@ fn send_direct_request( } } -fn send_direct_vc_request( +fn send_direct_vc_request( cli: &Cli, trusted_args: &TrustedCli, operation_call: &TrustedOperation, key: RequestAesKey, -) -> TrustedOpResult { +) -> TrustedOpResult { let encryption_key = get_shielding_key(cli).unwrap(); let shard = read_shard(trusted_args, cli).unwrap(); let jsonrpc_call: String = get_vc_json_request(shard, operation_call, encryption_key, key); @@ -369,22 +400,19 @@ fn send_direct_vc_request( }, DirectRequestStatus::TrustedOperationStatus(status, top_hash) => { debug!("request status is: {:?}, top_hash: {:?}", status, top_hash); - if connection_can_be_closed(status) { - direct_api.close().unwrap(); - return Ok(None) - } }, DirectRequestStatus::Ok => { debug!("request status is ignored"); 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) }, } - if !return_value.do_watch { - debug!("do watch is false, closing connection"); - direct_api.close().unwrap(); - return Ok(None) - } }; }, Err(e) => { @@ -438,7 +466,7 @@ pub(crate) fn wait_until( match receiver.recv() { Ok(response) => { debug!("received response: {}", response); - let parse_result: StdResult = serde_json::from_str(&response); + let parse_result: Result = serde_json::from_str(&response); if let Ok(response) = parse_result { if let Ok(return_value) = RpcReturnValue::from_hex(&response.result) { debug!("successfully decoded rpc response: {:?}", return_value); @@ -482,13 +510,3 @@ pub(crate) fn wait_until( }; } } - -fn connection_can_be_closed(top_status: TrustedOperationStatus) -> bool { - !matches!( - top_status, - TrustedOperationStatus::Submitted - | TrustedOperationStatus::Future - | TrustedOperationStatus::Ready - | TrustedOperationStatus::Broadcast - ) -} diff --git a/tee-worker/core-primitives/stf-executor/src/getter_executor.rs b/tee-worker/core-primitives/stf-executor/src/getter_executor.rs index 8008e15b71..af81764203 100644 --- a/tee-worker/core-primitives/stf-executor/src/getter_executor.rs +++ b/tee-worker/core-primitives/stf-executor/src/getter_executor.rs @@ -75,7 +75,6 @@ mod tests { use super::*; use codec::{Decode, Encode}; use ita_stf::{PublicGetter, TrustedGetter, TrustedGetterSigned}; - use itp_stf_primitives::types::AccountId; use itp_stf_state_observer::mock::ObserveStateMock; use litentry_primitives::{Address32, Identity, LitentryMultiSignature}; use sp_core::ed25519::Signature; diff --git a/tee-worker/litentry/core/assertion-build/src/holding_time.rs b/tee-worker/litentry/core/assertion-build/src/holding_time.rs index 461b4ec253..bfe249121a 100644 --- a/tee-worker/litentry/core/assertion-build/src/holding_time.rs +++ b/tee-worker/litentry/core/assertion-build/src/holding_time.rs @@ -236,7 +236,6 @@ mod tests { use lc_data_providers::GLOBAL_DATA_PROVIDER_CONFIG; use lc_mock_server::run; use litentry_primitives::{AmountHoldingTimeType, Web3Network}; - use std::sync::Arc; fn init() { let _ = env_logger::builder().is_test(true).try_init(); diff --git a/tee-worker/litentry/core/data-providers/src/achainable.rs b/tee-worker/litentry/core/data-providers/src/achainable.rs index abe36bbefc..e6b795849d 100644 --- a/tee-worker/litentry/core/data-providers/src/achainable.rs +++ b/tee-worker/litentry/core/data-providers/src/achainable.rs @@ -1310,7 +1310,6 @@ mod tests { }; use lc_mock_server::run; use litentry_primitives::Web3Network; - use std::sync::Arc; fn new_achainable_client() -> AchainableClient { let _ = env_logger::builder().is_test(true).try_init(); diff --git a/tee-worker/litentry/core/data-providers/src/discord_litentry.rs b/tee-worker/litentry/core/data-providers/src/discord_litentry.rs index 8e205fb710..3473bbba45 100644 --- a/tee-worker/litentry/core/data-providers/src/discord_litentry.rs +++ b/tee-worker/litentry/core/data-providers/src/discord_litentry.rs @@ -172,7 +172,6 @@ impl DiscordLitentryClient { mod tests { use super::*; use lc_mock_server::run; - use std::sync::Arc; fn init() { let _ = env_logger::builder().is_test(true).try_init(); diff --git a/tee-worker/litentry/core/data-providers/src/twitter_official.rs b/tee-worker/litentry/core/data-providers/src/twitter_official.rs index 012cdf2057..8bbca0219d 100644 --- a/tee-worker/litentry/core/data-providers/src/twitter_official.rs +++ b/tee-worker/litentry/core/data-providers/src/twitter_official.rs @@ -266,7 +266,6 @@ impl TwitterOfficialClient { mod tests { use super::*; use lc_mock_server::run; - use std::sync::Arc; fn init() { let _ = env_logger::builder().is_test(true).try_init(); diff --git a/tee-worker/litentry/primitives/src/aes.rs b/tee-worker/litentry/primitives/src/aes.rs index aa83fed5e8..d63b02432a 100644 --- a/tee-worker/litentry/primitives/src/aes.rs +++ b/tee-worker/litentry/primitives/src/aes.rs @@ -101,17 +101,15 @@ pub fn aes_decrypt(key: &RequestAesKey, data: &mut AesOutput) -> Option> let in_out = data.ciphertext.as_mut(); if let Ok(unbound_key) = UnboundKey::new(&AES_256_GCM, key.as_slice()) { let less_safe_key = LessSafeKey::new(unbound_key); - if (less_safe_key.open_in_place( - Nonce::assume_unique_for_key(data.nonce), - Aad::from(data.aad.clone()), - in_out, - )) - .is_ok() - { - return Some((*in_out).to_vec()) - } + return less_safe_key + .open_in_place( + Nonce::assume_unique_for_key(data.nonce), + Aad::from(data.aad.clone()), + in_out, + ) + .ok() + .map(|data| data.to_vec()) } - None } diff --git a/tee-worker/sidechain/rpc-handler/src/direct_top_pool_api.rs b/tee-worker/sidechain/rpc-handler/src/direct_top_pool_api.rs index 4b6c41ba72..2cb4863ff0 100644 --- a/tee-worker/sidechain/rpc-handler/src/direct_top_pool_api.rs +++ b/tee-worker/sidechain/rpc-handler/src/direct_top_pool_api.rs @@ -101,9 +101,10 @@ where while let Ok(response) = receiver.try_recv() { if let Some(Ok(response)) = response { + // response is already encoded let json_value = RpcReturnValue { do_watch: false, - value: response.encode(), + value: response, status: DirectRequestStatus::Ok, }; return Ok(json!(json_value.to_hex())) diff --git a/tee-worker/ts-tests/integration-tests/common/utils/crypto.ts b/tee-worker/ts-tests/integration-tests/common/utils/crypto.ts index 6fb99bf55c..84b530ed5a 100644 --- a/tee-worker/ts-tests/integration-tests/common/utils/crypto.ts +++ b/tee-worker/ts-tests/integration-tests/common/utils/crypto.ts @@ -43,7 +43,7 @@ export function decryptWithAes(key: HexString, aesOutput: AesOutput, type: 'hex' const authorTag = ciphertext.subarray(ciphertext.length - tagSize); const decipher = crypto.createDecipheriv('aes-256-gcm', secretKey, nonce, { - authTagLength: 16, + authTagLength: tagSize, }); decipher.setAAD(aad); decipher.setAuthTag(authorTag);