Skip to content

Commit

Permalink
Ab/shield from shard vault (#1497)
Browse files Browse the repository at this point in the history
* now shielding from vault instead of alice. breaks sidechain block production

* fix

* fix unit testing

* fix clippy
  • Loading branch information
brenzi authored Nov 20, 2023
1 parent 4689acf commit 4e4de90
Show file tree
Hide file tree
Showing 16 changed files with 104 additions and 35 deletions.
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
32 changes: 28 additions & 4 deletions core-primitives/stf-executor/src/enclave_signer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,15 @@

use crate::{
error::{Error, Result},
traits::StfEnclaveSigning,
traits::{StfEnclaveSigning, StfShardVaultQuery},
H256,
};
use codec::{Decode, Encode};
use core::{fmt::Debug, marker::PhantomData};
use itp_ocall_api::EnclaveAttestationOCallApi;
use itp_sgx_crypto::{ed25519_derivation::DeriveEd25519, key_repository::AccessKey};
use itp_sgx_externalities::SgxExternalitiesTrait;
use itp_stf_interface::system_pallet::SystemPalletAccountInterface;
use itp_stf_interface::{system_pallet::SystemPalletAccountInterface, ShardVaultQuery};
use itp_stf_primitives::{
traits::TrustedCallSigning,
types::{AccountId, KeyPair},
Expand Down Expand Up @@ -60,7 +60,8 @@ where
StateObserver::StateType: SgxExternalitiesTrait,
ShieldingKeyRepository: AccessKey,
<ShieldingKeyRepository as AccessKey>::KeyType: DeriveEd25519,
Stf: SystemPalletAccountInterface<StateObserver::StateType, AccountId>,
Stf: SystemPalletAccountInterface<StateObserver::StateType, AccountId>
+ ShardVaultQuery<StateObserver::StateType>,
Stf::Index: Into<Index>,
TopPoolAuthor: AuthorApi<H256, H256, TCS, G> + Send + Sync + 'static,
TCS: PartialEq + Encode + Decode + Debug + Send + Sync,
Expand Down Expand Up @@ -105,7 +106,8 @@ where
StateObserver::StateType: SgxExternalitiesTrait,
ShieldingKeyRepository: AccessKey,
<ShieldingKeyRepository as AccessKey>::KeyType: DeriveEd25519,
Stf: SystemPalletAccountInterface<StateObserver::StateType, AccountId>,
Stf: SystemPalletAccountInterface<StateObserver::StateType, AccountId>
+ ShardVaultQuery<StateObserver::StateType>,
Stf::Index: Into<Index>,
TopPoolAuthor: AuthorApi<H256, H256, TCS, G> + Send + Sync + 'static,
TCS: PartialEq + Encode + Decode + Debug + Send + Sync,
Expand Down Expand Up @@ -142,3 +144,25 @@ where
))
}
}

impl<OCallApi, StateObserver, ShieldingKeyRepository, Stf, TopPoolAuthor, TCS, G> StfShardVaultQuery
for StfEnclaveSigner<OCallApi, StateObserver, ShieldingKeyRepository, Stf, TopPoolAuthor, TCS, G>
where
OCallApi: EnclaveAttestationOCallApi,
StateObserver: ObserveState,
StateObserver::StateType: SgxExternalitiesTrait,
ShieldingKeyRepository: AccessKey,
<ShieldingKeyRepository as AccessKey>::KeyType: DeriveEd25519,
Stf: SystemPalletAccountInterface<StateObserver::StateType, AccountId>
+ ShardVaultQuery<StateObserver::StateType>,
Stf::Index: Into<Index>,
TopPoolAuthor: AuthorApi<H256, H256, TCS, G> + Send + Sync + 'static,
TCS: PartialEq + Encode + Decode + Debug + Send + Sync,
G: PartialEq + Encode + Decode + Debug + Send + Sync,
{
fn get_shard_vault(&self, shard: &ShardIdentifier) -> Result<AccountId> {
let vault = self.state_observer.observe_state(shard, move |state| Stf::get_vault(state))?;

vault.ok_or_else(|| Error::Other("shard vault undefined".into()))
}
}
7 changes: 7 additions & 0 deletions core-primitives/stf-executor/src/mocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ use sp_runtime::traits::Header as HeaderTrait;
use std::sync::RwLock;
use std::{boxed::Box, marker::PhantomData, ops::Deref, time::Duration, vec::Vec};

use crate::traits::StfShardVaultQuery;
use itp_stf_primitives::{
traits::{GetterAuthorization, TrustedCallVerification},
types::TrustedOperation,
Expand Down Expand Up @@ -136,6 +137,12 @@ impl<TCS: PartialEq + Encode + Debug> StfEnclaveSigning<TCS> for StfEnclaveSigne
}
}

impl StfShardVaultQuery for StfEnclaveSignerMock {
fn get_shard_vault(&self, _shard: &ShardIdentifier) -> Result<AccountId> {
Err(crate::error::Error::Other("shard vault undefined".into()))
}
}

/// GetState mock
#[derive(Default)]
pub struct GetStateMock<StateType> {
Expand Down
4 changes: 4 additions & 0 deletions core-primitives/stf-executor/src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ where
) -> Result<TCS>;
}

pub trait StfShardVaultQuery {
fn get_shard_vault(&self, shard: &ShardIdentifier) -> Result<AccountId>;
}

/// Proposes a state update to `Externalities`.
pub trait StateUpdateProposer<TCS, G>
where
Expand Down
10 changes: 9 additions & 1 deletion core-primitives/stf-interface/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ use core::fmt::Debug;
use itp_node_api_metadata::NodeMetadataTrait;
use itp_node_api_metadata_provider::AccessNodeMetadata;
use itp_stf_primitives::traits::TrustedCallVerification;
use itp_types::{parentchain::ParentchainId, OpaqueCall};
use itp_types::{
parentchain::{AccountId, ParentchainId},
OpaqueCall,
};

#[cfg(feature = "mocks")]
pub mod mocks;
Expand All @@ -44,6 +47,11 @@ pub trait InitState<State, AccountId> {
fn init_state(enclave_account: AccountId) -> State;
}

/// Interface to query shard vault account for shard
pub trait ShardVaultQuery<S> {
fn get_vault(state: &mut S) -> Option<AccountId>;
}

/// Interface for all functions calls necessary to update an already
/// initialized state.
pub trait UpdateState<State, StateDiff> {
Expand Down
1 change: 1 addition & 0 deletions core-primitives/types/src/parentchain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ where
fn handle_events(
executor: &Executor,
events: impl FilterEvents,
vault_account: &AccountId,
) -> core::result::Result<(), Error>;
}

Expand Down
2 changes: 1 addition & 1 deletion core/parentchain/block-importer/src/block_importer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ impl<
Ok(executed_shielding_calls) => {
calls.push(executed_shielding_calls);
},
Err(_) => error!("[{:?}] Error executing relevant extrinsics", id),
Err(e) => error!("[{:?}] Error executing relevant extrinsics: {:?}", id, e),
};

info!(
Expand Down
2 changes: 2 additions & 0 deletions core/parentchain/indirect-calls-executor/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ itp-ocall-api = { path = "../../../core-primitives/ocall-api", default-features
itp-sgx-crypto = { path = "../../../core-primitives/sgx/crypto", default-features = false }
itp-sgx-runtime-primitives = { path = "../../../core-primitives/sgx-runtime-primitives", default-features = false }
itp-stf-executor = { path = "../../../core-primitives/stf-executor", default-features = false }
itp-stf-interface = { path = "../../../core-primitives/stf-interface", default-features = false }
itp-stf-primitives = { path = "../../../core-primitives/stf-primitives", default-features = false }
itp-test = { path = "../../../core-primitives/test", default-features = false }
itp-top-pool-author = { path = "../../../core-primitives/top-pool-author", default-features = false }
Expand Down Expand Up @@ -59,6 +60,7 @@ std = [
"itp-ocall-api/std",
"itp-sgx-crypto/std",
"itp-stf-executor/std",
"itp-stf-interface/std",
"itp-top-pool-author/std",
"itp-api-client-types/std",
"itp-test/std",
Expand Down
11 changes: 7 additions & 4 deletions core/parentchain/indirect-calls-executor/src/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ use itp_node_api::metadata::{
NodeMetadataTrait,
};
use itp_sgx_crypto::{key_repository::AccessKey, ShieldingCryptoDecrypt, ShieldingCryptoEncrypt};
use itp_stf_executor::traits::StfEnclaveSigning;
use itp_stf_executor::traits::{StfEnclaveSigning, StfShardVaultQuery};
use itp_stf_primitives::{
traits::{IndirectExecutor, TrustedCallSigning, TrustedCallVerification},
types::AccountId,
Expand Down Expand Up @@ -129,7 +129,7 @@ impl<
ShieldingKeyRepository: AccessKey,
<ShieldingKeyRepository as AccessKey>::KeyType: ShieldingCryptoDecrypt<Error = itp_sgx_crypto::Error>
+ ShieldingCryptoEncrypt<Error = itp_sgx_crypto::Error>,
StfEnclaveSigner: StfEnclaveSigning<TCS>,
StfEnclaveSigner: StfEnclaveSigning<TCS> + StfShardVaultQuery,
TopPoolAuthor: AuthorApi<H256, H256, TCS, G> + Send + Sync + 'static,
NodeMetadataProvider: AccessNodeMetadata,
FilterIndirectCalls: FilterIntoDataFrom<NodeMetadataProvider::MetadataType>,
Expand Down Expand Up @@ -166,7 +166,10 @@ impl<
})?;
trace!("xt_statuses:: {:?}", xt_statuses);

ParentchainEventHandler::handle_events(self, events)?;
let shard = self.get_default_shard();
if let Ok(vault) = self.stf_enclave_signer.get_shard_vault(&shard) {
ParentchainEventHandler::handle_events(self, events, &vault)?;
}

// This would be catastrophic but should never happen
if xt_statuses.len() != block.extrinsics().len() {
Expand Down Expand Up @@ -253,7 +256,7 @@ impl<
ShieldingKeyRepository: AccessKey,
<ShieldingKeyRepository as AccessKey>::KeyType: ShieldingCryptoDecrypt<Error = itp_sgx_crypto::Error>
+ ShieldingCryptoEncrypt<Error = itp_sgx_crypto::Error>,
StfEnclaveSigner: StfEnclaveSigning<TCS>,
StfEnclaveSigner: StfEnclaveSigning<TCS> + StfShardVaultQuery,
TopPoolAuthor: AuthorApi<H256, H256, TCS, G> + Send + Sync + 'static,
TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification,
G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync,
Expand Down
1 change: 1 addition & 0 deletions core/parentchain/indirect-calls-executor/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@ where
fn handle_events(
_: &Executor,
_: impl itp_types::parentchain::FilterEvents,
_: &AccountId,
) -> core::result::Result<(), Error> {
Ok(())
}
Expand Down
1 change: 1 addition & 0 deletions enclave-runtime/Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1856,6 +1856,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

0 comments on commit 4e4de90

Please sign in to comment.