Skip to content

Commit

Permalink
feat: add a parachain event for completion of contract sync (#2870)
Browse files Browse the repository at this point in the history
* feat: add callback extrinsic for extrinsic

* fix: add TEE Origin

* fix: add evm_assertions metadata

* fix: fix test error

* refactor: fix clippy
  • Loading branch information
felixfaisal authored Jul 9, 2024
1 parent 467cfbc commit 660f468
Show file tree
Hide file tree
Showing 15 changed files with 202 additions and 30 deletions.
34 changes: 32 additions & 2 deletions pallets/evm-assertions/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ pub mod pallet {

#[derive(Encode, Decode, Clone, Default, Debug, PartialEq, Eq, TypeInfo)]
pub struct Assertion {
byte_code: Vec<u8>,
secrets: Vec<Vec<u8>>,
pub byte_code: Vec<u8>,
pub secrets: Vec<Vec<u8>>,
}

#[pallet::config]
Expand All @@ -58,6 +58,9 @@ pub mod pallet {

/// Only a member of the Developers Collective can deploy the contract
type ContractDevOrigin: EnsureOrigin<Self::RuntimeOrigin>;

/// Only TEE-Workers can call some extrinsics
type TEECallOrigin: EnsureOrigin<Self::RuntimeOrigin>;
}

/// Map for storing assertion smart contract bytecode alongside with additional secrets
Expand All @@ -71,6 +74,8 @@ pub mod pallet {
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
AssertionCreated { id: T::AssertionId, byte_code: Vec<u8>, secrets: Vec<Vec<u8>> },
AssertionStored { id: T::AssertionId },
AssertionVoided { id: T::AssertionId },
}

#[pallet::error]
Expand All @@ -97,5 +102,30 @@ pub mod pallet {
Self::deposit_event(Event::AssertionCreated { id, byte_code, secrets });
Ok(Pays::No.into())
}

/// Only called by the Identity-Worker
#[pallet::call_index(1)]
#[pallet::weight((T::DbWeight::get().read, DispatchClass::Normal, Pays::No))]
pub fn store_assertion(
origin: OriginFor<T>,
id: T::AssertionId,
) -> DispatchResultWithPostInfo {
let _ = T::TEECallOrigin::ensure_origin(origin)?;
Self::deposit_event(Event::AssertionStored { id });
Ok(Pays::No.into())
}

/// Only called by the Identity-Worker
#[pallet::call_index(2)]
#[pallet::weight((T::DbWeight::get().write, DispatchClass::Normal, Pays::No))]
pub fn void_assertion(
origin: OriginFor<T>,
id: T::AssertionId,
) -> DispatchResultWithPostInfo {
let _ = T::TEECallOrigin::ensure_origin(origin)?;
Assertions::<T>::remove(id);
Self::deposit_event(Event::AssertionVoided { id });
Ok(Pays::No.into())
}
}
}
1 change: 1 addition & 0 deletions pallets/evm-assertions/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ impl pallet_evm_assertions::Config for Test {
type RuntimeEvent = RuntimeEvent;
type AssertionId = H160;
type ContractDevOrigin = frame_system::EnsureRoot<Self::AccountId>;
type TEECallOrigin = frame_system::EnsureRoot<Self::AccountId>;
}

parameter_types! {
Expand Down
24 changes: 23 additions & 1 deletion pallets/evm-assertions/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
//
// You should have received a copy of the GNU General Public License
// along with Litentry. If not, see <https://www.gnu.org/licenses/>.
use crate::{mock::*, Error};
use crate::{mock::*, Assertion, Error};
use frame_support::{assert_noop, assert_ok};
use sp_core::H160;

Expand Down Expand Up @@ -63,3 +63,25 @@ fn should_not_create_new_assertion_if_exists() {
);
});
}

#[test]
fn should_remove_assertion_if_failed_to_store() {
new_test_ext().execute_with(|| {
let assertion_id: H160 = H160::from_slice(&[1u8; 20]);
let byte_code = [0u8; 256].to_vec();
let secrets = vec![[2u8; 13].to_vec(), [3u8; 32].to_vec()];

assert_ok!(EvmAssertions::create_assertion(
RuntimeOrigin::root(),
assertion_id,
byte_code.clone(),
secrets.clone()
));

assert_eq!(EvmAssertions::assertions(assertion_id), Some(Assertion { byte_code, secrets }));

assert_ok!(EvmAssertions::void_assertion(RuntimeOrigin::root(), assertion_id,));

assert_eq!(EvmAssertions::assertions(assertion_id), None);
});
}
1 change: 1 addition & 0 deletions runtime/rococo/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1034,6 +1034,7 @@ impl pallet_evm_assertions::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type AssertionId = H160;
type ContractDevOrigin = pallet_collective::EnsureMember<AccountId, DeveloperCommitteeInstance>;
type TEECallOrigin = EnsureEnclaveSigner<Runtime>;
}

// Temporary for bitacross team to test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use itp_stf_primitives::{traits::IndirectExecutor, types::TrustedOperation};
use itp_types::{
parentchain::{
events::ParentchainBlockProcessed, AccountId, FilterEvents, HandleParentchainEvents,
ParentchainEventProcessingError,
ParentchainEventProcessingError, ProcessedEventsArtifacts,
},
RsaRequest, H256,
};
Expand Down Expand Up @@ -212,8 +212,10 @@ where
&self,
executor: &Executor,
events: impl FilterEvents,
) -> Result<Vec<H256>, Error> {
) -> Result<ProcessedEventsArtifacts, Error> {
let mut handled_events: Vec<H256> = Vec::new();
let mut successful_assertion_ids: Vec<H160> = Vec::new();
let mut failed_assertion_ids: Vec<H160> = Vec::new();
if let Ok(events) = events.get_link_identity_events() {
debug!("Handling link_identity events");
events
Expand Down Expand Up @@ -309,6 +311,11 @@ where
let result =
self.store_assertion(executor, event.id, event.byte_code, event.secrets);
handled_events.push(event_hash);
if result.is_ok() {
successful_assertion_ids.push(event.id);
} else {
failed_assertion_ids.push(event.id)
}
result
})
.map_err(|_| ParentchainEventProcessingError::AssertionCreatedFailure)?;
Expand All @@ -323,7 +330,7 @@ where
});
}

Ok(handled_events)
Ok((handled_events, successful_assertion_ids, failed_assertion_ids))
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,8 @@ 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::{FilterEvents, HandleParentchainEvents, ProcessedEventsArtifacts};
use log::*;
use sp_core::H256;
use sp_std::vec::Vec;

pub struct ParentchainEventHandler {}
Expand All @@ -36,8 +35,8 @@ where
&self,
_executor: &Executor,
_events: impl FilterEvents,
) -> Result<Vec<H256>, Error> {
) -> Result<ProcessedEventsArtifacts, Error> {
debug!("not handling any events for target a");
Ok(Vec::new())
Ok((Vec::new(), Vec::new(), Vec::new()))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,8 @@ 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::{FilterEvents, HandleParentchainEvents, ProcessedEventsArtifacts};
use log::*;
use sp_core::H256;
use sp_std::vec::Vec;

pub struct ParentchainEventHandler {}
Expand All @@ -36,8 +35,8 @@ where
&self,
_executor: &Executor,
_events: impl FilterEvents,
) -> Result<Vec<H256>, Error> {
) -> Result<ProcessedEventsArtifacts, Error> {
debug!("not handling any events for target B");
Ok(Vec::new())
Ok((Vec::new(), Vec::new(), Vec::new()))
}
}
8 changes: 6 additions & 2 deletions tee-worker/core-primitives/node-api/metadata/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
#![cfg_attr(not(feature = "std"), no_std)]

use crate::{
error::Result, pallet_balances::BalancesCallIndexes, pallet_imp::IMPCallIndexes,
error::Result, pallet_balances::BalancesCallIndexes,
pallet_evm_assertion::EvmAssertionsCallIndexes, pallet_imp::IMPCallIndexes,
pallet_proxy::ProxyCallIndexes, pallet_system::SystemConstants,
pallet_teebag::TeebagCallIndexes, pallet_timestamp::TimestampCallIndexes,
pallet_utility::UtilityCallIndexes, pallet_vcmp::VCMPCallIndexes,
Expand All @@ -33,6 +34,7 @@ pub use itp_api_client_types::{Metadata, MetadataError};

pub mod error;
pub mod pallet_balances;
pub mod pallet_evm_assertion;
pub mod pallet_imp;
pub mod pallet_proxy;
pub mod pallet_system;
Expand All @@ -55,6 +57,7 @@ pub trait NodeMetadataTrait:
+ ProxyCallIndexes
+ BalancesCallIndexes
+ TimestampCallIndexes
+ EvmAssertionsCallIndexes
{
}

Expand All @@ -66,7 +69,8 @@ impl<
+ UtilityCallIndexes
+ ProxyCallIndexes
+ BalancesCallIndexes
+ TimestampCallIndexes,
+ TimestampCallIndexes
+ EvmAssertionsCallIndexes,
> NodeMetadataTrait for T
{
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
*/

use crate::{
error::Result, pallet_balances::BalancesCallIndexes, pallet_imp::IMPCallIndexes,
error::Result, pallet_balances::BalancesCallIndexes,
pallet_evm_assertion::EvmAssertionsCallIndexes, pallet_imp::IMPCallIndexes,
pallet_proxy::ProxyCallIndexes, pallet_system::SystemConstants,
pallet_teebag::TeebagCallIndexes, pallet_timestamp::TimestampCallIndexes,
pallet_utility::UtilityCallIndexes, pallet_vcmp::VCMPCallIndexes, runtime_call::RuntimeCall,
Expand Down Expand Up @@ -64,6 +65,10 @@ pub struct NodeMetadataMock {
vcmp_request_vc: u8,
vcmp_vc_issued: u8,
vcmp_some_error: u8,
// EVM Assertion
evm_assertions_module: u8,
evm_assertions_store_assertion: u8,
evm_assertions_void_assertion: u8,

utility_module: u8,
utility_batch: u8,
Expand Down Expand Up @@ -116,6 +121,10 @@ impl NodeMetadataMock {
vcmp_vc_issued: 3u8,
vcmp_some_error: 9u8,

evm_assertions_module: 76u8,
evm_assertions_store_assertion: 77u8,
evm_assertions_void_assertion: 78u8,

utility_module: 80u8,
utility_batch: 0u8,
utility_as_derivative: 1u8,
Expand Down Expand Up @@ -291,3 +300,13 @@ impl TimestampCallIndexes for NodeMetadataMock {
Ok([self.timestamp_module, self.timestamp_set])
}
}

impl EvmAssertionsCallIndexes for NodeMetadataMock {
fn store_assertion_call_indexes(&self) -> Result<[u8; 2]> {
Ok([self.evm_assertions_module, self.evm_assertions_store_assertion])
}

fn void_assertion_call_indexes(&self) -> Result<[u8; 2]> {
Ok([self.evm_assertions_module, self.evm_assertions_void_assertion])
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
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::{error::Result, NodeMetadata};

/// Pallet name:
const EVM_ASSERTION: &str = "EvmAssertions";

pub trait EvmAssertionsCallIndexes {
fn store_assertion_call_indexes(&self) -> Result<[u8; 2]>;
fn void_assertion_call_indexes(&self) -> Result<[u8; 2]>;
}

impl EvmAssertionsCallIndexes for NodeMetadata {
fn store_assertion_call_indexes(&self) -> Result<[u8; 2]> {
self.call_indexes(EVM_ASSERTION, "store_assertion")
}

fn void_assertion_call_indexes(&self) -> Result<[u8; 2]> {
self.call_indexes(EVM_ASSERTION, "void_assertion")
}
}
6 changes: 4 additions & 2 deletions tee-worker/core-primitives/types/src/parentchain/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ use events::{
use itp_stf_primitives::traits::{IndirectExecutor, TrustedCallVerification};
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
use sp_core::{bounded::alloc, H256};
use sp_core::{bounded::alloc, H160, H256};
use sp_runtime::{generic::Header as HeaderG, traits::BlakeTwo256, MultiAddress, MultiSignature};

use self::events::ParentchainBlockProcessed;
Expand Down Expand Up @@ -124,6 +124,8 @@ pub enum ExtrinsicStatus {
Failed,
}

pub type ProcessedEventsArtifacts = (Vec<H256>, Vec<H160>, Vec<H160>);

pub trait HandleParentchainEvents<Executor, TCS, Error>
where
Executor: IndirectExecutor<TCS, Error>,
Expand All @@ -133,7 +135,7 @@ where
&self,
executor: &Executor,
events: impl FilterEvents,
) -> Result<Vec<H256>, Error>;
) -> Result<ProcessedEventsArtifacts, Error>;
}

#[derive(Debug)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -184,8 +184,8 @@ impl<
&raw_events,
self.ocall_api.clone(),
) {
Ok(Some(confirm_processed_parentchain_block_call)) => {
calls.push(confirm_processed_parentchain_block_call);
Ok(Some(opaque_calls)) => {
calls.extend(opaque_calls);
},
Ok(None) => trace!("omitting confirmation call to non-integritee parentchain"),
Err(e) => error!("[{:?}] Error executing relevant events: {:?}", id, e),
Expand Down
Loading

0 comments on commit 660f468

Please sign in to comment.