Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3221,6 +3221,7 @@ dependencies = [
"itp-sgx-crypto",
"itp-sgx-runtime-primitives",
"itp-stf-executor",
"itp-stf-interface",
"itp-stf-primitives",
"itp-test",
"itp-top-pool-author",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,7 @@ impl FilterEvents for FilterableEvents {
.iter()
.flatten() // flatten filters out the nones
.filter_map(|ev| match ev.as_event::<BalanceTransfer>() {
Ok(maybe_event) => {
if maybe_event.is_none() {
log::warn!("Transfer event does not exist in parentchain metadata");
};
maybe_event
},
Ok(maybe_event) => maybe_event,
Err(e) => {
log::error!("Could not decode event: {:?}", e);
None
Expand Down
25 changes: 12 additions & 13 deletions app-libs/parentchain-interface/src/integritee/event_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,9 @@ use ita_stf::{Getter, TrustedCall, TrustedCallSigned};
use itc_parentchain_indirect_calls_executor::error::Error;
use itp_stf_primitives::{traits::IndirectExecutor, types::TrustedOperation};
use itp_types::parentchain::{AccountId, FilterEvents, HandleParentchainEvents, ParentchainError};
use itp_utils::hex::hex_encode;
use log::*;

type Seed = [u8; 32];

const ALICE_ENCODED: Seed = [
212, 53, 147, 199, 21, 253, 211, 28, 97, 20, 26, 189, 4, 169, 159, 214, 130, 44, 133, 88, 133,
76, 205, 227, 154, 86, 132, 231, 165, 109, 162, 125,
];

const SHIELDING_ACCOUNT: AccountId = AccountId::new(ALICE_ENCODED);

pub struct ParentchainEventHandler {}

impl ParentchainEventHandler {
Expand Down Expand Up @@ -61,15 +53,22 @@ impl<Executor> HandleParentchainEvents<Executor, TrustedCallSigned, Error>
where
Executor: IndirectExecutor<TrustedCallSigned, Error>,
{
fn handle_events(executor: &Executor, events: impl FilterEvents) -> Result<(), Error> {
fn handle_events(
executor: &Executor,
events: impl FilterEvents,
vault_account: &AccountId,
) -> Result<(), Error> {
let filter_events = events.get_transfer_events();

trace!(
"filtering transfer events to shard vault account: {}",
hex_encode(vault_account.encode().as_slice())
);
if let Ok(events) = filter_events {
events
.iter()
.filter(|&event| event.to == SHIELDING_ACCOUNT)
.filter(|&event| event.to == *vault_account)
.try_for_each(|event| {
info!("transfer_event: {}", event);
info!("found transfer_event to vault account: {}", event);
//call = IndirectCall::ShieldFunds(ShieldFundsArgs{ })
Self::shield_funds(executor, &event.from, event.amount)
})
Expand Down
8 changes: 6 additions & 2 deletions app-libs/parentchain-interface/src/target_a/event_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub use ita_sgx_runtime::{Balance, Index};
use ita_stf::TrustedCallSigned;
use itc_parentchain_indirect_calls_executor::error::Error;
use itp_stf_primitives::traits::IndirectExecutor;
use itp_types::parentchain::{FilterEvents, HandleParentchainEvents};
use itp_types::parentchain::{AccountId, FilterEvents, HandleParentchainEvents};
use log::*;

pub struct ParentchainEventHandler {}
Expand All @@ -30,7 +30,11 @@ impl<Executor> HandleParentchainEvents<Executor, TrustedCallSigned, Error>
where
Executor: IndirectExecutor<TrustedCallSigned, Error>,
{
fn handle_events(_executor: &Executor, _events: impl FilterEvents) -> Result<(), Error> {
fn handle_events(
_executor: &Executor,
_events: impl FilterEvents,
_vault_account: &AccountId,
) -> Result<(), Error> {
debug!("not handling any events for target A");
Ok(())
}
Expand Down
8 changes: 6 additions & 2 deletions app-libs/parentchain-interface/src/target_b/event_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub use ita_sgx_runtime::{Balance, Index};
use ita_stf::TrustedCallSigned;
use itc_parentchain_indirect_calls_executor::error::Error;
use itp_stf_primitives::traits::IndirectExecutor;
use itp_types::parentchain::{FilterEvents, HandleParentchainEvents};
use itp_types::parentchain::{AccountId, FilterEvents, HandleParentchainEvents};
use log::*;

pub struct ParentchainEventHandler {}
Expand All @@ -30,7 +30,11 @@ impl<Executor> HandleParentchainEvents<Executor, TrustedCallSigned, Error>
where
Executor: IndirectExecutor<TrustedCallSigned, Error>,
{
fn handle_events(_executor: &Executor, _events: impl FilterEvents) -> Result<(), Error> {
fn handle_events(
_executor: &Executor,
_events: impl FilterEvents,
_vault_account: &AccountId,
) -> Result<(), Error> {
debug!("not handling any events for target B");
Ok(())
}
Expand Down
19 changes: 17 additions & 2 deletions app-libs/stf/src/stf_sgx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,15 @@ use itp_stf_interface::{
parentchain_pallet::ParentchainPalletInterface,
sudo_pallet::SudoPalletInterface,
system_pallet::{SystemPalletAccountInterface, SystemPalletEventInterface},
ExecuteCall, ExecuteGetter, InitState, StateCallInterface, StateGetterInterface, UpdateState,
ExecuteCall, ExecuteGetter, InitState, ShardVaultQuery, StateCallInterface,
StateGetterInterface, UpdateState, SHARD_VAULT_KEY,
};
use itp_stf_primitives::{error::StfError, traits::TrustedCallVerification};
use itp_storage::storage_value_key;
use itp_types::{parentchain::ParentchainId, OpaqueCall};
use itp_types::{
parentchain::{AccountId, ParentchainId},
OpaqueCall,
};
use itp_utils::stringify::account_id_to_string;
use log::*;
use sp_runtime::traits::StaticLookup;
Expand Down Expand Up @@ -160,6 +164,17 @@ where
}
}

impl<TCS, G, State, Runtime> ShardVaultQuery<State> for Stf<TCS, G, State, Runtime>
where
State: SgxExternalitiesTrait + Debug,
{
fn get_vault(state: &mut State) -> Option<AccountId> {
state
.get(SHARD_VAULT_KEY.as_bytes())
.and_then(|v| Decode::decode(&mut v.clone().as_slice()).ok())
}
}

impl<TCS, G, State, Runtime> SudoPalletInterface<State> for Stf<TCS, G, State, Runtime>
where
State: SgxExternalitiesTrait,
Expand Down
2 changes: 2 additions & 0 deletions cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,8 @@ pub enum CliError {
TrustedOp { msg: String },
#[error("EvmReadCommands error: {:?}", msg)]
EvmRead { msg: String },
#[error("worker rpc api error: {:?}", msg)]
WorkerRpcApi { msg: String },
}

pub type CliResult = Result<CliResultOk, CliError>;
Expand Down
67 changes: 67 additions & 0 deletions cli/src/trusted_base_cli/commands/get_shard.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
Copyright 2021 Integritee AG and Supercomputing Systems AG

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/

use crate::{
command_utils::get_worker_api_direct, trusted_cli::TrustedCli, Cli, CliError, CliResult,
CliResultOk,
};
use base58::ToBase58;
use codec::{Decode, Encode};

use itc_rpc_client::direct_client::DirectApi;
use itp_rpc::{RpcRequest, RpcResponse, RpcReturnValue};

use itp_types::DirectRequestStatus;
use itp_utils::FromHexPrefixed;
use log::*;

use sp_core::H256;

#[derive(Parser)]
pub struct GetShardCommand {}

impl GetShardCommand {
pub(crate) fn run(&self, cli: &Cli, _trusted_args: &TrustedCli) -> CliResult {
let direct_api = get_worker_api_direct(cli);
let rpc_method = "author_getShard".to_owned();
let jsonrpc_call: String = RpcRequest::compose_jsonrpc_call(rpc_method, vec![]).unwrap();
let rpc_response_str = direct_api.get(&jsonrpc_call).unwrap();
// Decode RPC response.
let rpc_response: RpcResponse = serde_json::from_str(&rpc_response_str)
.map_err(|err| CliError::WorkerRpcApi { msg: err.to_string() })?;
let rpc_return_value = RpcReturnValue::from_hex(&rpc_response.result)
// Replace with `inspect_err` once it's stable.
.map_err(|err| {
error!("Failed to decode RpcReturnValue: {:?}", err);
CliError::WorkerRpcApi { msg: "failed to decode RpcReturnValue".to_string() }
})?;

if rpc_return_value.status == DirectRequestStatus::Error {
println!("[Error] {}", String::decode(&mut rpc_return_value.value.as_slice()).unwrap());
return Err(CliError::WorkerRpcApi { msg: "rpc error".to_string() })
}

let shard = H256::decode(&mut rpc_return_value.value.as_slice())
// Replace with `inspect_err` once it's stable.
.map_err(|err| {
error!("Failed to decode shard: {:?}", err);
CliError::WorkerRpcApi { msg: err.to_string() }
})?;
println!("{}", shard.encode().to_base58());
Ok(CliResultOk::H256 { hash: shard })
}
}
71 changes: 71 additions & 0 deletions cli/src/trusted_base_cli/commands/get_shard_vault.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
Copyright 2021 Integritee AG and Supercomputing Systems AG

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/

use crate::{
command_utils::get_worker_api_direct, trusted_cli::TrustedCli, Cli, CliError, CliResult,
CliResultOk,
};

use codec::Decode;

use itc_rpc_client::direct_client::DirectApi;
use itp_rpc::{RpcRequest, RpcResponse, RpcReturnValue};

use itp_types::{AccountId, DirectRequestStatus};
use itp_utils::FromHexPrefixed;
use log::*;

use sp_core::crypto::Ss58Codec;

#[derive(Parser)]
pub struct GetShardVaultCommand {}

impl GetShardVaultCommand {
pub(crate) fn run(&self, cli: &Cli, _trusted_args: &TrustedCli) -> CliResult {
let direct_api = get_worker_api_direct(cli);
let rpc_method = "author_getShardVault".to_owned();
let jsonrpc_call: String = RpcRequest::compose_jsonrpc_call(rpc_method, vec![]).unwrap();
let rpc_response_str = direct_api.get(&jsonrpc_call).unwrap();
// Decode RPC response.
let rpc_response: RpcResponse = serde_json::from_str(&rpc_response_str)
.map_err(|err| CliError::WorkerRpcApi { msg: err.to_string() })?;
let rpc_return_value = RpcReturnValue::from_hex(&rpc_response.result)
// Replace with `inspect_err` once it's stable.
.map_err(|err| {
error!("Failed to decode RpcReturnValue: {:?}", err);
CliError::WorkerRpcApi { msg: "failed to decode RpcReturnValue".to_string() }
})?;

if rpc_return_value.status == DirectRequestStatus::Error {
println!("[Error] {}", String::decode(&mut rpc_return_value.value.as_slice()).unwrap());
return Err(CliError::WorkerRpcApi { msg: "rpc error".to_string() })
}

let vault = AccountId::decode(&mut rpc_return_value.value.as_slice())
// Replace with `inspect_err` once it's stable.
.map_err(|err| {
error!("Failed to decode vault account: {:?}", err);
CliError::WorkerRpcApi { msg: err.to_string() }
})?;
let vault_ss58 = vault.to_ss58check();
println!("{}", vault_ss58);
Ok(CliResultOk::PubKeysBase58 {
pubkeys_sr25519: None,
pubkeys_ed25519: Some(vec![vault_ss58]),
})
}
}
2 changes: 2 additions & 0 deletions cli/src/trusted_base_cli/commands/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
pub mod balance;
pub mod get_shard;
pub mod get_shard_vault;
pub mod nonce;
pub mod set_balance;
pub mod transfer;
Expand Down
13 changes: 11 additions & 2 deletions cli/src/trusted_base_cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@

use crate::{
trusted_base_cli::commands::{
balance::BalanceCommand, nonce::NonceCommand, set_balance::SetBalanceCommand,
transfer::TransferCommand, unshield_funds::UnshieldFundsCommand,
balance::BalanceCommand, get_shard::GetShardCommand, get_shard_vault::GetShardVaultCommand,
nonce::NonceCommand, set_balance::SetBalanceCommand, transfer::TransferCommand,
unshield_funds::UnshieldFundsCommand,
},
trusted_cli::TrustedCli,
trusted_command_utils::get_keystore_path,
Expand Down Expand Up @@ -54,6 +55,12 @@ pub enum TrustedBaseCommand {
/// gets the nonce of a given account, taking the pending trusted calls
/// in top pool in consideration
Nonce(NonceCommand),

/// get shard for this worker
GetShard(GetShardCommand),

/// get shard vault for shielding (if defined for this worker)
GetShardVault(GetShardVaultCommand),
}

impl TrustedBaseCommand {
Expand All @@ -66,6 +73,8 @@ impl TrustedBaseCommand {
TrustedBaseCommand::Balance(cmd) => cmd.run(cli, trusted_cli),
TrustedBaseCommand::UnshieldFunds(cmd) => cmd.run(cli, trusted_cli),
TrustedBaseCommand::Nonce(cmd) => cmd.run(cli, trusted_cli),
TrustedBaseCommand::GetShard(cmd) => cmd.run(cli, trusted_cli),
TrustedBaseCommand::GetShardVault(cmd) => cmd.run(cli, trusted_cli),
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion cli/src/trusted_cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use crate::trusted_base_cli::TrustedBaseCommand;
pub struct TrustedCli {
/// targeted worker MRENCLAVE
#[clap(short, long)]
pub(crate) mrenclave: String,
pub(crate) mrenclave: Option<String>,

/// shard identifier
#[clap(short, long)]
Expand Down
7 changes: 6 additions & 1 deletion cli/src/trusted_command_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,12 @@ pub(crate) fn get_keystore_path(trusted_args: &TrustedCli) -> PathBuf {
}

pub(crate) fn get_identifiers(trusted_args: &TrustedCli) -> ([u8; 32], ShardIdentifier) {
let mrenclave = mrenclave_from_base58(&trusted_args.mrenclave);
let mrenclave = mrenclave_from_base58(
trusted_args
.mrenclave
.as_ref()
.expect("argument '--mrenclave' must be provided for this command"),
);
let shard = match &trusted_args.shard {
Some(val) =>
ShardIdentifier::from_slice(&val.from_base58().expect("shard has to be base58 encoded")),
Expand Down
7 changes: 6 additions & 1 deletion cli/src/trusted_operation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,12 @@ pub fn read_shard(trusted_args: &TrustedCli) -> StdResult<ShardIdentifier, codec
Ok(s) => ShardIdentifier::decode(&mut &s[..]),
_ => panic!("shard argument must be base58 encoded"),
},
None => match trusted_args.mrenclave.from_base58() {
None => match trusted_args
.mrenclave
.as_ref()
.expect("at least argument '--mrenclave' must be provided for this command")
.from_base58()
{
Ok(s) => ShardIdentifier::decode(&mut &s[..]),
_ => panic!("mrenclave argument must be base58 encoded"),
},
Expand Down
Loading