From b4c24cf8fb1a764b7f54c2cdd8fd6411fb61b142 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Fri, 4 Oct 2024 14:06:26 +0000 Subject: [PATCH 01/39] adding omni-account primitives --- common/primitives/core/Cargo.toml | 2 +- common/primitives/core/src/lib.rs | 3 ++ common/primitives/core/src/omni_account.rs | 47 ++++++++++++++++++++++ 3 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 common/primitives/core/src/omni_account.rs diff --git a/common/primitives/core/Cargo.toml b/common/primitives/core/Cargo.toml index 385072795f..b500fd95fd 100644 --- a/common/primitives/core/Cargo.toml +++ b/common/primitives/core/Cargo.toml @@ -13,7 +13,7 @@ strum_macros = { version = "0.26", default-features = false } frame-support = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } pallet-evm = { git = "https://github.com/paritytech/frontier", branch = "polkadot-v1.1.0", default-features = false } scale-info = { version = "2.11", default-features = false, features = ["derive"] } -sp-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } +sp-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false, features = ["full_crypto"] } sp-io = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } diff --git a/common/primitives/core/src/lib.rs b/common/primitives/core/src/lib.rs index acea7e721f..3c9973769c 100644 --- a/common/primitives/core/src/lib.rs +++ b/common/primitives/core/src/lib.rs @@ -29,6 +29,9 @@ pub use assertion::Assertion; pub mod identity; pub use identity::*; +pub mod omni_account; +pub use omni_account::*; + extern crate alloc; extern crate core; use alloc::{format, str, str::FromStr, string::String, vec, vec::Vec}; diff --git a/common/primitives/core/src/omni_account.rs b/common/primitives/core/src/omni_account.rs new file mode 100644 index 0000000000..e39c9b7873 --- /dev/null +++ b/common/primitives/core/src/omni_account.rs @@ -0,0 +1,47 @@ +use crate::{Hash, Identity, Vec}; +use parity_scale_codec::{Decode, Encode}; +use scale_info::TypeInfo; +use sp_core::blake2_256; +use sp_runtime::{BoundedVec, RuntimeDebug}; + +#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, Eq, RuntimeDebug)] +pub struct IDGraphMember { + pub id: MemberIdentity, + pub hash: Hash, +} + +#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, Eq, RuntimeDebug)] +pub enum MemberIdentity { + Public(Identity), + Private(Vec), +} + +impl MemberIdentity { + pub fn is_public(&self) -> bool { + matches!(self, Self::Public(..)) + } +} + +impl From for MemberIdentity { + fn from(identity: Identity) -> Self { + Self::Public(identity) + } +} + +pub trait IDGraphHash { + fn hash(&self) -> Hash; +} + +impl IDGraphHash for BoundedVec { + fn hash(&self) -> Hash { + let members_hashes: Vec = self.iter().map(|member| member.hash).collect(); + Hash::from(blake2_256(&members_hashes.encode())) + } +} + +impl IDGraphHash for Vec { + fn hash(&self) -> Hash { + let members_hashes: Vec = self.iter().map(|member| member.hash).collect(); + Hash::from(blake2_256(&members_hashes.encode())) + } +} From 26ecf054ddc0ce931fcdc692d6a5713f9b5c2144 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Fri, 4 Oct 2024 14:08:39 +0000 Subject: [PATCH 02/39] updating omni-account pallet to use new primitives --- parachain/Cargo.lock | 1 - parachain/pallets/omni-account/Cargo.toml | 3 +-- parachain/pallets/omni-account/src/lib.rs | 22 ++------------------- parachain/pallets/omni-account/src/tests.rs | 1 + 4 files changed, 4 insertions(+), 23 deletions(-) diff --git a/parachain/Cargo.lock b/parachain/Cargo.lock index 76618ffb6a..7763e5b6d8 100644 --- a/parachain/Cargo.lock +++ b/parachain/Cargo.lock @@ -7820,7 +7820,6 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", - "sp-core-hashing", "sp-io", "sp-keyring", "sp-runtime", diff --git a/parachain/pallets/omni-account/Cargo.toml b/parachain/pallets/omni-account/Cargo.toml index 451bb0ee7e..0bc68fa68e 100644 --- a/parachain/pallets/omni-account/Cargo.toml +++ b/parachain/pallets/omni-account/Cargo.toml @@ -12,8 +12,7 @@ scale-info = { workspace = true } frame-support = { workspace = true } frame-system = { workspace = true } -sp-core = { workspace = true } -sp-core-hashing = { workspace = true } +sp-core = { workspace = true, features = ["full_crypto"] } sp-io = { workspace = true } sp-runtime = { workspace = true } sp-std = { workspace = true } diff --git a/parachain/pallets/omni-account/src/lib.rs b/parachain/pallets/omni-account/src/lib.rs index 228a5a1d53..d01b97aea5 100644 --- a/parachain/pallets/omni-account/src/lib.rs +++ b/parachain/pallets/omni-account/src/lib.rs @@ -5,37 +5,19 @@ mod mock; #[cfg(test)] mod tests; -pub use core_primitives::{Identity, MemberIdentity}; +pub use core_primitives::{IDGraphHash, IDGraphMember, Identity, MemberIdentity}; pub use frame_system::pallet_prelude::BlockNumberFor; pub use pallet::*; use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; use sp_core::H256; -use sp_core_hashing::blake2_256; use sp_std::vec::Vec; -#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, Eq, RuntimeDebug)] -pub struct IDGraphMember { - pub id: MemberIdentity, - pub hash: H256, -} - pub trait AccountIdConverter { fn convert(identity: &Identity) -> Option; } -pub trait IDGraphHash { - fn graph_hash(&self) -> H256; -} - -impl IDGraphHash for BoundedVec { - fn graph_hash(&self) -> H256 { - let id_graph_members_hashes: Vec = self.iter().map(|member| member.hash).collect(); - H256::from(blake2_256(&id_graph_members_hashes.encode())) - } -} - #[frame_support::pallet] pub mod pallet { use super::*; @@ -139,7 +121,7 @@ pub mod pallet { .map_err(|_| Error::::IDGraphLenLimitReached)?; LinkedIdentityHashes::::insert(identity_hash, ()); - IDGraphHashes::::insert(who_account_id.clone(), id_graph.graph_hash()); + IDGraphHashes::::insert(who_account_id.clone(), id_graph.hash()); IDGraphs::::insert(who_account_id.clone(), id_graph); Self::deposit_event(Event::IdentityLinked { diff --git a/parachain/pallets/omni-account/src/tests.rs b/parachain/pallets/omni-account/src/tests.rs index 4b8b0c795e..ecb408f2dd 100644 --- a/parachain/pallets/omni-account/src/tests.rs +++ b/parachain/pallets/omni-account/src/tests.rs @@ -1,6 +1,7 @@ use crate::{mock::*, IDGraphs, LinkedIdentityHashes, *}; use core_primitives::Identity; use frame_support::{assert_noop, assert_ok}; +use sp_core::blake2_256; use sp_runtime::traits::BadOrigin; use sp_std::vec; From 471a3ea3719ed009dd4fee44acf0c795ae95828d Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Fri, 4 Oct 2024 14:08:53 +0000 Subject: [PATCH 03/39] cleaning up identity primitives --- common/primitives/core/src/identity.rs | 20 +------------------- 1 file changed, 1 insertion(+), 19 deletions(-) diff --git a/common/primitives/core/src/identity.rs b/common/primitives/core/src/identity.rs index 3e5980a826..80da5bacfc 100644 --- a/common/primitives/core/src/identity.rs +++ b/common/primitives/core/src/identity.rs @@ -35,7 +35,7 @@ use sp_core::{ use sp_io::hashing::blake2_256; use sp_runtime::{ traits::{BlakeTwo256, ConstU32}, - BoundedVec, RuntimeDebug, + BoundedVec, }; use strum_macros::EnumIter; @@ -529,24 +529,6 @@ impl From<[u8; 33]> for Identity { } } -#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, Eq, RuntimeDebug)] -pub enum MemberIdentity { - Public(Identity), - Private(Vec), -} - -impl MemberIdentity { - pub fn is_public(&self) -> bool { - matches!(self, Self::Public(..)) - } -} - -impl From for MemberIdentity { - fn from(identity: Identity) -> Self { - Self::Public(identity) - } -} - #[cfg(test)] mod tests { use super::*; From 19db50c647dea58ac0ca9fe7c0053d3afb07c5d0 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Fri, 4 Oct 2024 14:16:18 +0000 Subject: [PATCH 04/39] adding new primitives for storage keys --- tee-worker/Cargo.lock | 1 + .../common/core-primitives/storage/Cargo.toml | 2 ++ .../common/core-primitives/storage/src/keys.rs | 16 ++++++++++++++-- .../common/core-primitives/storage/src/lib.rs | 2 ++ tee-worker/identity/enclave-runtime/Cargo.lock | 1 + 5 files changed, 20 insertions(+), 2 deletions(-) diff --git a/tee-worker/Cargo.lock b/tee-worker/Cargo.lock index 3598a69365..8acf531237 100644 --- a/tee-worker/Cargo.lock +++ b/tee-worker/Cargo.lock @@ -4389,6 +4389,7 @@ dependencies = [ "frame-support", "hash-db 0.15.2", "itp-types", + "litentry-hex-utils 0.1.0", "parity-scale-codec", "sgx_tstd", "sp-core", diff --git a/tee-worker/common/core-primitives/storage/Cargo.toml b/tee-worker/common/core-primitives/storage/Cargo.toml index d3c48d6e05..72659e1b52 100644 --- a/tee-worker/common/core-primitives/storage/Cargo.toml +++ b/tee-worker/common/core-primitives/storage/Cargo.toml @@ -23,6 +23,8 @@ sp-trie = { workspace = true } itp-types = { workspace = true } +litentry-hex-utils = { workspace = true } + [dev-dependencies] sp-state-machine = { workspace = true, features = ["std"] } diff --git a/tee-worker/common/core-primitives/storage/src/keys.rs b/tee-worker/common/core-primitives/storage/src/keys.rs index 43de4f667e..5771bd8c03 100644 --- a/tee-worker/common/core-primitives/storage/src/keys.rs +++ b/tee-worker/common/core-primitives/storage/src/keys.rs @@ -15,9 +15,11 @@ */ -use codec::Encode; +use alloc::{string::String, vec::Vec}; +use codec::{Decode, Encode}; use frame_metadata::v14::StorageHasher; -use sp_std::vec::Vec; +use frame_support::{Blake2_128Concat, ReversibleStorageHasher}; +use litentry_hex_utils::decode_hex; pub fn storage_value_key(module_prefix: &str, storage_prefix: &str) -> Vec { let mut bytes = sp_core::twox_128(module_prefix.as_bytes()).to_vec(); @@ -37,6 +39,16 @@ pub fn storage_map_key( bytes } +pub fn extract_blake2_128concat_key(raw_storage_key: &[u8]) -> Option { + let mut raw_key = Blake2_128Concat::reverse(raw_storage_key); + K::decode(&mut raw_key).ok() +} + +pub fn decode_storage_key(raw_key: Vec) -> Option> { + let hex_key = String::decode(&mut raw_key.as_slice()).unwrap_or_default(); + decode_hex(hex_key).ok() +} + pub fn storage_double_map_key( module_prefix: &str, storage_prefix: &str, diff --git a/tee-worker/common/core-primitives/storage/src/lib.rs b/tee-worker/common/core-primitives/storage/src/lib.rs index 3a3b6f2a6d..77a087e23e 100644 --- a/tee-worker/common/core-primitives/storage/src/lib.rs +++ b/tee-worker/common/core-primitives/storage/src/lib.rs @@ -23,6 +23,8 @@ compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the sam #[cfg(all(not(feature = "std"), feature = "sgx"))] extern crate sgx_tstd as std; +extern crate alloc; + pub use error::Error; pub use frame_metadata::v14::StorageHasher; pub use keys::*; diff --git a/tee-worker/identity/enclave-runtime/Cargo.lock b/tee-worker/identity/enclave-runtime/Cargo.lock index 34b8f1631d..2d26517e8f 100644 --- a/tee-worker/identity/enclave-runtime/Cargo.lock +++ b/tee-worker/identity/enclave-runtime/Cargo.lock @@ -2667,6 +2667,7 @@ dependencies = [ "frame-support", "hash-db 0.15.2", "itp-types", + "litentry-hex-utils 0.1.0", "parity-scale-codec", "sgx_tstd", "sp-core", From 49f8ef25672aff6bcce3f6a7978796861697dc78 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Fri, 4 Oct 2024 14:31:23 +0000 Subject: [PATCH 05/39] adding omni-account litentry core --- tee-worker/Cargo.lock | 16 +++++ tee-worker/Cargo.toml | 2 + .../litentry/core/omni-account/Cargo.toml | 33 +++++++++++ .../litentry/core/omni-account/src/lib.rs | 58 +++++++++++++++++++ 4 files changed, 109 insertions(+) create mode 100644 tee-worker/identity/litentry/core/omni-account/Cargo.toml create mode 100644 tee-worker/identity/litentry/core/omni-account/src/lib.rs diff --git a/tee-worker/Cargo.lock b/tee-worker/Cargo.lock index 8acf531237..59fe636326 100644 --- a/tee-worker/Cargo.lock +++ b/tee-worker/Cargo.lock @@ -5256,6 +5256,22 @@ dependencies = [ "warp", ] +[[package]] +name = "lc-omni-account" +version = "0.1.0" +dependencies = [ + "frame-support", + "itp-ocall-api", + "itp-storage", + "itp-types", + "lazy_static", + "litentry-primitives", + "log 0.4.20", + "parity-scale-codec", + "sgx_tstd", + "sp-core", +] + [[package]] name = "lc-parachain-extrinsic-task-receiver" version = "0.1.0" diff --git a/tee-worker/Cargo.toml b/tee-worker/Cargo.toml index 07f58471b0..f84eb26837 100644 --- a/tee-worker/Cargo.toml +++ b/tee-worker/Cargo.toml @@ -54,6 +54,7 @@ members = [ "identity/litentry/core/vc-task/sender", "identity/litentry/core/vc-task/receiver", "identity/litentry/core/identity-verification", + "identity/litentry/core/omni-account", "identity/litentry/core/stf-task/sender", "identity/litentry/core/stf-task/receiver", "identity/litentry/core/service", @@ -300,6 +301,7 @@ lc-stf-task-sender = { path = "identity/litentry/core/stf-task/sender", default- lc-stf-task-receiver = { path = "identity/litentry/core/stf-task/receiver", default-features = false } lc-vc-task-sender = { path = "identity/litentry/core/vc-task/sender", default-features = false } lc-vc-task-receiver = { path = "identity/litentry/core/vc-task/receiver", default-features = false } +lc-omni-account = { path = "identity/app-libs/omni-account", default-features = false } itc-peer-top-broadcaster = { path = "identity/core/peer-top-broadcaster", default-features = false } itc-rpc-server = { path = "identity/core/rpc-server", default-features = false } diff --git a/tee-worker/identity/litentry/core/omni-account/Cargo.toml b/tee-worker/identity/litentry/core/omni-account/Cargo.toml new file mode 100644 index 0000000000..e854396582 --- /dev/null +++ b/tee-worker/identity/litentry/core/omni-account/Cargo.toml @@ -0,0 +1,33 @@ +[package] +authors = ["Trust Computing GmbH "] +edition = "2021" +name = "lc-omni-account" +version = "0.1.0" + +[dependencies] +litentry-primitives = { workspace = true } + +itp-ocall-api = { workspace = true } +itp-storage = { workspace = true } +itp-types = { workspace = true } + +sp-core = { workspace = true, features = ["full_crypto"] } +codec = { package = "parity-scale-codec", workspace = true } +frame-support = { workspace = true } +lazy_static = { workspace = true } +log = { workspace = true } + +sgx_tstd = { workspace = true, features = ["net", "thread"], optional = true } + +[features] +default = ["std"] +std = [ + "litentry-primitives/std", + "frame-support/std", + "itp-storage/std", + "itp-types/std", +] +sgx = [ + "litentry-primitives/sgx", + "sgx_tstd", +] diff --git a/tee-worker/identity/litentry/core/omni-account/src/lib.rs b/tee-worker/identity/litentry/core/omni-account/src/lib.rs new file mode 100644 index 0000000000..12ed2ee445 --- /dev/null +++ b/tee-worker/identity/litentry/core/omni-account/src/lib.rs @@ -0,0 +1,58 @@ +// Copyright 2020-2024 Trust Computing GmbH. +// This file is part of Litentry. +// +// Litentry is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// Litentry is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Litentry. If not, see . + +#![cfg_attr(not(feature = "std"), no_std)] + +pub extern crate alloc; + +#[cfg(all(not(feature = "std"), feature = "sgx"))] +extern crate sgx_tstd as std; + +#[cfg(all(feature = "std", feature = "sgx"))] +compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the same time"); + +use alloc::vec::Vec; +use codec::Decode; +use itp_types::parentchain::{AccountId, Hash, Header, ParentchainId}; +use litentry_primitives::Identity; + +pub type IDGraph = Vec; + +#[derive(Debug)] +pub enum Error { + LockPoisoning, + NotFound, + OCallApiError(&'static str), +} + +// TODO: get this from core_primitives after the release-v0.9.19 branch has been updated +#[derive(Debug, Clone, Decode)] +pub enum MemberIdentity { + Public(Identity), + Private(Vec), +} + +#[derive(Debug, Clone, Decode)] +pub struct IDGraphMember { + pub id: MemberIdentity, + pub hash: Hash, +} + +#[derive(Debug, Clone)] +pub struct OmniAccountIDGraph { + pub graph: IDGraph, + pub hash: Hash, +} From de03b6d1c6130b369019122a8a21a90711959c77 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Fri, 4 Oct 2024 14:32:51 +0000 Subject: [PATCH 06/39] preparing IDGraphs in-memory store --- .../core/omni-account/src/id_graphs_store.rs | 63 +++++++++++++++++++ .../litentry/core/omni-account/src/lib.rs | 4 ++ 2 files changed, 67 insertions(+) create mode 100644 tee-worker/identity/litentry/core/omni-account/src/id_graphs_store.rs diff --git a/tee-worker/identity/litentry/core/omni-account/src/id_graphs_store.rs b/tee-worker/identity/litentry/core/omni-account/src/id_graphs_store.rs new file mode 100644 index 0000000000..8ec2e41578 --- /dev/null +++ b/tee-worker/identity/litentry/core/omni-account/src/id_graphs_store.rs @@ -0,0 +1,63 @@ +use crate::{Error, Identity, OmniAccountIDGraph}; +use alloc::collections::btree_map::BTreeMap; +use lazy_static::lazy_static; + +#[cfg(feature = "std")] +use std::sync::RwLock; +#[cfg(feature = "sgx")] +use std::sync::SgxRwLock as RwLock; + +lazy_static! { + static ref ID_GRAPHS: RwLock> = + RwLock::new(BTreeMap::new()); +} + +pub struct IDGraphsStore; + +impl IDGraphsStore { + pub fn get(&self, owner: Identity) -> Result { + let id_graph = ID_GRAPHS + .read() + .map_err(|_| { + log::error!("[IDGraphsInMemoryRepository] Lock poisoning"); + Error::LockPoisoning + })? + .get(&owner) + .cloned(); + + id_graph.ok_or(Error::NotFound) + } + + pub fn insert(&self, owner: Identity, id_graph: OmniAccountIDGraph) -> Result<(), Error> { + ID_GRAPHS + .write() + .map_err(|_| { + log::error!("[IDGraphsInMemoryRepository] Lock poisoning"); + Error::LockPoisoning + })? + .insert(owner, id_graph); + + Ok(()) + } + + pub fn remove(&self, owner: Identity) -> Result<(), Error> { + ID_GRAPHS + .write() + .map_err(|_| { + log::error!("[IDGraphsInMemoryRepository] Lock poisoning"); + Error::LockPoisoning + })? + .remove(&owner); + + Ok(()) + } + + pub fn load(&self, id_graphs: BTreeMap) -> Result<(), Error> { + *ID_GRAPHS.write().map_err(|_| { + log::error!("[IDGraphsInMemoryRepository] Lock poisoning"); + Error::LockPoisoning + })? = id_graphs; + + Ok(()) + } +} diff --git a/tee-worker/identity/litentry/core/omni-account/src/lib.rs b/tee-worker/identity/litentry/core/omni-account/src/lib.rs index 12ed2ee445..ead7e73e48 100644 --- a/tee-worker/identity/litentry/core/omni-account/src/lib.rs +++ b/tee-worker/identity/litentry/core/omni-account/src/lib.rs @@ -24,6 +24,10 @@ extern crate sgx_tstd as std; #[cfg(all(feature = "std", feature = "sgx"))] compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the same time"); + +mod id_graphs_store; +pub use id_graphs_store::IDGraphsStore; + use alloc::vec::Vec; use codec::Decode; use itp_types::parentchain::{AccountId, Hash, Header, ParentchainId}; From 288cad787f8fc1463124a8a566fe76a5789846f5 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Fri, 4 Oct 2024 14:38:36 +0000 Subject: [PATCH 07/39] adding initial implementation of id_graphs_repository --- .../src/id_graphs_repository/mod.rs | 90 +++++++++++++++++++ .../litentry/core/omni-account/src/lib.rs | 2 + 2 files changed, 92 insertions(+) create mode 100644 tee-worker/identity/litentry/core/omni-account/src/id_graphs_repository/mod.rs diff --git a/tee-worker/identity/litentry/core/omni-account/src/id_graphs_repository/mod.rs b/tee-worker/identity/litentry/core/omni-account/src/id_graphs_repository/mod.rs new file mode 100644 index 0000000000..d053590ade --- /dev/null +++ b/tee-worker/identity/litentry/core/omni-account/src/id_graphs_repository/mod.rs @@ -0,0 +1,90 @@ +use crate::{ + AccountId, Error, Hash, Header, IDGraph, IDGraphMember, Identity, OmniAccountIDGraph, + ParentchainId, +}; +use alloc::{collections::btree_map::BTreeMap, vec::Vec}; +use codec::Encode; +use frame_support::storage::storage_prefix; +use itp_ocall_api::EnclaveOnChainOCallApi; +use itp_storage::{ + decode_storage_key, extract_blake2_128concat_key, storage_map_key, StorageHasher, +}; +use sp_core::blake2_256; + +type IDGraphs = BTreeMap; + +// TODO: get this from core_primitives after the release-v0.9.19 branch has been updated +pub trait IDGraphHash { + fn hash(&self) -> Hash; +} +impl IDGraphHash for Vec { + fn hash(&self) -> Hash { + let members_hashes: Vec = self.iter().map(|member| member.hash).collect(); + Hash::from(blake2_256(&members_hashes.encode())) + } +} + +pub trait GetIDGraphsRepository { + fn get(&self, block_header: Header, owner: Identity) -> Result; + fn get_all(&self, block_header: Header) -> Result; +} + +pub struct IDGraphsRepository { + ocall_api: OCallApi, +} + +impl IDGraphsRepository { + pub fn new(ocall_api: OCallApi) -> Self { + Self { ocall_api } + } +} + +impl GetIDGraphsRepository for IDGraphsRepository { + fn get(&self, block_header: Header, owner: Identity) -> Result { + let storage_key = + storage_map_key("OmniAccount", "IDGraphs", &owner, &StorageHasher::Blake2_128Concat); + let storage_entry = self + .ocall_api + .get_storage_verified(storage_key, &block_header, &ParentchainId::Litentry) + .map_err(|_| Error::OCallApiError("Failed to get storage"))?; + let id_graph: Vec = + storage_entry.value().to_owned().ok_or(Error::NotFound)?; + let id_graph_hash = id_graph.hash(); + + Ok(OmniAccountIDGraph { graph: id_graph, hash: id_graph_hash }) + } + + fn get_all(&self, block_header: Header) -> Result { + let id_graphs_key_prefix = storage_prefix(b"OmniAccount", b"IDGraphs"); + let id_graphs_storage_keys_response = self + .ocall_api + .get_storage_keys(id_graphs_key_prefix.into()) + .map_err(|_| Error::OCallApiError("Failed to get storage keys"))?; + let id_graphs_storage_keys = id_graphs_storage_keys_response + .into_iter() + .filter_map(decode_storage_key) + .collect::>>(); + let id_graphs: IDGraphs = self + .ocall_api + .get_multiple_storages_verified( + id_graphs_storage_keys, + &block_header, + &ParentchainId::Litentry, + ) + .map_err(|_| Error::OCallApiError("Failed to get multiple storages"))? + .into_iter() + .filter_map(|entry| { + // TODO: double check this + let storage_key = decode_storage_key(entry.key)?; + let account_id: AccountId = extract_blake2_128concat_key(&storage_key)?; + let id_graph: IDGraph = entry.value?; + let id_graph_hash = id_graph.hash(); + let omni_account_id_graph = + OmniAccountIDGraph { graph: id_graph, hash: id_graph_hash }; + Some((account_id, omni_account_id_graph)) + }) + .collect(); + + Ok(id_graphs) + } +} diff --git a/tee-worker/identity/litentry/core/omni-account/src/lib.rs b/tee-worker/identity/litentry/core/omni-account/src/lib.rs index ead7e73e48..457fa2ec0b 100644 --- a/tee-worker/identity/litentry/core/omni-account/src/lib.rs +++ b/tee-worker/identity/litentry/core/omni-account/src/lib.rs @@ -24,6 +24,8 @@ extern crate sgx_tstd as std; #[cfg(all(feature = "std", feature = "sgx"))] compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the same time"); +mod id_graphs_repository; +pub use id_graphs_repository::*; mod id_graphs_store; pub use id_graphs_store::IDGraphsStore; From 8f7f119adc682f2cc7bff10c140ead221eff8cf2 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Fri, 4 Oct 2024 15:11:36 +0000 Subject: [PATCH 08/39] fixing fmt --- tee-worker/identity/litentry/core/omni-account/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tee-worker/identity/litentry/core/omni-account/Cargo.toml b/tee-worker/identity/litentry/core/omni-account/Cargo.toml index e854396582..b8211e06f1 100644 --- a/tee-worker/identity/litentry/core/omni-account/Cargo.toml +++ b/tee-worker/identity/litentry/core/omni-account/Cargo.toml @@ -11,11 +11,11 @@ itp-ocall-api = { workspace = true } itp-storage = { workspace = true } itp-types = { workspace = true } -sp-core = { workspace = true, features = ["full_crypto"] } codec = { package = "parity-scale-codec", workspace = true } frame-support = { workspace = true } lazy_static = { workspace = true } log = { workspace = true } +sp-core = { workspace = true, features = ["full_crypto"] } sgx_tstd = { workspace = true, features = ["net", "thread"], optional = true } From 71590248e4bf8b6bd69c2898f048110ddc3a6371 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Sat, 5 Oct 2024 11:44:01 +0000 Subject: [PATCH 09/39] feat: refactor IDGraphs handling and repository methods --- .../src/id_graphs_repository/mod.rs | 22 ++++++++++++------- .../core/omni-account/src/id_graphs_store.rs | 14 +++++------- .../litentry/core/omni-account/src/lib.rs | 4 +++- 3 files changed, 23 insertions(+), 17 deletions(-) diff --git a/tee-worker/identity/litentry/core/omni-account/src/id_graphs_repository/mod.rs b/tee-worker/identity/litentry/core/omni-account/src/id_graphs_repository/mod.rs index d053590ade..94d1e1b86b 100644 --- a/tee-worker/identity/litentry/core/omni-account/src/id_graphs_repository/mod.rs +++ b/tee-worker/identity/litentry/core/omni-account/src/id_graphs_repository/mod.rs @@ -1,8 +1,8 @@ use crate::{ - AccountId, Error, Hash, Header, IDGraph, IDGraphMember, Identity, OmniAccountIDGraph, + AccountId, Error, Hash, Header, IDGraph, IDGraphMember, IDGraphs, Identity, OmniAccountIDGraph, ParentchainId, }; -use alloc::{collections::btree_map::BTreeMap, vec::Vec}; +use alloc::vec::Vec; use codec::Encode; use frame_support::storage::storage_prefix; use itp_ocall_api::EnclaveOnChainOCallApi; @@ -11,8 +11,6 @@ use itp_storage::{ }; use sp_core::blake2_256; -type IDGraphs = BTreeMap; - // TODO: get this from core_primitives after the release-v0.9.19 branch has been updated pub trait IDGraphHash { fn hash(&self) -> Hash; @@ -25,8 +23,12 @@ impl IDGraphHash for Vec { } pub trait GetIDGraphsRepository { - fn get(&self, block_header: Header, owner: Identity) -> Result; - fn get_all(&self, block_header: Header) -> Result; + fn get_by_owner( + &self, + block_header: Header, + owner: Identity, + ) -> Result; + fn get(&self, block_header: Header) -> Result; } pub struct IDGraphsRepository { @@ -40,7 +42,11 @@ impl IDGraphsRepository { } impl GetIDGraphsRepository for IDGraphsRepository { - fn get(&self, block_header: Header, owner: Identity) -> Result { + fn get_by_owner( + &self, + block_header: Header, + owner: Identity, + ) -> Result { let storage_key = storage_map_key("OmniAccount", "IDGraphs", &owner, &StorageHasher::Blake2_128Concat); let storage_entry = self @@ -54,7 +60,7 @@ impl GetIDGraphsRepository for IDGraphsReposit Ok(OmniAccountIDGraph { graph: id_graph, hash: id_graph_hash }) } - fn get_all(&self, block_header: Header) -> Result { + fn get(&self, block_header: Header) -> Result { let id_graphs_key_prefix = storage_prefix(b"OmniAccount", b"IDGraphs"); let id_graphs_storage_keys_response = self .ocall_api diff --git a/tee-worker/identity/litentry/core/omni-account/src/id_graphs_store.rs b/tee-worker/identity/litentry/core/omni-account/src/id_graphs_store.rs index 8ec2e41578..3767c3a91a 100644 --- a/tee-worker/identity/litentry/core/omni-account/src/id_graphs_store.rs +++ b/tee-worker/identity/litentry/core/omni-account/src/id_graphs_store.rs @@ -1,5 +1,4 @@ -use crate::{Error, Identity, OmniAccountIDGraph}; -use alloc::collections::btree_map::BTreeMap; +use crate::{AccountId, BTreeMap, Error, IDGraphs, OmniAccountIDGraph}; use lazy_static::lazy_static; #[cfg(feature = "std")] @@ -8,14 +7,13 @@ use std::sync::RwLock; use std::sync::SgxRwLock as RwLock; lazy_static! { - static ref ID_GRAPHS: RwLock> = - RwLock::new(BTreeMap::new()); + static ref ID_GRAPHS: RwLock = RwLock::new(BTreeMap::new()); } pub struct IDGraphsStore; impl IDGraphsStore { - pub fn get(&self, owner: Identity) -> Result { + pub fn get(&self, owner: AccountId) -> Result { let id_graph = ID_GRAPHS .read() .map_err(|_| { @@ -28,7 +26,7 @@ impl IDGraphsStore { id_graph.ok_or(Error::NotFound) } - pub fn insert(&self, owner: Identity, id_graph: OmniAccountIDGraph) -> Result<(), Error> { + pub fn insert(&self, owner: AccountId, id_graph: OmniAccountIDGraph) -> Result<(), Error> { ID_GRAPHS .write() .map_err(|_| { @@ -40,7 +38,7 @@ impl IDGraphsStore { Ok(()) } - pub fn remove(&self, owner: Identity) -> Result<(), Error> { + pub fn remove(&self, owner: AccountId) -> Result<(), Error> { ID_GRAPHS .write() .map_err(|_| { @@ -52,7 +50,7 @@ impl IDGraphsStore { Ok(()) } - pub fn load(&self, id_graphs: BTreeMap) -> Result<(), Error> { + pub fn load(&self, id_graphs: IDGraphs) -> Result<(), Error> { *ID_GRAPHS.write().map_err(|_| { log::error!("[IDGraphsInMemoryRepository] Lock poisoning"); Error::LockPoisoning diff --git a/tee-worker/identity/litentry/core/omni-account/src/lib.rs b/tee-worker/identity/litentry/core/omni-account/src/lib.rs index 457fa2ec0b..733ef7219f 100644 --- a/tee-worker/identity/litentry/core/omni-account/src/lib.rs +++ b/tee-worker/identity/litentry/core/omni-account/src/lib.rs @@ -30,11 +30,13 @@ pub use id_graphs_repository::*; mod id_graphs_store; pub use id_graphs_store::IDGraphsStore; -use alloc::vec::Vec; +use alloc::{collections::btree_map::BTreeMap, vec::Vec}; use codec::Decode; use itp_types::parentchain::{AccountId, Hash, Header, ParentchainId}; use litentry_primitives::Identity; +pub type IDGraphs = BTreeMap; + pub type IDGraph = Vec; #[derive(Debug)] From 9fba6d1a380b63d6634e4a3bcb038706795ebc1a Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Mon, 7 Oct 2024 16:43:28 +0000 Subject: [PATCH 10/39] injecting OnChainEncryptionKeyRepository and parentchain header to the stf executor --- tee-worker/Cargo.lock | 6 + .../core-primitives/ocall-api/Cargo.toml | 1 + .../core-primitives/ocall-api/src/lib.rs | 3 + .../core-primitives/ocall-api/src/mock.rs | 100 +++++++++ .../core-primitives/stf-interface/Cargo.toml | 14 +- .../core-primitives/stf-interface/src/lib.rs | 29 ++- .../stf-interface/src/mocks.rs | 33 ++- .../common/core-primitives/test/Cargo.toml | 2 +- .../core-primitives/test/src/mock/stf_mock.rs | 44 +++- tee-worker/identity/app-libs/stf/Cargo.toml | 4 + .../identity/app-libs/stf/src/stf_sgx.rs | 45 +++- .../identity/app-libs/stf/src/trusted_call.rs | 18 +- .../core-primitives/stf-executor/Cargo.toml | 1 + .../stf-executor/src/executor.rs | 199 ++++++++++++++---- .../stf-executor/src/executor_tests.rs | 15 +- .../core-primitives/stf-executor/src/mocks.rs | 6 +- .../stf-executor/src/traits.rs | 6 +- .../offchain-worker-executor/src/executor.rs | 14 +- .../identity/enclave-runtime/Cargo.lock | 6 + .../src/initialization/global_components.rs | 8 +- .../parentchain/integritee_parachain.rs | 14 +- .../parentchain/integritee_solochain.rs | 14 +- .../parentchain/target_a_parachain.rs | 18 +- .../parentchain/target_a_solochain.rs | 18 +- .../parentchain/target_b_parachain.rs | 18 +- .../parentchain/target_b_solochain.rs | 18 +- .../src/test/enclave_signer_tests.rs | 23 +- .../src/test/fixtures/test_setup.rs | 18 +- .../enclave-runtime/src/test/mocks/types.rs | 7 +- .../src/test/sidechain_aura_tests.rs | 1 + .../src/test/sidechain_event_tests.rs | 1 + .../enclave-runtime/src/test/tests_main.rs | 41 +++- .../enclave-runtime/src/top_pool_execution.rs | 2 +- .../consensus/aura/src/proposer_factory.rs | 25 ++- .../consensus/aura/src/slot_proposer.rs | 24 ++- 35 files changed, 659 insertions(+), 137 deletions(-) create mode 100644 tee-worker/common/core-primitives/ocall-api/src/mock.rs diff --git a/tee-worker/Cargo.lock b/tee-worker/Cargo.lock index 59fe636326..111a01a78a 100644 --- a/tee-worker/Cargo.lock +++ b/tee-worker/Cargo.lock @@ -3394,6 +3394,8 @@ dependencies = [ "itp-node-api", "itp-node-api-metadata", "itp-node-api-metadata-provider", + "itp-ocall-api", + "itp-sgx-crypto", "itp-sgx-externalities", "itp-stf-interface", "itp-stf-primitives", @@ -3604,6 +3606,7 @@ dependencies = [ "itp-ocall-api", "itp-sgx-crypto", "itp-sgx-externalities", + "itp-sgx-io", "itp-stf-interface", "itp-stf-primitives", "itp-stf-state-handler", @@ -4326,9 +4329,12 @@ version = "0.8.0" dependencies = [ "itp-node-api-metadata", "itp-node-api-metadata-provider", + "itp-ocall-api", + "itp-sgx-crypto", "itp-stf-primitives", "itp-types", "parity-scale-codec", + "sp-runtime", ] [[package]] diff --git a/tee-worker/common/core-primitives/ocall-api/Cargo.toml b/tee-worker/common/core-primitives/ocall-api/Cargo.toml index 655bedbc9a..e678a539bc 100644 --- a/tee-worker/common/core-primitives/ocall-api/Cargo.toml +++ b/tee-worker/common/core-primitives/ocall-api/Cargo.toml @@ -27,3 +27,4 @@ std = [ "itp-storage/std", "itp-types/std", ] +mocks = [] diff --git a/tee-worker/common/core-primitives/ocall-api/src/lib.rs b/tee-worker/common/core-primitives/ocall-api/src/lib.rs index d4a0a9b944..e3168a19cf 100644 --- a/tee-worker/common/core-primitives/ocall-api/src/lib.rs +++ b/tee-worker/common/core-primitives/ocall-api/src/lib.rs @@ -17,6 +17,9 @@ #![cfg_attr(not(feature = "std"), no_std)] +#[cfg(feature = "mocks")] +pub mod mock; + pub extern crate alloc; use alloc::{string::String, vec::Vec}; diff --git a/tee-worker/common/core-primitives/ocall-api/src/mock.rs b/tee-worker/common/core-primitives/ocall-api/src/mock.rs new file mode 100644 index 0000000000..c746865a93 --- /dev/null +++ b/tee-worker/common/core-primitives/ocall-api/src/mock.rs @@ -0,0 +1,100 @@ +/* + Copyright 2021 Integritee AG and Supercomputing Systems AG + Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. + + 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::{EnclaveOnChainOCallApi, Error as OCallApiError}; +use alloc::{collections::BTreeMap, string::String, vec::Vec}; +use codec::{Decode, Encode}; +use core::fmt::Debug; +use itp_storage::Error::StorageValueUnavailable; +use itp_types::{ + parentchain::ParentchainId, storage::StorageEntryVerified, AccountId, BlockHash, + ShardIdentifier, WorkerRequest, WorkerResponse, WorkerType, +}; +use sgx_types::*; +use sp_core::H256; +use sp_runtime::{traits::Header as HeaderTrait, OpaqueExtrinsic}; +use sp_std::prelude::*; + +#[derive(Default, Clone, Debug)] +pub struct OnchainMock { + inner: BTreeMap, Vec>, +} + +impl OnchainMock { + pub fn get_at_header>( + &self, + header: &Header, + key: &[u8], + ) -> Option<&Vec> { + let key_with_header = (header, key).encode(); + self.inner.get(&key_with_header) + } +} + +impl EnclaveOnChainOCallApi for OnchainMock { + fn send_to_parentchain( + &self, + _extrinsics: Vec, + _: &ParentchainId, + _: bool, + ) -> SgxResult<()> { + Ok(()) + } + + fn worker_request( + &self, + _req: Vec, + _: &ParentchainId, + ) -> SgxResult>> { + Ok(Vec::new()) + } + + fn get_storage_verified, V: Decode>( + &self, + storage_hash: Vec, + header: &Header, + parentchain_id: &ParentchainId, + ) -> Result, OCallApiError> { + self.get_multiple_storages_verified(vec![storage_hash], header, parentchain_id)? + .into_iter() + .next() + .ok_or_else(|| OCallApiError::Storage(StorageValueUnavailable)) + } + + fn get_multiple_storages_verified, V: Decode>( + &self, + storage_hashes: Vec>, + header: &Header, + _: &ParentchainId, + ) -> Result>, OCallApiError> { + let mut entries = Vec::with_capacity(storage_hashes.len()); + for hash in storage_hashes.into_iter() { + let value = self + .get_at_header(header, &hash) + .map(|val| Decode::decode(&mut val.as_slice())) + .transpose() + .map_err(OCallApiError::Codec)?; + + entries.push(StorageEntryVerified::new(hash, value)) + } + Ok(entries) + } + + fn get_storage_keys(&self, _key_prefix: Vec) -> Result>, OCallApiError> { + Ok(Default::default()) + } +} diff --git a/tee-worker/common/core-primitives/stf-interface/Cargo.toml b/tee-worker/common/core-primitives/stf-interface/Cargo.toml index a46749521d..bd3cddfbf5 100644 --- a/tee-worker/common/core-primitives/stf-interface/Cargo.toml +++ b/tee-worker/common/core-primitives/stf-interface/Cargo.toml @@ -11,6 +11,10 @@ itp-node-api-metadata = { workspace = true, features = ["mocks"] } itp-node-api-metadata-provider = { workspace = true } itp-stf-primitives = { workspace = true } itp-types = { workspace = true } +itp-ocall-api = { workspace = true } +itp-sgx-crypto = { workspace = true } + +sp-runtime = { workspace = true } [features] default = ["std"] @@ -19,6 +23,12 @@ std = [ "itp-node-api-metadata-provider/std", "itp-stf-primitives/std", "itp-types/std", + "itp-sgx-crypto/std", +] +sgx = [ + "itp-sgx-crypto/sgx", +] +mocks = [ + "itp-ocall-api/mocks", + "itp-sgx-crypto/mocks", ] -sgx = [] -mocks = [] diff --git a/tee-worker/common/core-primitives/stf-interface/src/lib.rs b/tee-worker/common/core-primitives/stf-interface/src/lib.rs index 179adf6504..40692790c7 100644 --- a/tee-worker/common/core-primitives/stf-interface/src/lib.rs +++ b/tee-worker/common/core-primitives/stf-interface/src/lib.rs @@ -27,11 +27,15 @@ use codec::{Decode, Encode}; use core::fmt::Debug; use itp_node_api_metadata::NodeMetadataTrait; use itp_node_api_metadata_provider::AccessNodeMetadata; +use itp_ocall_api::EnclaveOnChainOCallApi; +// TODO: use Aes256 when available +use itp_sgx_crypto::{aes::Aes, key_repository::AccessKey}; use itp_stf_primitives::traits::TrustedCallVerification; use itp_types::{ parentchain::{BlockHash, BlockNumber, ParentchainCall, ParentchainId}, ShardIdentifier, H256, }; +use sp_runtime::traits::Header as HeaderTrait; #[cfg(feature = "mocks")] pub mod mocks; @@ -62,11 +66,20 @@ pub trait UpdateState { } /// Interface to execute state mutating calls on a state. -pub trait StateCallInterface -where +pub trait StateCallInterface< + TCS, + State, + NodeMetadataRepository, + OCallApi, + PH, + OnChainEncryptionKeyRepository, +> where NodeMetadataRepository: AccessNodeMetadata, NodeMetadataRepository::MetadataType: NodeMetadataTrait, TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, + OCallApi: EnclaveOnChainOCallApi, + PH: HeaderTrait, + OnChainEncryptionKeyRepository: AccessKey, { type Error: Encode; type Result: StfExecutionResult; @@ -77,6 +90,7 @@ where /// 1. add a parameter to pass the top_hash around /// 2. returns the encoded rpc response value field that should be passed /// back to the requester when the call is triggered synchronously + // #[allow(clippy::too_many_arguments)] fn execute_call( state: &mut State, shard: &ShardIdentifier, @@ -84,6 +98,9 @@ where top_hash: H256, calls: &mut Vec, node_metadata_repo: Arc, + ocall_api: Arc, + parentchain_header: &PH, + on_chain_encryption_key_repo: Arc, ) -> Result; } @@ -94,10 +111,13 @@ pub trait StateGetterInterface { } /// Trait used to abstract the call execution. -pub trait ExecuteCall +pub trait ExecuteCall where NodeMetadataRepository: AccessNodeMetadata, NodeMetadataRepository::MetadataType: NodeMetadataTrait, + OCallApi: EnclaveOnChainOCallApi, + PH: HeaderTrait, + OnChainEncryptionKeyRepository: AccessKey, { type Error: Encode; type Result: StfExecutionResult; @@ -112,6 +132,9 @@ where top_hash: H256, calls: &mut Vec, node_metadata_repo: Arc, + ocall_api: Arc, + parentchain_header: &PH, + on_chain_encryption_key_repo: Arc, ) -> Result; /// Get storages hashes that should be updated for a specific call. diff --git a/tee-worker/common/core-primitives/stf-interface/src/mocks.rs b/tee-worker/common/core-primitives/stf-interface/src/mocks.rs index 44bda77d36..1e2810b5a1 100644 --- a/tee-worker/common/core-primitives/stf-interface/src/mocks.rs +++ b/tee-worker/common/core-primitives/stf-interface/src/mocks.rs @@ -27,11 +27,18 @@ use codec::{Decode, Encode}; use core::{fmt::Debug, marker::PhantomData}; use itp_node_api_metadata::metadata_mocks::NodeMetadataMock; use itp_node_api_metadata_provider::NodeMetadataRepository; +use itp_ocall_api::mock::OnchainMock; +// TODO: use Aes256 when available +use itp_sgx_crypto::{mocks::KeyRepositoryMock, Aes}; use itp_stf_primitives::traits::TrustedCallVerification; use itp_types::{ parentchain::{ParentchainCall, ParentchainId}, AccountId, Index, ShardIdentifier, H256, }; +use sp_runtime::{generic::Header, traits::BlakeTwo256}; + +type BlockNumber = u32; +pub type ParentchainHeader = Header; #[derive(Default)] pub struct StateInterfaceMock { @@ -56,8 +63,15 @@ impl UpdateState for StateInterfaceMock StateCallInterface> - for StateInterfaceMock +impl + StateCallInterface< + TCS, + State, + NodeMetadataRepository, + OnchainMock, + ParentchainHeader, + KeyRepositoryMock, + > for StateInterfaceMock where TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, { @@ -71,6 +85,9 @@ where _top_hash: H256, _calls: &mut Vec, _node_metadata_repo: Arc>, + _ocall_api: Arc, + _parentchain_header: &ParentchainHeader, + _key_repository: Arc>, ) -> Result { unimplemented!() } @@ -100,7 +117,14 @@ impl SystemPalletAccountInterface pub struct CallExecutorMock; -impl ExecuteCall> for CallExecutorMock { +impl + ExecuteCall< + NodeMetadataRepository, + OnchainMock, + ParentchainHeader, + KeyRepositoryMock, + > for CallExecutorMock +{ type Error = String; type Result = (); @@ -110,6 +134,9 @@ impl ExecuteCall> for CallExecutorMock _top_hash: H256, _calls: &mut Vec, _node_metadata_repo: Arc>, + _ocall_api: Arc, + _parentchain_header: &ParentchainHeader, + _key_repository: Arc>, ) -> Result<(), Self::Error> { unimplemented!() } diff --git a/tee-worker/common/core-primitives/test/Cargo.toml b/tee-worker/common/core-primitives/test/Cargo.toml index a738a22b15..acfa543348 100644 --- a/tee-worker/common/core-primitives/test/Cargo.toml +++ b/tee-worker/common/core-primitives/test/Cargo.toml @@ -20,7 +20,7 @@ sp-std = { workspace = true } itp-node-api = { workspace = true } itp-node-api-metadata-provider = { workspace = true } itp-ocall-api = { workspace = true } -itp-sgx-crypto = { workspace = true } +itp-sgx-crypto = { workspace = true, features = ["mocks"] } itp-sgx-externalities = { workspace = true } itp-stf-interface = { workspace = true } itp-stf-primitives = { workspace = true } diff --git a/tee-worker/common/core-primitives/test/src/mock/stf_mock.rs b/tee-worker/common/core-primitives/test/src/mock/stf_mock.rs index 40b9225761..9d5c29022d 100644 --- a/tee-worker/common/core-primitives/test/src/mock/stf_mock.rs +++ b/tee-worker/common/core-primitives/test/src/mock/stf_mock.rs @@ -14,11 +14,14 @@ limitations under the License. */ +use super::onchain_mock::OnchainMock; use alloc::{boxed::Box, sync::Arc}; use codec::{Decode, Encode}; use core::fmt::Debug; use itp_node_api::metadata::metadata_mocks::NodeMetadataMock; use itp_node_api_metadata_provider::NodeMetadataRepository; +// TODO: use Aes256 when available +use itp_sgx_crypto::{mocks::KeyRepositoryMock, Aes}; use itp_sgx_externalities::{SgxExternalities, SgxExternalitiesDiffType, SgxExternalitiesTrait}; use itp_stf_interface::{ runtime_upgrade::RuntimeUpgradeInterface, ExecuteCall, InitState, StateCallInterface, @@ -37,14 +40,18 @@ use itp_types::{ use litentry_primitives::{Identity, LitentryMultiSignature}; use log::*; use sp_core::{sr25519, Pair}; -use sp_runtime::transaction_validity::{ - TransactionValidityError, UnknownTransaction, ValidTransaction, +use sp_runtime::{ + generic::Header, + traits::BlakeTwo256, + transaction_validity::{TransactionValidityError, UnknownTransaction, ValidTransaction}, }; use sp_std::{vec, vec::Vec}; use std::{thread::sleep, time::Duration}; // a few dummy types type NodeMetadataRepositoryMock = NodeMetadataRepository; +type BlockNumber = u32; +pub type ParentchainHeader = Header; #[derive(Debug, PartialEq, Eq, Encode)] pub enum StfMockError { @@ -63,8 +70,15 @@ impl UpdateState for StfMock { } } -impl StateCallInterface - for StfMock +impl + StateCallInterface< + TrustedCallSignedMock, + SgxExternalities, + NodeMetadataRepositoryMock, + OnchainMock, + ParentchainHeader, + KeyRepositoryMock, + > for StfMock { type Error = StfMockError; type Result = (); @@ -76,8 +90,21 @@ impl StateCallInterface, node_metadata_repo: Arc, + ocall_api: Arc, + parentchain_header: &ParentchainHeader, + key_repository: Arc>, ) -> Result<(), Self::Error> { - state.execute_with(|| call.execute(shard, top_hash, calls, node_metadata_repo)) + state.execute_with(|| { + call.execute( + shard, + top_hash, + calls, + node_metadata_repo, + ocall_api, + parentchain_header, + key_repository, + ) + }) } } @@ -170,7 +197,9 @@ impl Default for TrustedCallSignedMock { } } -impl ExecuteCall for TrustedCallSignedMock { +impl ExecuteCall> + for TrustedCallSignedMock +{ type Error = StfMockError; type Result = (); @@ -180,6 +209,9 @@ impl ExecuteCall for TrustedCallSignedMock { _top_hash: H256, _calls: &mut Vec, _node_metadata_repo: Arc, + _ocall_api: Arc, + _parentchain_header: &ParentchainHeader, + _on_chain_encryption_key_repo: Arc>, ) -> Result<(), Self::Error> { match self.call { TrustedCallMock::noop(_) => Ok(()), diff --git a/tee-worker/identity/app-libs/stf/Cargo.toml b/tee-worker/identity/app-libs/stf/Cargo.toml index 02b7067a1b..5926804de1 100644 --- a/tee-worker/identity/app-libs/stf/Cargo.toml +++ b/tee-worker/identity/app-libs/stf/Cargo.toml @@ -23,6 +23,8 @@ itp-stf-primitives = { workspace = true } itp-storage = { workspace = true } itp-types = { workspace = true } itp-utils = { workspace = true } +itp-ocall-api = { workspace = true } +itp-sgx-crypto = { workspace = true } ita-sgx-runtime = { package = "id-ita-sgx-runtime", path = "../sgx-runtime", default-features = false } sp-io = { path = "../../../common/core-primitives/substrate-sgx/sp-io", default-features = false, features = ["disable_oom", "disable_panic_handler", "disable_allocator"] } @@ -57,6 +59,7 @@ sgx = [ "litentry-primitives/sgx", "lc-stf-task-sender/sgx", "itp-node-api-metadata-provider/sgx", + "itp-sgx-crypto/sgx", ] std = [ "codec/std", @@ -80,6 +83,7 @@ std = [ "litentry-primitives/std", "lc-stf-task-sender/std", "itp-node-api-metadata-provider/std", + "itp-sgx-crypto/std", ] test = [] development = [ diff --git a/tee-worker/identity/app-libs/stf/src/stf_sgx.rs b/tee-worker/identity/app-libs/stf/src/stf_sgx.rs index 7e99061839..c6436bffb9 100644 --- a/tee-worker/identity/app-libs/stf/src/stf_sgx.rs +++ b/tee-worker/identity/app-libs/stf/src/stf_sgx.rs @@ -28,6 +28,9 @@ use ita_sgx_runtime::{ Executive, ParentchainInstanceLitentry, ParentchainInstanceTargetA, ParentchainInstanceTargetB, }; use itp_node_api::metadata::{provider::AccessNodeMetadata, NodeMetadataTrait}; +use itp_ocall_api::EnclaveOnChainOCallApi; +// TODO: use Aes256 when available +use itp_sgx_crypto::{aes::Aes, key_repository::AccessKey}; use itp_sgx_externalities::SgxExternalitiesTrait; use itp_stf_interface::{ parentchain_pallet::ParentchainPalletInstancesInterface, @@ -47,7 +50,7 @@ use itp_types::{ }; use itp_utils::stringify::account_id_to_string; use log::*; -use sp_runtime::traits::StaticLookup; +use sp_runtime::traits::{Header as HeaderTrait, StaticLookup}; impl InitState for Stf where @@ -134,11 +137,27 @@ where } } -impl - StateCallInterface for Stf +impl< + TCS, + G, + State, + Runtime, + NodeMetadataRepository, + OCallApi, + PH, + OnChainEncryptionKeyRepository, + > + StateCallInterface< + TCS, + State, + NodeMetadataRepository, + OCallApi, + PH, + OnChainEncryptionKeyRepository, + > for Stf where TCS: PartialEq - + ExecuteCall + + ExecuteCall + Encode + Decode + Debug @@ -149,6 +168,9 @@ where State: SgxExternalitiesTrait + Debug, NodeMetadataRepository: AccessNodeMetadata, NodeMetadataRepository::MetadataType: NodeMetadataTrait, + OCallApi: EnclaveOnChainOCallApi, + PH: HeaderTrait, + OnChainEncryptionKeyRepository: AccessKey, { type Error = TCS::Error; type Result = TCS::Result; @@ -160,8 +182,21 @@ where top_hash: H256, calls: &mut Vec, node_metadata_repo: Arc, + ocall_api: Arc, + parentchain_header: &PH, + on_chain_encryption_key_repo: Arc, ) -> Result { - state.execute_with(|| call.execute(shard, top_hash, calls, node_metadata_repo)) + state.execute_with(|| { + call.execute( + shard, + top_hash, + calls, + node_metadata_repo, + ocall_api, + parentchain_header, + on_chain_encryption_key_repo, + ) + }) } } diff --git a/tee-worker/identity/app-libs/stf/src/trusted_call.rs b/tee-worker/identity/app-libs/stf/src/trusted_call.rs index 0fc8c6f11c..525b3ef521 100644 --- a/tee-worker/identity/app-libs/stf/src/trusted_call.rs +++ b/tee-worker/identity/app-libs/stf/src/trusted_call.rs @@ -39,6 +39,9 @@ pub use ita_sgx_runtime::{ }; use itp_node_api::metadata::{provider::AccessNodeMetadata, NodeMetadataTrait}; use itp_node_api_metadata::{pallet_imp::IMPCallIndexes, pallet_vcmp::VCMPCallIndexes}; +use itp_ocall_api::EnclaveOnChainOCallApi; +// TODO: use Aes256 when available +use itp_sgx_crypto::{key_repository::AccessKey, Aes}; use itp_stf_interface::ExecuteCall; use itp_stf_primitives::{ error::StfError, @@ -62,7 +65,10 @@ use sp_core::{ ed25519, }; use sp_io::hashing::blake2_256; -use sp_runtime::{traits::ConstU32, BoundedVec, MultiAddress}; +use sp_runtime::{ + traits::{ConstU32, Header as HeaderTrait}, + BoundedVec, MultiAddress, +}; pub type IMTCall = ita_sgx_runtime::IdentityManagementCall; pub type IMT = ita_sgx_runtime::pallet_identity_management_tee::Pallet; @@ -339,10 +345,15 @@ impl TrustedCallVerification for TrustedCallSigned { } } -impl ExecuteCall for TrustedCallSigned +impl + ExecuteCall + for TrustedCallSigned where NodeMetadataRepository: AccessNodeMetadata, NodeMetadataRepository::MetadataType: NodeMetadataTrait, + OCallApi: EnclaveOnChainOCallApi, + PH: HeaderTrait, + OnChainEncryptionKeyRepository: AccessKey, { type Error = StfError; type Result = TrustedCallResult; @@ -386,6 +397,9 @@ where top_hash: H256, calls: &mut Vec, node_metadata_repo: Arc, + _ocall_api: Arc, + _parentchain_header: &PH, + _on_chain_encryption_key_repo: Arc, ) -> Result { let sender = self.call.sender_identity().clone(); let account_id: AccountId = sender.to_account_id().ok_or(Self::Error::InvalidAccount)?; diff --git a/tee-worker/identity/core-primitives/stf-executor/Cargo.toml b/tee-worker/identity/core-primitives/stf-executor/Cargo.toml index e77096f69e..21d5576966 100644 --- a/tee-worker/identity/core-primitives/stf-executor/Cargo.toml +++ b/tee-worker/identity/core-primitives/stf-executor/Cargo.toml @@ -21,6 +21,7 @@ itp-stf-state-handler = { workspace = true } itp-stf-state-observer = { workspace = true } itp-time-utils = { workspace = true } itp-types = { workspace = true } +itp-sgx-io = { workspace = true } itp-top-pool-author = { package = "id-itp-top-pool-author", path = "../top-pool-author", default-features = false } diff --git a/tee-worker/identity/core-primitives/stf-executor/src/executor.rs b/tee-worker/identity/core-primitives/stf-executor/src/executor.rs index ffc6d92fce..3e98e06214 100644 --- a/tee-worker/identity/core-primitives/stf-executor/src/executor.rs +++ b/tee-worker/identity/core-primitives/stf-executor/src/executor.rs @@ -24,6 +24,8 @@ use codec::{Decode, Encode}; use itp_enclave_metrics::EnclaveMetric; use itp_node_api::metadata::{provider::AccessNodeMetadata, NodeMetadataTrait}; use itp_ocall_api::{EnclaveAttestationOCallApi, EnclaveMetricsOCallApi, EnclaveOnChainOCallApi}; +// TODO: use Aes256 when available +use itp_sgx_crypto::{aes::Aes, key_repository::AccessKey}; use itp_sgx_externalities::{SgxExternalitiesTrait, StateHash}; use itp_stf_interface::{ parentchain_pallet::ParentchainPalletInstancesInterface, @@ -36,7 +38,7 @@ use itp_stf_primitives::{ use itp_stf_state_handler::{handle_state::HandleState, query_shard_state::QueryShardState}; use itp_time_utils::duration_now; use itp_types::{ - parentchain::{Header as ParentchainHeader, ParentchainCall, ParentchainId}, + parentchain::{ParentchainCall, ParentchainId}, storage::StorageEntryVerified, H256, }; @@ -47,20 +49,46 @@ use std::{ time::Duration, vec, vec::Vec, }; -pub struct StfExecutor -where +pub struct StfExecutor< + OCallApi, + StateHandler, + NodeMetadataRepository, + Stf, + TCS, + G, + PH, + OnChainEncryptionKeyRepository, +> where TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, { ocall_api: Arc, state_handler: Arc, node_metadata_repo: Arc, - _phantom: PhantomData<(Stf, TCS, G)>, + on_chain_encryption_key_repository: Arc, + _phantom: PhantomData<(Stf, TCS, G, PH)>, } -impl - StfExecutor -where +impl< + OCallApi, + StateHandler, + NodeMetadataRepository, + Stf, + TCS, + G, + PH, + OnChainEncryptionKeyRepository, + > + StfExecutor< + OCallApi, + StateHandler, + NodeMetadataRepository, + Stf, + TCS, + G, + PH, + OnChainEncryptionKeyRepository, + > where OCallApi: EnclaveAttestationOCallApi + EnclaveOnChainOCallApi + EnclaveMetricsOCallApi, StateHandler: HandleState, StateHandler::StateT: SgxExternalitiesTrait + Encode, @@ -69,19 +97,42 @@ where Stf: UpdateState< StateHandler::StateT, ::SgxExternalitiesDiffType, - > + StateCallInterface, + > + StateCallInterface< + TCS, + StateHandler::StateT, + NodeMetadataRepository, + OCallApi, + PH, + OnChainEncryptionKeyRepository, + >, ::SgxExternalitiesDiffType: IntoIterator, Option>)> + From, Option>>>, - >::Error: Debug, + >::Error: Debug, TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, + PH: HeaderTrait, + OnChainEncryptionKeyRepository: AccessKey, { pub fn new( ocall_api: Arc, state_handler: Arc, node_metadata_repo: Arc, + on_chain_encryption_key_repository: Arc, ) -> Self { - StfExecutor { ocall_api, state_handler, node_metadata_repo, _phantom: PhantomData } + StfExecutor { + ocall_api, + state_handler, + node_metadata_repo, + on_chain_encryption_key_repository, + _phantom: PhantomData, + } } /// Execute a trusted call on the STF @@ -90,17 +141,14 @@ where /// an invalid trusted call, which results in `Ok(ExecutionStatus::Failure)`. The latter /// can be used to remove the trusted call from a queue. In the former case we might keep the /// trusted call and just re-try the operation. - fn execute_trusted_call_on_stf( + fn execute_trusted_call_on_stf( &self, state: &mut StateHandler::StateT, trusted_operation: &TrustedOperation, - _header: &PH, + parentchain_header: &PH, shard: &ShardIdentifier, post_processing: StatePostProcessing, - ) -> Result> - where - PH: HeaderTrait, - { + ) -> Result> { debug!("query mrenclave of self"); let mrenclave = self.ocall_api.get_mrenclave_of_self()?; @@ -132,6 +180,9 @@ where trusted_operation.hash(), &mut extrinsic_call_backs, self.node_metadata_repo.clone(), + self.ocall_api.clone(), + parentchain_header, + self.on_chain_encryption_key_repository.clone(), ) { Err(e) => { if let Err(e) = @@ -180,10 +231,26 @@ where } } -impl - StfUpdateState - for StfExecutor -where +impl< + OCallApi, + StateHandler, + NodeMetadataRepository, + Stf, + TCS, + G, + PH, + OnChainEncryptionKeyRepository, + > StfUpdateState + for StfExecutor< + OCallApi, + StateHandler, + NodeMetadataRepository, + Stf, + TCS, + G, + PH, + OnChainEncryptionKeyRepository, + > where OCallApi: EnclaveAttestationOCallApi + EnclaveOnChainOCallApi, StateHandler: HandleState + QueryShardState, StateHandler::StateT: SgxExternalitiesTrait + Encode, @@ -191,21 +258,18 @@ where Stf: UpdateState< StateHandler::StateT, ::SgxExternalitiesDiffType, - > + ParentchainPalletInstancesInterface, + > + ParentchainPalletInstancesInterface, ::SgxExternalitiesDiffType: IntoIterator, Option>)>, - >::Error: - Debug, + >::Error: Debug, ::SgxExternalitiesDiffType: From, Option>>>, TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, + PH: HeaderTrait, + OnChainEncryptionKeyRepository: AccessKey, { - fn update_states( - &self, - header: &ParentchainHeader, - parentchain_id: &ParentchainId, - ) -> Result<()> { + fn update_states(&self, header: &PH, parentchain_id: &ParentchainId) -> Result<()> { debug!("Update STF storage upon block import!"); let storage_hashes = Stf::storage_hashes_to_update_on_block(parentchain_id); @@ -245,28 +309,46 @@ where } } -impl - StfExecutor -where +impl< + OCallApi, + StateHandler, + NodeMetadataRepository, + Stf, + TCS, + G, + PH, + OnChainEncryptionKeyRepository, + > + StfExecutor< + OCallApi, + StateHandler, + NodeMetadataRepository, + Stf, + TCS, + G, + PH, + OnChainEncryptionKeyRepository, + > where ::SgxExternalitiesDiffType: From, Option>>> + IntoIterator, Option>)>, - >::Error: - Debug, + >::Error: Debug, NodeMetadataRepository: AccessNodeMetadata, OCallApi: EnclaveAttestationOCallApi + EnclaveOnChainOCallApi, StateHandler: HandleState + QueryShardState, StateHandler::StateT: Encode + SgxExternalitiesTrait, - Stf: ParentchainPalletInstancesInterface + Stf: ParentchainPalletInstancesInterface + UpdateState< StateHandler::StateT, ::SgxExternalitiesDiffType, >, TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, + PH: HeaderTrait, + OnChainEncryptionKeyRepository: AccessKey, { fn initialize_new_shards( &self, - header: &ParentchainHeader, + header: &PH, state_diff_update: &BTreeMap, Option>>, shards: &Vec, ) -> Result<()> { @@ -295,9 +377,26 @@ where } } -impl StateUpdateProposer - for StfExecutor -where +impl< + OCallApi, + StateHandler, + NodeMetadataRepository, + Stf, + TCS, + G, + PH, + OnChainEncryptionKeyRepository, + > StateUpdateProposer + for StfExecutor< + OCallApi, + StateHandler, + NodeMetadataRepository, + Stf, + TCS, + G, + PH, + OnChainEncryptionKeyRepository, + > where OCallApi: EnclaveAttestationOCallApi + EnclaveOnChainOCallApi + EnclaveMetricsOCallApi, StateHandler: HandleState, StateHandler::StateT: SgxExternalitiesTrait + Encode + StateHash, @@ -307,20 +406,35 @@ where Stf: UpdateState< StateHandler::StateT, ::SgxExternalitiesDiffType, - > + StateCallInterface - + RuntimeUpgradeInterface, + > + StateCallInterface< + TCS, + StateHandler::StateT, + NodeMetadataRepository, + OCallApi, + PH, + OnChainEncryptionKeyRepository, + > + RuntimeUpgradeInterface, ::SgxExternalitiesDiffType: IntoIterator, Option>)>, ::SgxExternalitiesDiffType: From, Option>>>, - >::Error: Debug, + >::Error: Debug, >::Error: Debug, TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, + PH: HeaderTrait, + OnChainEncryptionKeyRepository: AccessKey, { type Externalities = StateHandler::StateT; - fn propose_state_update( + fn propose_state_update( &self, trusted_calls: &[TrustedOperation], header: &PH, @@ -329,7 +443,6 @@ where prepare_state_function: F, ) -> Result> where - PH: HeaderTrait, F: FnOnce(Self::Externalities) -> Self::Externalities, { let ends_at = duration_now() + max_exec_duration; diff --git a/tee-worker/identity/core-primitives/stf-executor/src/executor_tests.rs b/tee-worker/identity/core-primitives/stf-executor/src/executor_tests.rs index 2eb0185bcd..b4249d5e49 100644 --- a/tee-worker/identity/core-primitives/stf-executor/src/executor_tests.rs +++ b/tee-worker/identity/core-primitives/stf-executor/src/executor_tests.rs @@ -18,9 +18,12 @@ use crate::{executor::StfExecutor, traits::StateUpdateProposer}; use codec::Encode; use itc_parentchain_test::ParentchainHeaderBuilder; +// TODO: use Aes256 when available use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; use itp_ocall_api::EnclaveAttestationOCallApi; +use itp_sgx_crypto::{mocks::KeyRepositoryMock, Aes}; use itp_sgx_externalities::{SgxExternalities as State, SgxExternalitiesTrait}; +use itp_sgx_io::SealedIO; use itp_stf_primitives::{traits::TrustedCallSigning, types::ShardIdentifier}; use itp_stf_state_handler::handle_state::HandleState; use itp_test::mock::{ @@ -28,7 +31,7 @@ use itp_test::mock::{ onchain_mock::OnchainMock, stf_mock::{GetterMock, StfMock, TrustedCallMock, TrustedCallSignedMock}, }; -use itp_types::H256; +use itp_types::{parentchain::Header as ParentchainHeader, H256}; use sp_core::{ed25519, Pair}; use sp_runtime::app_crypto::sp_core::blake2_256; use std::{sync::Arc, time::Duration, vec}; @@ -244,6 +247,8 @@ fn stf_executor() -> ( StfMock, TrustedCallSignedMock, GetterMock, + ParentchainHeader, + KeyRepositoryMock, >, Arc, Arc, @@ -251,7 +256,13 @@ fn stf_executor() -> ( let ocall_api = Arc::new(OnchainMock::default()); let state_handler = Arc::new(HandleStateMock::default()); let node_metadata_repo = Arc::new(NodeMetadataRepository::new(NodeMetadataMock::new())); - let executor = StfExecutor::new(ocall_api.clone(), state_handler.clone(), node_metadata_repo); + let encryption_key_repository = Arc::new(KeyRepositoryMock::new(Aes::default())); + let executor = StfExecutor::new( + ocall_api.clone(), + state_handler.clone(), + node_metadata_repo, + encryption_key_repository, + ); (executor, ocall_api, state_handler) } diff --git a/tee-worker/identity/core-primitives/stf-executor/src/mocks.rs b/tee-worker/identity/core-primitives/stf-executor/src/mocks.rs index d328a2e24e..96a554501b 100644 --- a/tee-worker/identity/core-primitives/stf-executor/src/mocks.rs +++ b/tee-worker/identity/core-primitives/stf-executor/src/mocks.rs @@ -59,15 +59,16 @@ impl StfExecutorMock { } } -impl StateUpdateProposer for StfExecutorMock +impl StateUpdateProposer for StfExecutorMock where State: SgxExternalitiesTrait + Encode + Clone, TCS: PartialEq + Encode + Decode + Clone + Debug + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Clone + Debug + Send + Sync, + PH: HeaderTrait, { type Externalities = State; - fn propose_state_update( + fn propose_state_update( &self, trusted_calls: &[TrustedOperation], _header: &PH, @@ -76,7 +77,6 @@ where prepare_state_function: F, ) -> Result> where - PH: HeaderTrait, F: FnOnce(Self::Externalities) -> Self::Externalities, { let mut lock = self.state.write().unwrap(); diff --git a/tee-worker/identity/core-primitives/stf-executor/src/traits.rs b/tee-worker/identity/core-primitives/stf-executor/src/traits.rs index 62e788141a..3b77b99588 100644 --- a/tee-worker/identity/core-primitives/stf-executor/src/traits.rs +++ b/tee-worker/identity/core-primitives/stf-executor/src/traits.rs @@ -55,10 +55,11 @@ where } /// Proposes a state update to `Externalities`. -pub trait StateUpdateProposer +pub trait StateUpdateProposer where TCS: PartialEq + Encode + Decode + Debug + Send + Sync, G: PartialEq + Encode + Decode + Debug + Send + Sync, + PH: HeaderTrait, { type Externalities: SgxExternalitiesTrait + Encode; @@ -66,7 +67,7 @@ where /// /// All executed call hashes and the mutated state are returned. /// If the time expires, any remaining trusted calls within the batch will be ignored. - fn propose_state_update( + fn propose_state_update( &self, trusted_calls: &[TrustedOperation], header: &PH, @@ -75,7 +76,6 @@ where prepare_state_function: F, ) -> Result> where - PH: HeaderTrait, F: FnOnce(Self::Externalities) -> Self::Externalities; } diff --git a/tee-worker/identity/core/offchain-worker-executor/src/executor.rs b/tee-worker/identity/core/offchain-worker-executor/src/executor.rs index 5cf3e778b8..51f9590e12 100644 --- a/tee-worker/identity/core/offchain-worker-executor/src/executor.rs +++ b/tee-worker/identity/core/offchain-worker-executor/src/executor.rs @@ -30,7 +30,7 @@ use itp_stf_state_handler::{handle_state::HandleState, query_shard_state::QueryS use itp_top_pool_author::traits::AuthorApi; use itp_types::{parentchain::ParentchainCall, OpaqueCall, ShardIdentifier, H256}; use log::*; -use sp_runtime::traits::Block; +use sp_runtime::traits::{Block, Header as HeaderTrait}; use std::{marker::PhantomData, sync::Arc, time::Duration, vec::Vec}; /// Off-chain worker executor implementation. @@ -51,13 +51,14 @@ pub struct Executor< Stf, TCS, G, + PH, > { top_pool_author: Arc, stf_executor: Arc, state_handler: Arc, validator_accessor: Arc, extrinsics_factory: Arc, - _phantom: PhantomData<(ParentchainBlock, Stf, TCS, G)>, + _phantom: PhantomData<(ParentchainBlock, Stf, TCS, G, PH)>, } impl< @@ -70,6 +71,7 @@ impl< Stf, TCS, G, + PH, > Executor< ParentchainBlock, @@ -81,9 +83,10 @@ impl< Stf, TCS, G, + PH, > where - ParentchainBlock: Block, - StfExecutor: StateUpdateProposer, + ParentchainBlock: Block, + StfExecutor: StateUpdateProposer, TopPoolAuthor: AuthorApi, StateHandler: QueryShardState + HandleState, ValidatorAccessor: ValidatorAccess + Send + Sync + 'static, @@ -92,6 +95,7 @@ impl< Stf: SystemPalletEventInterface, TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, + PH: HeaderTrait, { pub fn new( top_pool_author: Arc, @@ -186,7 +190,7 @@ impl< fn apply_state_update( &self, shard: &ShardIdentifier, - updated_state: >::Externalities, + updated_state: >::Externalities, ) -> Result<()> { self.state_handler.reset(updated_state, shard)?; Ok(()) diff --git a/tee-worker/identity/enclave-runtime/Cargo.lock b/tee-worker/identity/enclave-runtime/Cargo.lock index 2d26517e8f..4a6442c950 100644 --- a/tee-worker/identity/enclave-runtime/Cargo.lock +++ b/tee-worker/identity/enclave-runtime/Cargo.lock @@ -1924,6 +1924,8 @@ dependencies = [ "itp-node-api", "itp-node-api-metadata", "itp-node-api-metadata-provider", + "itp-ocall-api", + "itp-sgx-crypto", "itp-sgx-externalities", "itp-stf-interface", "itp-stf-primitives", @@ -2086,6 +2088,7 @@ dependencies = [ "itp-ocall-api", "itp-sgx-crypto", "itp-sgx-externalities", + "itp-sgx-io", "itp-stf-interface", "itp-stf-primitives", "itp-stf-state-handler", @@ -2607,9 +2610,12 @@ version = "0.8.0" dependencies = [ "itp-node-api-metadata", "itp-node-api-metadata-provider", + "itp-ocall-api", + "itp-sgx-crypto", "itp-stf-primitives", "itp-types", "parity-scale-codec", + "sp-runtime", ] [[package]] diff --git a/tee-worker/identity/enclave-runtime/src/initialization/global_components.rs b/tee-worker/identity/enclave-runtime/src/initialization/global_components.rs index 5255d5303e..188eb8c6c8 100644 --- a/tee-worker/identity/enclave-runtime/src/initialization/global_components.rs +++ b/tee-worker/identity/enclave-runtime/src/initialization/global_components.rs @@ -79,7 +79,10 @@ use itp_top_pool_author::{ api::SidechainApi, author::{Author, AuthorTopFilter, BroadcastedTopFilter}, }; -use itp_types::{Block as ParentchainBlock, SignedBlock as SignedParentchainBlock}; +use itp_types::{ + parentchain::Header as ParentchainHeader, Block as ParentchainBlock, + SignedBlock as SignedParentchainBlock, +}; use its_primitives::{ traits::{Block as SidechainBlockTrait, SignedBlock as SignedSidechainBlockTrait}, types::block::SignedBlock as SignedSidechainBlock, @@ -126,6 +129,8 @@ pub type EnclaveStfExecutor = StfExecutor< EnclaveStf, EnclaveTrustedCallSigned, EnclaveGetter, + ParentchainHeader, + EnclaveStateKeyRepository, // TODO: use new aes256 key repository when available >; pub type EnclaveStfEnclaveSigner = StfEnclaveSigner< EnclaveOCallApi, @@ -362,6 +367,7 @@ pub type EnclaveOffchainWorkerExecutor = itc_offchain_worker_executor::executor: EnclaveStf, EnclaveTrustedCallSigned, EnclaveGetter, + ParentchainHeader, >; // Base component instances diff --git a/tee-worker/identity/enclave-runtime/src/initialization/parentchain/integritee_parachain.rs b/tee-worker/identity/enclave-runtime/src/initialization/parentchain/integritee_parachain.rs index 62e7bb6d67..ebaf69177e 100644 --- a/tee-worker/identity/enclave-runtime/src/initialization/parentchain/integritee_parachain.rs +++ b/tee-worker/identity/enclave-runtime/src/initialization/parentchain/integritee_parachain.rs @@ -19,12 +19,17 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, - EnclaveStfExecutor, EnclaveValidatorAccessor, + EnclaveExtrinsicsFactory, + EnclaveNodeMetadataRepository, + EnclaveOCallApi, + EnclaveStfExecutor, + EnclaveValidatorAccessor, IntegriteeParentchainBlockImportDispatcher, GLOBAL_INTEGRITEE_PARENTCHAIN_LIGHT_CLIENT_SEAL, - GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE, GLOBAL_OCALL_API_COMPONENT, + GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE, + GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, + GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, // TODO: use global for aes256 key repository }, parentchain::common::{ create_extrinsics_factory, create_integritee_offchain_immediate_import_dispatcher, @@ -80,10 +85,13 @@ impl IntegriteeParachainHandler { node_metadata_repository.clone(), )?; + let on_chain_encryption_key_repository = GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.get()?; + let stf_executor = Arc::new(EnclaveStfExecutor::new( ocall_api, state_handler, node_metadata_repository.clone(), + on_chain_encryption_key_repository, )); let block_importer = create_integritee_parentchain_block_importer( diff --git a/tee-worker/identity/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs b/tee-worker/identity/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs index f8c8d512d7..f9a7c4df25 100644 --- a/tee-worker/identity/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs +++ b/tee-worker/identity/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs @@ -19,12 +19,17 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, - EnclaveStfExecutor, EnclaveValidatorAccessor, + EnclaveExtrinsicsFactory, + EnclaveNodeMetadataRepository, + EnclaveOCallApi, + EnclaveStfExecutor, + EnclaveValidatorAccessor, IntegriteeParentchainBlockImportDispatcher, GLOBAL_INTEGRITEE_PARENTCHAIN_LIGHT_CLIENT_SEAL, - GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE, GLOBAL_OCALL_API_COMPONENT, + GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE, + GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, + GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, // TODO: use global for aes256 key repository }, parentchain::common::{ create_extrinsics_factory, create_integritee_offchain_immediate_import_dispatcher, @@ -79,10 +84,13 @@ impl IntegriteeSolochainHandler { node_metadata_repository.clone(), )?; + let on_chain_encryption_key_repository = GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.get()?; + let stf_executor = Arc::new(EnclaveStfExecutor::new( ocall_api, state_handler, node_metadata_repository.clone(), + on_chain_encryption_key_repository, )); let block_importer = create_integritee_parentchain_block_importer( diff --git a/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_a_parachain.rs b/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_a_parachain.rs index 59921c14af..0d74df3e5f 100644 --- a/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_a_parachain.rs +++ b/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_a_parachain.rs @@ -25,10 +25,17 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, - EnclaveStfExecutor, EnclaveValidatorAccessor, TargetAParentchainBlockImportDispatcher, - GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE, + EnclaveExtrinsicsFactory, + EnclaveNodeMetadataRepository, + EnclaveOCallApi, + EnclaveStfExecutor, + EnclaveValidatorAccessor, + TargetAParentchainBlockImportDispatcher, + GLOBAL_OCALL_API_COMPONENT, + GLOBAL_STATE_HANDLER_COMPONENT, + GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, // TODO: use global for aes256 key repository + GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL, + GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE, }, parentchain::common::{ create_extrinsics_factory, create_sidechain_triggered_import_dispatcher_for_target_a, @@ -84,10 +91,13 @@ impl TargetAParachainHandler { node_metadata_repository.clone(), )?; + let on_chain_encryption_key_repository = GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.get()?; + let stf_executor = Arc::new(EnclaveStfExecutor::new( ocall_api, state_handler, node_metadata_repository.clone(), + on_chain_encryption_key_repository, )); let block_importer = create_target_a_parentchain_block_importer( diff --git a/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs b/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs index 41a12bbbf8..3836780052 100644 --- a/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs +++ b/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs @@ -19,10 +19,17 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, - EnclaveStfExecutor, EnclaveValidatorAccessor, TargetAParentchainBlockImportDispatcher, - GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE, + EnclaveExtrinsicsFactory, + EnclaveNodeMetadataRepository, + EnclaveOCallApi, + EnclaveStfExecutor, + EnclaveValidatorAccessor, + TargetAParentchainBlockImportDispatcher, + GLOBAL_OCALL_API_COMPONENT, + GLOBAL_STATE_HANDLER_COMPONENT, + GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, // TODO: use global for aes256 key repository + GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL, + GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE, }, parentchain::common::{ create_extrinsics_factory, create_sidechain_triggered_import_dispatcher_for_target_a, @@ -77,10 +84,13 @@ impl TargetASolochainHandler { node_metadata_repository.clone(), )?; + let on_chain_encryption_key_repository = GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.get()?; + let stf_executor = Arc::new(EnclaveStfExecutor::new( ocall_api, state_handler, node_metadata_repository.clone(), + on_chain_encryption_key_repository, )); let block_importer = create_target_a_parentchain_block_importer( diff --git a/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_b_parachain.rs b/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_b_parachain.rs index 21b729a456..e4ec762651 100644 --- a/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_b_parachain.rs +++ b/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_b_parachain.rs @@ -25,10 +25,17 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, - EnclaveStfExecutor, EnclaveValidatorAccessor, TargetBParentchainBlockImportDispatcher, - GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE, + EnclaveExtrinsicsFactory, + EnclaveNodeMetadataRepository, + EnclaveOCallApi, + EnclaveStfExecutor, + EnclaveValidatorAccessor, + TargetBParentchainBlockImportDispatcher, + GLOBAL_OCALL_API_COMPONENT, + GLOBAL_STATE_HANDLER_COMPONENT, + GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, // TODO: use global for aes256 key repository + GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL, + GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE, }, parentchain::common::{ create_extrinsics_factory, create_sidechain_triggered_import_dispatcher_for_target_b, @@ -84,10 +91,13 @@ impl TargetBParachainHandler { node_metadata_repository.clone(), )?; + let on_chain_encryption_key_repository = GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.get()?; + let stf_executor = Arc::new(EnclaveStfExecutor::new( ocall_api, state_handler, node_metadata_repository.clone(), + on_chain_encryption_key_repository, )); let block_importer = create_target_b_parentchain_block_importer( diff --git a/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs b/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs index 954fe436c8..e457a24b44 100644 --- a/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs +++ b/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs @@ -19,10 +19,17 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, - EnclaveStfExecutor, EnclaveValidatorAccessor, TargetBParentchainBlockImportDispatcher, - GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE, + EnclaveExtrinsicsFactory, + EnclaveNodeMetadataRepository, + EnclaveOCallApi, + EnclaveStfExecutor, + EnclaveValidatorAccessor, + TargetBParentchainBlockImportDispatcher, + GLOBAL_OCALL_API_COMPONENT, + GLOBAL_STATE_HANDLER_COMPONENT, + GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, // TODO: use global for aes256 key repository + GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL, + GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE, }, parentchain::common::{ create_extrinsics_factory, create_sidechain_triggered_import_dispatcher_for_target_b, @@ -77,10 +84,13 @@ impl TargetBSolochainHandler { node_metadata_repository.clone(), )?; + let on_chain_encryption_key_repository = GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.get()?; + let stf_executor = Arc::new(EnclaveStfExecutor::new( ocall_api, state_handler, node_metadata_repository.clone(), + on_chain_encryption_key_repository, )); let block_importer = create_target_b_parentchain_block_importer( diff --git a/tee-worker/identity/enclave-runtime/src/test/enclave_signer_tests.rs b/tee-worker/identity/enclave-runtime/src/test/enclave_signer_tests.rs index 8f20f23a86..e2fdd419ab 100644 --- a/tee-worker/identity/enclave-runtime/src/test/enclave_signer_tests.rs +++ b/tee-worker/identity/enclave-runtime/src/test/enclave_signer_tests.rs @@ -20,7 +20,10 @@ use ita_stf::{Getter, Stf, TrustedCall, TrustedCallSigned}; use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; use itp_ocall_api::EnclaveAttestationOCallApi; use itp_sgx_crypto::{ - ed25519_derivation::DeriveEd25519, key_repository::AccessKey, mocks::KeyRepositoryMock, + ed25519_derivation::DeriveEd25519, + key_repository::AccessKey, + mocks::KeyRepositoryMock, + Aes, // TODO: use Aes256 when available }; use itp_sgx_externalities::SgxExternalities; use itp_stf_executor::{enclave_signer::StfEnclaveSigner, traits::StfEnclaveSigning}; @@ -35,15 +38,21 @@ use itp_stf_primitives::{ use itp_stf_state_observer::mock::ObserveStateMock; use itp_test::mock::onchain_mock::OnchainMock; use itp_top_pool_author::{mocks::AuthorApiMock, traits::AuthorApi}; -use itp_types::RsaRequest; +use itp_types::{Header, RsaRequest}; use litentry_primitives::Identity; use sgx_crypto_helper::{rsa3072::Rsa3072KeyPair, RsaKeyPair}; use sp_core::Pair; +use sp_runtime::traits::Header as HeaderTrait; use std::{sync::Arc, vec::Vec}; type ShieldingKeyRepositoryMock = KeyRepositoryMock; +type OnChainEncryptionKeyRepositoryMock = KeyRepositoryMock; type TestStf = Stf; +pub fn latest_parentchain_header() -> Header { + Header::new(1, Default::default(), Default::default(), [69; 32].into(), Default::default()) +} + pub fn derive_key_is_deterministic() { let rsa_key = Rsa3072KeyPair::new().unwrap(); @@ -98,7 +107,7 @@ pub fn nonce_is_computed_correctly() { let shard = ShardIdentifier::default(); let enclave_signer = StfEnclaveSigner::<_, _, _, TestStf, _, TrustedCallSigned, Getter>::new( state_observer, - ocall_api, + ocall_api.clone(), shielding_key_repo, top_pool_author.clone(), ); @@ -134,6 +143,8 @@ pub fn nonce_is_computed_correctly() { assert_eq!(0, TestStf::get_account_nonce(&mut state, &enclave_account)); let repo = Arc::new(NodeMetadataRepository::new(NodeMetadataMock::new())); + let on_chain_encryption_key_repository = + Arc::new(OnChainEncryptionKeyRepositoryMock::new(Aes::default())); assert!(TestStf::execute_call( &mut state, &shard, @@ -141,6 +152,9 @@ pub fn nonce_is_computed_correctly() { Default::default(), &mut Vec::new(), repo.clone(), + ocall_api.clone(), + &latest_parentchain_header(), + on_chain_encryption_key_repository.clone() ) .is_ok()); @@ -151,6 +165,9 @@ pub fn nonce_is_computed_correctly() { Default::default(), &mut Vec::new(), repo, + ocall_api, + &latest_parentchain_header(), + on_chain_encryption_key_repository ) .is_ok()); assert_eq!(2, TestStf::get_account_nonce(&mut state, &enclave_account)); diff --git a/tee-worker/identity/enclave-runtime/src/test/fixtures/test_setup.rs b/tee-worker/identity/enclave-runtime/src/test/fixtures/test_setup.rs index 78c2bef328..570b3e589e 100644 --- a/tee-worker/identity/enclave-runtime/src/test/fixtures/test_setup.rs +++ b/tee-worker/identity/enclave-runtime/src/test/fixtures/test_setup.rs @@ -24,7 +24,12 @@ use ita_sgx_runtime::Runtime; use ita_stf::{Getter, State, Stf, TrustedCallSigned}; use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; use itp_ocall_api::EnclaveAttestationOCallApi; -use itp_sgx_crypto::{ed25519_derivation::DeriveEd25519, mocks::KeyRepositoryMock}; +use itp_sgx_crypto::{ + ed25519_derivation::DeriveEd25519, + key_repository::KeyRepository, + mocks::KeyRepositoryMock, + Aes, // TODO: use Aes256 when available +}; use itp_sgx_externalities::SgxExternalities; use itp_stf_executor::executor::StfExecutor; use itp_stf_primitives::types::{ShardIdentifier, TrustedOperation}; @@ -38,7 +43,7 @@ use itp_top_pool_author::{ author::Author, top_filter::{AllowAllTopsFilter, DirectCallsOnlyFilter}, }; -use itp_types::{Block, MrEnclave}; +use itp_types::{parentchain::Header as ParentchainHeader, Block, MrEnclave}; use sp_core::{crypto::Pair, ed25519 as spEd25519}; use std::sync::Arc; pub type TestRpcResponder = RpcResponderMock>>; @@ -61,6 +66,8 @@ pub type TestTopPoolAuthor = Author< >; pub type TestStf = Stf; +type TestOnChainEncryptionKeyRepository = KeyRepositoryMock; + pub type TestStfExecutor = StfExecutor< OcallApi, HandleStateMock, @@ -68,6 +75,8 @@ pub type TestStfExecutor = StfExecutor< TestStf, TrustedCallSigned, Getter, + ParentchainHeader, + TestOnChainEncryptionKeyRepository, >; /// Returns all the things that are commonly used in tests and runs @@ -80,6 +89,7 @@ pub fn test_setup() -> ( ShieldingCryptoMock, Arc, Arc, + Arc, ) { let shielding_key = ShieldingCryptoMock::default(); let shielding_key_repo = Arc::new(KeyRepositoryMock::new(shielding_key.clone())); @@ -91,10 +101,13 @@ pub fn test_setup() -> ( let mrenclave = OcallApi.get_mrenclave_of_self().unwrap().m; let node_metadata_repo = Arc::new(NodeMetadataRepository::new(NodeMetadataMock::new())); + let on_chain_encryption_key_repository = KeyRepositoryMock::new(Aes::default()); + let stf_executor = Arc::new(TestStfExecutor::new( Arc::new(OcallApi), state_handler.clone(), node_metadata_repo, + Arc::new(on_chain_encryption_key_repository), )); let (sender, _receiver) = std::sync::mpsc::sync_channel(1000); @@ -115,6 +128,7 @@ pub fn test_setup() -> ( shielding_key, state_handler, stf_executor, + Arc::new(OcallApi), ) } diff --git a/tee-worker/identity/enclave-runtime/src/test/mocks/types.rs b/tee-worker/identity/enclave-runtime/src/test/mocks/types.rs index ae939c53e4..ac39650570 100644 --- a/tee-worker/identity/enclave-runtime/src/test/mocks/types.rs +++ b/tee-worker/identity/enclave-runtime/src/test/mocks/types.rs @@ -39,7 +39,10 @@ use itp_top_pool_author::{ author::Author, top_filter::{AllowAllTopsFilter, DirectCallsOnlyFilter}, }; -use itp_types::{Block as ParentchainBlock, SignedBlock as SignedParentchainBlock}; +use itp_types::{ + parentchain::Header as ParentchainHeader, Block as ParentchainBlock, + SignedBlock as SignedParentchainBlock, +}; use its_primitives::types::SignedBlock as SignedSidechainBlock; use its_sidechain::{aura::block_importer::BlockImporter, block_composer::BlockComposer}; use primitive_types::H256; @@ -74,6 +77,8 @@ pub type TestStfExecutor = StfExecutor< TestStf, TrustedCallSigned, Getter, + ParentchainHeader, + TestStateKeyRepo, >; pub type TestRpcResponder = RpcResponderMock; diff --git a/tee-worker/identity/enclave-runtime/src/test/sidechain_aura_tests.rs b/tee-worker/identity/enclave-runtime/src/test/sidechain_aura_tests.rs index 0e2c6639c9..ac867fffa3 100644 --- a/tee-worker/identity/enclave-runtime/src/test/sidechain_aura_tests.rs +++ b/tee-worker/identity/enclave-runtime/src/test/sidechain_aura_tests.rs @@ -103,6 +103,7 @@ pub fn produce_sidechain_block_and_import_it() { ocall_api.clone(), state_handler.clone(), node_metadata_repo, + state_key_repo.clone(), )); let top_pool = create_top_pool(); diff --git a/tee-worker/identity/enclave-runtime/src/test/sidechain_event_tests.rs b/tee-worker/identity/enclave-runtime/src/test/sidechain_event_tests.rs index 458ea2053b..a148d54b2e 100644 --- a/tee-worker/identity/enclave-runtime/src/test/sidechain_event_tests.rs +++ b/tee-worker/identity/enclave-runtime/src/test/sidechain_event_tests.rs @@ -87,6 +87,7 @@ pub fn ensure_events_get_reset_upon_block_proposal() { ocall_api.clone(), state_handler.clone(), node_metadata_repo, + state_key_repo.clone(), )); let top_pool = create_top_pool(); let (sender, _receiver) = std::sync::mpsc::sync_channel(1000); diff --git a/tee-worker/identity/enclave-runtime/src/test/tests_main.rs b/tee-worker/identity/enclave-runtime/src/test/tests_main.rs index 0a61660650..c94e12ee18 100644 --- a/tee-worker/identity/enclave-runtime/src/test/tests_main.rs +++ b/tee-worker/identity/enclave-runtime/src/test/tests_main.rs @@ -37,7 +37,7 @@ use ita_stf::{ AccountInfo, Getter, State, TrustedCall, TrustedCallSigned, TrustedGetter, }; use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; -use itp_sgx_crypto::{Aes, StateCrypto}; +use itp_sgx_crypto::{mocks::KeyRepositoryMock, Aes, StateCrypto}; use itp_sgx_externalities::{SgxExternalitiesDiffType, SgxExternalitiesTrait, StateHash}; use itp_stf_executor::{ executor_tests as stf_executor_tests, traits::StateUpdateProposer, BatchExecutionResult, @@ -183,7 +183,7 @@ fn run_evm_tests() {} fn test_compose_block() { // given - let (_, _, shard, _, _, state_handler, _) = test_setup(); + let (_, _, shard, _, _, state_handler, _, ..) = test_setup(); let block_composer = BlockComposer::::new( test_account(), Arc::new(TestStateKeyRepo::new(state_key())), @@ -325,7 +325,7 @@ fn test_differentiate_getter_and_call_works() { fn test_create_block_and_confirmation_works() { // given - let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor) = test_setup(); + let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor, ..) = test_setup(); let block_composer = BlockComposer::::new( test_account(), @@ -375,7 +375,7 @@ fn test_create_block_and_confirmation_works() { fn test_create_state_diff() { // given - let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor) = test_setup(); + let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor, ..) = test_setup(); let block_composer = BlockComposer::::new( test_account(), @@ -441,7 +441,7 @@ fn test_create_state_diff() { fn test_executing_call_updates_account_nonce() { // given - let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor) = test_setup(); + let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor, ..) = test_setup(); let sender = funded_pair(); let receiver = unfunded_public(); @@ -475,7 +475,7 @@ fn test_executing_call_updates_account_nonce() { } fn test_call_set_update_parentchain_block() { - let (_, _, shard, _, _, state_handler, _) = test_setup(); + let (_, _, shard, _, _, state_handler, _, ..) = test_setup(); let (mut state, _) = state_handler.load_cloned(&shard).unwrap(); let block_number = 3; @@ -498,7 +498,7 @@ fn test_call_set_update_parentchain_block() { fn test_signature_must_match_public_sender_in_call() { // given - let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor) = test_setup(); + let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor, ..) = test_setup(); // create accounts let sender = funded_pair(); @@ -529,7 +529,7 @@ fn test_signature_must_match_public_sender_in_call() { fn test_invalid_nonce_call_is_not_executed() { // given - let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor) = test_setup(); + let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor, ..) = test_setup(); // create accounts let sender = funded_pair(); @@ -560,7 +560,8 @@ fn test_invalid_nonce_call_is_not_executed() { pub fn test_retrieve_events() { // given - let (_, mut state, shard, mrenclave, ..) = test_setup(); + let (_, mut state, shard, mrenclave, _shielding_key, _state_handler, _stf_executor, ocall_api) = + test_setup(); let mut opaque_vec = Vec::new(); let sender = funded_pair(); let receiver = unendowed_account(); @@ -577,6 +578,8 @@ pub fn test_retrieve_events() { .sign(&sender.into(), 0, &mrenclave, &shard); let repo = Arc::new(NodeMetadataRepository::::default()); let shard = ShardIdentifier::default(); + let on_chain_encryption_key_repository = + Arc::new(KeyRepositoryMock::::new(Aes::default())); TestStf::execute_call( &mut state, &shard, @@ -584,6 +587,9 @@ pub fn test_retrieve_events() { Default::default(), &mut opaque_vec, repo, + ocall_api, + &latest_parentchain_header(), + on_chain_encryption_key_repository, ) .unwrap(); @@ -591,7 +597,8 @@ pub fn test_retrieve_events() { } pub fn test_retrieve_event_count() { - let (_, mut state, shard, mrenclave, ..) = test_setup(); + let (_, mut state, shard, mrenclave, _shielding_key, _state_handler, _stf_executor, ocall_api) = + test_setup(); let mut opaque_vec = Vec::new(); let sender = funded_pair(); let receiver = unendowed_account(); @@ -610,6 +617,8 @@ pub fn test_retrieve_event_count() { // when let repo = Arc::new(NodeMetadataRepository::::default()); let shard = ShardIdentifier::default(); + let on_chain_encryption_key_repository = + Arc::new(KeyRepositoryMock::::new(Aes::default())); TestStf::execute_call( &mut state, &shard, @@ -617,6 +626,9 @@ pub fn test_retrieve_event_count() { Default::default(), &mut opaque_vec, repo, + ocall_api, + &latest_parentchain_header(), + on_chain_encryption_key_repository, ) .unwrap(); @@ -625,7 +637,8 @@ pub fn test_retrieve_event_count() { } pub fn test_reset_events() { - let (_, mut state, shard, mrenclave, ..) = test_setup(); + let (_, mut state, shard, mrenclave, _shielding_key, _state_handler, _stf_executor, ocall_api) = + test_setup(); let mut opaque_vec = Vec::new(); let sender = funded_pair(); let receiver = unendowed_account(); @@ -641,6 +654,9 @@ pub fn test_reset_events() { .sign(&sender.into(), 0, &mrenclave, &shard); let repo = Arc::new(NodeMetadataRepository::::default()); let shard = ShardIdentifier::default(); + let on_chain_encryption_key_repository = + Arc::new(KeyRepositoryMock::::new(Aes::default())); + TestStf::execute_call( &mut state, &shard, @@ -648,6 +664,9 @@ pub fn test_reset_events() { Default::default(), &mut opaque_vec, repo, + ocall_api, + &latest_parentchain_header(), + on_chain_encryption_key_repository, ) .unwrap(); let receiver_acc_info = TestStf::get_account_data(&mut state, &receiver.public().into()); diff --git a/tee-worker/identity/enclave-runtime/src/top_pool_execution.rs b/tee-worker/identity/enclave-runtime/src/top_pool_execution.rs index 439a3f2463..f264ed819d 100644 --- a/tee-worker/identity/enclave-runtime/src/top_pool_execution.rs +++ b/tee-worker/identity/enclave-runtime/src/top_pool_execution.rs @@ -203,7 +203,7 @@ fn execute_top_pool_trusted_calls_internal() -> Result<()> { } log_remaining_slot_duration(&slot, "Before AURA"); - let env = ProposerFactory::::new( + let env = ProposerFactory::::new( top_pool_author, stf_executor, block_composer, diff --git a/tee-worker/identity/sidechain/consensus/aura/src/proposer_factory.rs b/tee-worker/identity/sidechain/consensus/aura/src/proposer_factory.rs index 61fa21557f..8c0f626dd9 100644 --- a/tee-worker/identity/sidechain/consensus/aura/src/proposer_factory.rs +++ b/tee-worker/identity/sidechain/consensus/aura/src/proposer_factory.rs @@ -32,7 +32,7 @@ use its_primitives::traits::{ }; use its_state::{SidechainState, SidechainSystemExt}; use sp_runtime::{ - traits::{Block, NumberFor}, + traits::{Block, Header as ParentchainHeaderTrait, NumberFor}, MultiSignature, }; use std::{marker::PhantomData, sync::Arc}; @@ -45,16 +45,18 @@ pub struct ProposerFactory< StfExecutor, BlockComposer, MetricsApi, + PH, > { top_pool_author: Arc, stf_executor: Arc, block_composer: Arc, metrics_api: Arc, _phantom: PhantomData, + _phantom_header: PhantomData, } -impl - ProposerFactory +impl + ProposerFactory { pub fn new( top_pool_executor: Arc, @@ -68,19 +70,21 @@ impl, + ParentchainBlock: Block, SignedSidechainBlock, TopPoolAuthor, StfExecutor, BlockComposer, MetricsApi, + PH, > Environment - for ProposerFactory + for ProposerFactory where NumberFor: BlockNumberOps, SignedSidechainBlock: SignedSidechainBlockTrait @@ -90,18 +94,19 @@ where HeaderTrait, TopPoolAuthor: AuthorApi + Send + Sync + 'static, - StfExecutor: StateUpdateProposer + Send + Sync + 'static, - ExternalitiesFor: + StfExecutor: StateUpdateProposer + Send + Sync + 'static, + ExternalitiesFor: SgxExternalitiesTrait + SidechainState + SidechainSystemExt + StateHash, - as SgxExternalitiesTrait>::SgxExternalitiesType: Encode, + as SgxExternalitiesTrait>::SgxExternalitiesType: Encode, BlockComposer: ComposeBlock< - ExternalitiesFor, + ExternalitiesFor, ParentchainBlock, SignedSidechainBlock = SignedSidechainBlock, > + Send + Sync + 'static, MetricsApi: EnclaveMetricsOCallApi, + PH: ParentchainHeaderTrait, { type Proposer = SlotProposer< ParentchainBlock, @@ -110,6 +115,7 @@ where StfExecutor, BlockComposer, MetricsApi, + PH, >; type Error = ConsensusError; @@ -126,6 +132,7 @@ where shard, metrics_api: self.metrics_api.clone(), _phantom: PhantomData, + _phantom_header: PhantomData, }) } } diff --git a/tee-worker/identity/sidechain/consensus/aura/src/slot_proposer.rs b/tee-worker/identity/sidechain/consensus/aura/src/slot_proposer.rs index 2424df56f6..eaf005d3a2 100644 --- a/tee-worker/identity/sidechain/consensus/aura/src/slot_proposer.rs +++ b/tee-worker/identity/sidechain/consensus/aura/src/slot_proposer.rs @@ -35,28 +35,31 @@ use its_primitives::traits::{ use its_state::{SidechainState, SidechainSystemExt}; use log::*; use sp_runtime::{ - traits::{Block, NumberFor}, + traits::{Block, Header as ParentchainHeaderTrait, NumberFor}, MultiSignature, }; use std::{marker::PhantomData, string::ToString, sync::Arc, time::Duration, vec::Vec}; -pub type ExternalitiesFor = >::Externalities; +pub type ExternalitiesFor = + >::Externalities; ///! `SlotProposer` instance that has access to everything needed to propose a sidechain block. pub struct SlotProposer< - ParentchainBlock: Block, + ParentchainBlock: Block
, SignedSidechainBlock: SignedSidechainBlockTrait, TopPoolAuthor, StfExecutor, BlockComposer, MetricsApi, + ParentchainHeader, > { pub(crate) top_pool_author: Arc, pub(crate) stf_executor: Arc, pub(crate) block_composer: Arc, - pub(crate) parentchain_header: ParentchainBlock::Header, + pub(crate) parentchain_header: ParentchainHeader, pub(crate) shard: ShardIdentifierFor, pub(crate) metrics_api: Arc, pub(crate) _phantom: PhantomData, + pub(crate) _phantom_header: PhantomData, } impl< @@ -66,6 +69,7 @@ impl< BlockComposer, StfExecutor, MetricsApi, + PH, > Proposer for SlotProposer< ParentchainBlock, @@ -74,28 +78,30 @@ impl< StfExecutor, BlockComposer, MetricsApi, + PH, > where - ParentchainBlock: Block, + ParentchainBlock: Block, NumberFor: BlockNumberOps, SignedSidechainBlock: SignedSidechainBlockTrait + 'static, SignedSidechainBlock::Block: SidechainBlockTrait, <::Block as SidechainBlockTrait>::HeaderType: HeaderTrait, - StfExecutor: StateUpdateProposer, - ExternalitiesFor: + StfExecutor: StateUpdateProposer, + ExternalitiesFor: SgxExternalitiesTrait + SidechainState + SidechainSystemExt + StateHash, - as SgxExternalitiesTrait>::SgxExternalitiesType: Encode, + as SgxExternalitiesTrait>::SgxExternalitiesType: Encode, TopPoolAuthor: AuthorApi + Send + Sync + 'static, BlockComposer: ComposeBlock< - ExternalitiesFor, + ExternalitiesFor, ParentchainBlock, SignedSidechainBlock = SignedSidechainBlock, > + Send + Sync + 'static, MetricsApi: EnclaveMetricsOCallApi, + PH: ParentchainHeaderTrait, { /// Proposes a new sidechain block. /// From 17845b866c427903c5019d0794e5340275ebefab Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Tue, 8 Oct 2024 13:05:23 +0000 Subject: [PATCH 11/39] refactoring omni-account core, updating names and structures --- .../src/id_graphs_repository/mod.rs | 96 ------------------ .../core/omni-account/src/id_graphs_store.rs | 61 ------------ .../core/omni-account/src/in_memory_store.rs | 65 ++++++++++++ .../litentry/core/omni-account/src/lib.rs | 18 ++-- .../core/omni-account/src/repository.rs | 98 +++++++++++++++++++ 5 files changed, 171 insertions(+), 167 deletions(-) delete mode 100644 tee-worker/identity/litentry/core/omni-account/src/id_graphs_repository/mod.rs delete mode 100644 tee-worker/identity/litentry/core/omni-account/src/id_graphs_store.rs create mode 100644 tee-worker/identity/litentry/core/omni-account/src/in_memory_store.rs create mode 100644 tee-worker/identity/litentry/core/omni-account/src/repository.rs diff --git a/tee-worker/identity/litentry/core/omni-account/src/id_graphs_repository/mod.rs b/tee-worker/identity/litentry/core/omni-account/src/id_graphs_repository/mod.rs deleted file mode 100644 index 94d1e1b86b..0000000000 --- a/tee-worker/identity/litentry/core/omni-account/src/id_graphs_repository/mod.rs +++ /dev/null @@ -1,96 +0,0 @@ -use crate::{ - AccountId, Error, Hash, Header, IDGraph, IDGraphMember, IDGraphs, Identity, OmniAccountIDGraph, - ParentchainId, -}; -use alloc::vec::Vec; -use codec::Encode; -use frame_support::storage::storage_prefix; -use itp_ocall_api::EnclaveOnChainOCallApi; -use itp_storage::{ - decode_storage_key, extract_blake2_128concat_key, storage_map_key, StorageHasher, -}; -use sp_core::blake2_256; - -// TODO: get this from core_primitives after the release-v0.9.19 branch has been updated -pub trait IDGraphHash { - fn hash(&self) -> Hash; -} -impl IDGraphHash for Vec { - fn hash(&self) -> Hash { - let members_hashes: Vec = self.iter().map(|member| member.hash).collect(); - Hash::from(blake2_256(&members_hashes.encode())) - } -} - -pub trait GetIDGraphsRepository { - fn get_by_owner( - &self, - block_header: Header, - owner: Identity, - ) -> Result; - fn get(&self, block_header: Header) -> Result; -} - -pub struct IDGraphsRepository { - ocall_api: OCallApi, -} - -impl IDGraphsRepository { - pub fn new(ocall_api: OCallApi) -> Self { - Self { ocall_api } - } -} - -impl GetIDGraphsRepository for IDGraphsRepository { - fn get_by_owner( - &self, - block_header: Header, - owner: Identity, - ) -> Result { - let storage_key = - storage_map_key("OmniAccount", "IDGraphs", &owner, &StorageHasher::Blake2_128Concat); - let storage_entry = self - .ocall_api - .get_storage_verified(storage_key, &block_header, &ParentchainId::Litentry) - .map_err(|_| Error::OCallApiError("Failed to get storage"))?; - let id_graph: Vec = - storage_entry.value().to_owned().ok_or(Error::NotFound)?; - let id_graph_hash = id_graph.hash(); - - Ok(OmniAccountIDGraph { graph: id_graph, hash: id_graph_hash }) - } - - fn get(&self, block_header: Header) -> Result { - let id_graphs_key_prefix = storage_prefix(b"OmniAccount", b"IDGraphs"); - let id_graphs_storage_keys_response = self - .ocall_api - .get_storage_keys(id_graphs_key_prefix.into()) - .map_err(|_| Error::OCallApiError("Failed to get storage keys"))?; - let id_graphs_storage_keys = id_graphs_storage_keys_response - .into_iter() - .filter_map(decode_storage_key) - .collect::>>(); - let id_graphs: IDGraphs = self - .ocall_api - .get_multiple_storages_verified( - id_graphs_storage_keys, - &block_header, - &ParentchainId::Litentry, - ) - .map_err(|_| Error::OCallApiError("Failed to get multiple storages"))? - .into_iter() - .filter_map(|entry| { - // TODO: double check this - let storage_key = decode_storage_key(entry.key)?; - let account_id: AccountId = extract_blake2_128concat_key(&storage_key)?; - let id_graph: IDGraph = entry.value?; - let id_graph_hash = id_graph.hash(); - let omni_account_id_graph = - OmniAccountIDGraph { graph: id_graph, hash: id_graph_hash }; - Some((account_id, omni_account_id_graph)) - }) - .collect(); - - Ok(id_graphs) - } -} diff --git a/tee-worker/identity/litentry/core/omni-account/src/id_graphs_store.rs b/tee-worker/identity/litentry/core/omni-account/src/id_graphs_store.rs deleted file mode 100644 index 3767c3a91a..0000000000 --- a/tee-worker/identity/litentry/core/omni-account/src/id_graphs_store.rs +++ /dev/null @@ -1,61 +0,0 @@ -use crate::{AccountId, BTreeMap, Error, IDGraphs, OmniAccountIDGraph}; -use lazy_static::lazy_static; - -#[cfg(feature = "std")] -use std::sync::RwLock; -#[cfg(feature = "sgx")] -use std::sync::SgxRwLock as RwLock; - -lazy_static! { - static ref ID_GRAPHS: RwLock = RwLock::new(BTreeMap::new()); -} - -pub struct IDGraphsStore; - -impl IDGraphsStore { - pub fn get(&self, owner: AccountId) -> Result { - let id_graph = ID_GRAPHS - .read() - .map_err(|_| { - log::error!("[IDGraphsInMemoryRepository] Lock poisoning"); - Error::LockPoisoning - })? - .get(&owner) - .cloned(); - - id_graph.ok_or(Error::NotFound) - } - - pub fn insert(&self, owner: AccountId, id_graph: OmniAccountIDGraph) -> Result<(), Error> { - ID_GRAPHS - .write() - .map_err(|_| { - log::error!("[IDGraphsInMemoryRepository] Lock poisoning"); - Error::LockPoisoning - })? - .insert(owner, id_graph); - - Ok(()) - } - - pub fn remove(&self, owner: AccountId) -> Result<(), Error> { - ID_GRAPHS - .write() - .map_err(|_| { - log::error!("[IDGraphsInMemoryRepository] Lock poisoning"); - Error::LockPoisoning - })? - .remove(&owner); - - Ok(()) - } - - pub fn load(&self, id_graphs: IDGraphs) -> Result<(), Error> { - *ID_GRAPHS.write().map_err(|_| { - log::error!("[IDGraphsInMemoryRepository] Lock poisoning"); - Error::LockPoisoning - })? = id_graphs; - - Ok(()) - } -} diff --git a/tee-worker/identity/litentry/core/omni-account/src/in_memory_store.rs b/tee-worker/identity/litentry/core/omni-account/src/in_memory_store.rs new file mode 100644 index 0000000000..eb49a948c3 --- /dev/null +++ b/tee-worker/identity/litentry/core/omni-account/src/in_memory_store.rs @@ -0,0 +1,65 @@ +use crate::{AccountId, BTreeMap, Error, OmniAccountMembers, OmniAccounts}; +use lazy_static::lazy_static; + +#[cfg(feature = "std")] +use std::sync::RwLock; +#[cfg(feature = "sgx")] +use std::sync::SgxRwLock as RwLock; + +lazy_static! { + static ref STORE: RwLock = RwLock::new(BTreeMap::new()); +} + +pub struct InMemoryStore; + +impl InMemoryStore { + pub fn get(&self, owner: AccountId) -> Result { + let id_graph = STORE + .read() + .map_err(|_| { + log::error!("[InMemoryStore] Lock poisoning"); + Error::LockPoisoning + })? + .get(&owner) + .cloned(); + + id_graph.ok_or(Error::NotFound) + } + + pub fn insert( + &self, + owner: AccountId, + omni_account_members: OmniAccountMembers, + ) -> Result<(), Error> { + STORE + .write() + .map_err(|_| { + log::error!("[InMemoryStore] Lock poisoning"); + Error::LockPoisoning + })? + .insert(owner, omni_account_members); + + Ok(()) + } + + pub fn remove(&self, owner: AccountId) -> Result<(), Error> { + STORE + .write() + .map_err(|_| { + log::error!("[InMemoryStore] Lock poisoning"); + Error::LockPoisoning + })? + .remove(&owner); + + Ok(()) + } + + pub fn load(&self, omni_accounts: OmniAccounts) -> Result<(), Error> { + *STORE.write().map_err(|_| { + log::error!("[InMemoryStore] Lock poisoning"); + Error::LockPoisoning + })? = omni_accounts; + + Ok(()) + } +} diff --git a/tee-worker/identity/litentry/core/omni-account/src/lib.rs b/tee-worker/identity/litentry/core/omni-account/src/lib.rs index 733ef7219f..cb02645316 100644 --- a/tee-worker/identity/litentry/core/omni-account/src/lib.rs +++ b/tee-worker/identity/litentry/core/omni-account/src/lib.rs @@ -24,20 +24,18 @@ extern crate sgx_tstd as std; #[cfg(all(feature = "std", feature = "sgx"))] compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the same time"); -mod id_graphs_repository; -pub use id_graphs_repository::*; +mod repository; +pub use repository::*; -mod id_graphs_store; -pub use id_graphs_store::IDGraphsStore; +mod in_memory_store; +pub use in_memory_store::InMemoryStore; use alloc::{collections::btree_map::BTreeMap, vec::Vec}; use codec::Decode; use itp_types::parentchain::{AccountId, Hash, Header, ParentchainId}; use litentry_primitives::Identity; -pub type IDGraphs = BTreeMap; - -pub type IDGraph = Vec; +pub type OmniAccounts = BTreeMap; #[derive(Debug)] pub enum Error { @@ -54,13 +52,13 @@ pub enum MemberIdentity { } #[derive(Debug, Clone, Decode)] -pub struct IDGraphMember { +pub struct MemberAccount { pub id: MemberIdentity, pub hash: Hash, } #[derive(Debug, Clone)] -pub struct OmniAccountIDGraph { - pub graph: IDGraph, +pub struct OmniAccountMembers { + pub member_accounts: Vec, pub hash: Hash, } diff --git a/tee-worker/identity/litentry/core/omni-account/src/repository.rs b/tee-worker/identity/litentry/core/omni-account/src/repository.rs new file mode 100644 index 0000000000..553e1e618c --- /dev/null +++ b/tee-worker/identity/litentry/core/omni-account/src/repository.rs @@ -0,0 +1,98 @@ +use crate::{ + AccountId, Error, Hash, Header, MemberAccount, OmniAccountMembers, OmniAccounts, ParentchainId, +}; +use alloc::vec::Vec; +use codec::Encode; +use frame_support::storage::storage_prefix; +use itp_ocall_api::EnclaveOnChainOCallApi; +use itp_storage::{ + decode_storage_key, extract_blake2_128concat_key, storage_map_key, StorageHasher, +}; +use sp_core::blake2_256; + +// TODO: get this from core_primitives after the release-v0.9.19 branch has been updated +pub trait GetAccountStoreHash { + fn hash(&self) -> Hash; +} +impl GetAccountStoreHash for Vec { + fn hash(&self) -> Hash { + let hashes: Vec = self.iter().map(|member| member.hash).collect(); + Hash::from(blake2_256(&hashes.encode())) + } +} + +pub trait GetAccountStoresRepository { + fn get_by_owner(&self, owner: AccountId) -> Result; + fn get(&self) -> Result; +} + +pub struct OmniAccountRepository { + ocall_api: OCallApi, + header: Header, +} + +impl OmniAccountRepository { + pub fn new(ocall_api: OCallApi, header: Header) -> Self { + Self { ocall_api, header } + } + + pub fn set_header(&mut self, header: Header) { + self.header = header; + } +} + +impl GetAccountStoresRepository + for OmniAccountRepository +{ + fn get_by_owner(&self, owner: AccountId) -> Result { + let storage_key = storage_map_key( + "OmniAccount", + "AccountStore", + &owner, + &StorageHasher::Blake2_128Concat, + ); + let storage_entry = self + .ocall_api + .get_storage_verified(storage_key, &self.header, &ParentchainId::Litentry) + .map_err(|_| Error::OCallApiError("Failed to get storage"))?; + let member_accounts: Vec = + storage_entry.value().to_owned().ok_or(Error::NotFound)?; + let account_store_hash = member_accounts.hash(); + + Ok(OmniAccountMembers { member_accounts, hash: account_store_hash }) + } + + fn get(&self) -> Result { + let account_store_key_prefix = storage_prefix(b"OmniAccount", b"AccountStore"); + let account_store_storage_keys_response = self + .ocall_api + .get_storage_keys(account_store_key_prefix.into()) + .map_err(|_| Error::OCallApiError("Failed to get storage keys"))?; + let account_store_storage_keys = account_store_storage_keys_response + .into_iter() + .filter_map(decode_storage_key) + .collect::>>(); + let omni_accounts: OmniAccounts = self + .ocall_api + .get_multiple_storages_verified( + account_store_storage_keys, + &self.header, + &ParentchainId::Litentry, + ) + .map_err(|_| Error::OCallApiError("Failed to get multiple storages"))? + .into_iter() + .filter_map(|entry| { + // TODO: double check this + let storage_key = decode_storage_key(entry.key)?; + let account_id: AccountId = extract_blake2_128concat_key(&storage_key)?; + let member_accounts: Vec = entry.value?; + let account_store_hash = member_accounts.hash(); + let omni_account_members = + OmniAccountMembers { member_accounts, hash: account_store_hash }; + Some((account_id, omni_account_members)) + }) + .collect(); + + Ok(omni_accounts) + } +} From 252e337a47598f9764e2e31d541da44213df0474 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Tue, 8 Oct 2024 13:31:08 +0000 Subject: [PATCH 12/39] fixing fmt issues --- parachain/pallets/omni-account/src/lib.rs | 1 - parachain/pallets/omni-account/src/tests.rs | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/parachain/pallets/omni-account/src/lib.rs b/parachain/pallets/omni-account/src/lib.rs index 99854478ea..1d97ec396c 100644 --- a/parachain/pallets/omni-account/src/lib.rs +++ b/parachain/pallets/omni-account/src/lib.rs @@ -370,4 +370,3 @@ impl, O>> + From>, Acco Ok(O::from(RawOrigin::OmniAccount(zero_account_id))) } } - diff --git a/parachain/pallets/omni-account/src/tests.rs b/parachain/pallets/omni-account/src/tests.rs index 89a8520560..3591d48fb0 100644 --- a/parachain/pallets/omni-account/src/tests.rs +++ b/parachain/pallets/omni-account/src/tests.rs @@ -17,9 +17,9 @@ use crate::{mock::*, AccountStore, MemberAccountHash, *}; use core_primitives::Identity; use frame_support::{assert_noop, assert_ok}; +use sp_core_hashing::blake2_256; use sp_runtime::{traits::BadOrigin, ModuleError}; use sp_std::vec; -use sp_core_hashing::blake2_256; fn remove_accounts_call(hashes: Vec) -> Box { let call = From 190dfb0ae2b444be014e9d83e3ab0f951b392f57 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Tue, 8 Oct 2024 14:05:29 +0000 Subject: [PATCH 13/39] fixing taplo issues --- tee-worker/common/core-primitives/stf-interface/Cargo.toml | 4 ++-- tee-worker/identity/app-libs/stf/Cargo.toml | 4 ++-- tee-worker/identity/core-primitives/stf-executor/Cargo.toml | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/tee-worker/common/core-primitives/stf-interface/Cargo.toml b/tee-worker/common/core-primitives/stf-interface/Cargo.toml index bd3cddfbf5..510df17f9c 100644 --- a/tee-worker/common/core-primitives/stf-interface/Cargo.toml +++ b/tee-worker/common/core-primitives/stf-interface/Cargo.toml @@ -9,10 +9,10 @@ codec = { package = "parity-scale-codec", workspace = true } itp-node-api-metadata = { workspace = true, features = ["mocks"] } itp-node-api-metadata-provider = { workspace = true } -itp-stf-primitives = { workspace = true } -itp-types = { workspace = true } itp-ocall-api = { workspace = true } itp-sgx-crypto = { workspace = true } +itp-stf-primitives = { workspace = true } +itp-types = { workspace = true } sp-runtime = { workspace = true } diff --git a/tee-worker/identity/app-libs/stf/Cargo.toml b/tee-worker/identity/app-libs/stf/Cargo.toml index 5926804de1..13af43351b 100644 --- a/tee-worker/identity/app-libs/stf/Cargo.toml +++ b/tee-worker/identity/app-libs/stf/Cargo.toml @@ -17,14 +17,14 @@ sgx_tstd = { workspace = true, features = ["untrusted_fs", "net", "backtrace"], itp-hashing = { workspace = true } itp-node-api = { workspace = true } itp-node-api-metadata = { workspace = true } +itp-ocall-api = { workspace = true } +itp-sgx-crypto = { workspace = true } itp-sgx-externalities = { workspace = true } itp-stf-interface = { workspace = true } itp-stf-primitives = { workspace = true } itp-storage = { workspace = true } itp-types = { workspace = true } itp-utils = { workspace = true } -itp-ocall-api = { workspace = true } -itp-sgx-crypto = { workspace = true } ita-sgx-runtime = { package = "id-ita-sgx-runtime", path = "../sgx-runtime", default-features = false } sp-io = { path = "../../../common/core-primitives/substrate-sgx/sp-io", default-features = false, features = ["disable_oom", "disable_panic_handler", "disable_allocator"] } diff --git a/tee-worker/identity/core-primitives/stf-executor/Cargo.toml b/tee-worker/identity/core-primitives/stf-executor/Cargo.toml index 21d5576966..260edbdd5d 100644 --- a/tee-worker/identity/core-primitives/stf-executor/Cargo.toml +++ b/tee-worker/identity/core-primitives/stf-executor/Cargo.toml @@ -15,13 +15,13 @@ itp-node-api = { workspace = true } itp-ocall-api = { workspace = true } itp-sgx-crypto = { workspace = true } itp-sgx-externalities = { workspace = true } +itp-sgx-io = { workspace = true } itp-stf-interface = { workspace = true } itp-stf-primitives = { workspace = true } itp-stf-state-handler = { workspace = true } itp-stf-state-observer = { workspace = true } itp-time-utils = { workspace = true } itp-types = { workspace = true } -itp-sgx-io = { workspace = true } itp-top-pool-author = { package = "id-itp-top-pool-author", path = "../top-pool-author", default-features = false } From dddd1271778643caed6156b8f8d2505ca44d9dc4 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Tue, 8 Oct 2024 15:10:48 +0000 Subject: [PATCH 14/39] fixing core primitives dependencies --- common/primitives/core/Cargo.toml | 3 ++- common/primitives/core/src/omni_account.rs | 2 +- parachain/Cargo.lock | 1 + 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/common/primitives/core/Cargo.toml b/common/primitives/core/Cargo.toml index b500fd95fd..2512c75747 100644 --- a/common/primitives/core/Cargo.toml +++ b/common/primitives/core/Cargo.toml @@ -13,7 +13,8 @@ strum_macros = { version = "0.26", default-features = false } frame-support = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } pallet-evm = { git = "https://github.com/paritytech/frontier", branch = "polkadot-v1.1.0", default-features = false } scale-info = { version = "2.11", default-features = false, features = ["derive"] } -sp-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false, features = ["full_crypto"] } +sp-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } +sp-core-hashing = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } sp-io = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } diff --git a/common/primitives/core/src/omni_account.rs b/common/primitives/core/src/omni_account.rs index 93cf3222a2..514ae890c5 100644 --- a/common/primitives/core/src/omni_account.rs +++ b/common/primitives/core/src/omni_account.rs @@ -1,7 +1,7 @@ use crate::{Hash, Identity, Vec}; use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; -use sp_core::blake2_256; +use sp_core_hashing::blake2_256; use sp_runtime::{BoundedVec, RuntimeDebug}; #[derive(Encode, Decode, TypeInfo, Clone, PartialEq, Eq, RuntimeDebug)] diff --git a/parachain/Cargo.lock b/parachain/Cargo.lock index dfde196e33..8908592a6d 100644 --- a/parachain/Cargo.lock +++ b/parachain/Cargo.lock @@ -1448,6 +1448,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", + "sp-core-hashing", "sp-io", "sp-runtime", "strum 0.26.3", From 597379d4f0bb649a401fa1dd4d3a3e61b694da1e Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 9 Oct 2024 08:11:39 +0000 Subject: [PATCH 15/39] updating litentry_primitives and importing new types directly --- tee-worker/Cargo.lock | 13 ++++----- .../common/litentry/primitives/src/lib.rs | 1 + .../identity/enclave-runtime/Cargo.lock | 13 ++++----- .../litentry/core/omni-account/src/lib.rs | 27 +++++-------------- .../core/omni-account/src/repository.rs | 16 ++--------- 5 files changed, 24 insertions(+), 46 deletions(-) diff --git a/tee-worker/Cargo.lock b/tee-worker/Cargo.lock index a36af346eb..90541e7035 100644 --- a/tee-worker/Cargo.lock +++ b/tee-worker/Cargo.lock @@ -1455,7 +1455,7 @@ checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa" [[package]] name = "core-primitives" version = "0.1.0" -source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#cdbe9b02c1c58ca3d0063bf2eaf26a1f9da314e9" +source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#84afa8035ad15a50b57ec9f7d3845d03bc9a426b" dependencies = [ "base58", "frame-support", @@ -1466,6 +1466,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", + "sp-core-hashing 5.0.0", "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", @@ -5617,7 +5618,7 @@ dependencies = [ [[package]] name = "litentry-hex-utils" version = "0.1.0" -source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#cdbe9b02c1c58ca3d0063bf2eaf26a1f9da314e9" +source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#84afa8035ad15a50b57ec9f7d3845d03bc9a426b" dependencies = [ "hex", ] @@ -5629,7 +5630,7 @@ version = "0.1.0" [[package]] name = "litentry-macros" version = "0.1.0" -source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#cdbe9b02c1c58ca3d0063bf2eaf26a1f9da314e9" +source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#84afa8035ad15a50b57ec9f7d3845d03bc9a426b" [[package]] name = "litentry-primitives" @@ -5660,7 +5661,7 @@ dependencies = [ [[package]] name = "litentry-proc-macros" version = "0.1.0" -source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#cdbe9b02c1c58ca3d0063bf2eaf26a1f9da314e9" +source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#84afa8035ad15a50b57ec9f7d3845d03bc9a426b" dependencies = [ "cargo_toml", "proc-macro2", @@ -6681,7 +6682,7 @@ dependencies = [ [[package]] name = "pallet-parachain-staking" version = "0.1.0" -source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#cdbe9b02c1c58ca3d0063bf2eaf26a1f9da314e9" +source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#84afa8035ad15a50b57ec9f7d3845d03bc9a426b" dependencies = [ "core-primitives", "frame-support", @@ -6751,7 +6752,7 @@ dependencies = [ [[package]] name = "pallet-teebag" version = "0.1.0" -source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#cdbe9b02c1c58ca3d0063bf2eaf26a1f9da314e9" +source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#84afa8035ad15a50b57ec9f7d3845d03bc9a426b" dependencies = [ "base64 0.13.1", "chrono 0.4.26", diff --git a/tee-worker/common/litentry/primitives/src/lib.rs b/tee-worker/common/litentry/primitives/src/lib.rs index 2a14a12b82..bfd7777e1c 100644 --- a/tee-worker/common/litentry/primitives/src/lib.rs +++ b/tee-worker/common/litentry/primitives/src/lib.rs @@ -75,6 +75,7 @@ pub use parentchain_primitives::{ Assertion, }, identity::*, + omni_account::*, AccountId as ParentchainAccountId, Balance as ParentchainBalance, BlockNumber as ParentchainBlockNumber, ErrorDetail, ErrorString, Hash as ParentchainHash, Header as ParentchainHeader, IMPError, Index as ParentchainIndex, IntoErrorDetail, diff --git a/tee-worker/identity/enclave-runtime/Cargo.lock b/tee-worker/identity/enclave-runtime/Cargo.lock index 2ce0cd3fbc..6db2c0ed82 100644 --- a/tee-worker/identity/enclave-runtime/Cargo.lock +++ b/tee-worker/identity/enclave-runtime/Cargo.lock @@ -612,7 +612,7 @@ checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" [[package]] name = "core-primitives" version = "0.1.0" -source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#cdbe9b02c1c58ca3d0063bf2eaf26a1f9da314e9" +source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#84afa8035ad15a50b57ec9f7d3845d03bc9a426b" dependencies = [ "base58", "frame-support", @@ -623,6 +623,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", + "sp-core-hashing", "sp-io", "sp-runtime", "sp-std", @@ -3386,7 +3387,7 @@ dependencies = [ [[package]] name = "litentry-hex-utils" version = "0.1.0" -source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#cdbe9b02c1c58ca3d0063bf2eaf26a1f9da314e9" +source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#84afa8035ad15a50b57ec9f7d3845d03bc9a426b" dependencies = [ "hex", ] @@ -3398,7 +3399,7 @@ version = "0.1.0" [[package]] name = "litentry-macros" version = "0.1.0" -source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#cdbe9b02c1c58ca3d0063bf2eaf26a1f9da314e9" +source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#84afa8035ad15a50b57ec9f7d3845d03bc9a426b" [[package]] name = "litentry-primitives" @@ -3437,7 +3438,7 @@ dependencies = [ [[package]] name = "litentry-proc-macros" version = "0.1.0" -source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#cdbe9b02c1c58ca3d0063bf2eaf26a1f9da314e9" +source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#84afa8035ad15a50b57ec9f7d3845d03bc9a426b" dependencies = [ "cargo_toml", "proc-macro2", @@ -3830,7 +3831,7 @@ dependencies = [ [[package]] name = "pallet-parachain-staking" version = "0.1.0" -source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#cdbe9b02c1c58ca3d0063bf2eaf26a1f9da314e9" +source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#84afa8035ad15a50b57ec9f7d3845d03bc9a426b" dependencies = [ "core-primitives", "frame-support", @@ -3897,7 +3898,7 @@ dependencies = [ [[package]] name = "pallet-teebag" version = "0.1.0" -source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#cdbe9b02c1c58ca3d0063bf2eaf26a1f9da314e9" +source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#84afa8035ad15a50b57ec9f7d3845d03bc9a426b" dependencies = [ "base64 0.13.1", "chrono 0.4.31", diff --git a/tee-worker/identity/litentry/core/omni-account/src/lib.rs b/tee-worker/identity/litentry/core/omni-account/src/lib.rs index cb02645316..ed007affc8 100644 --- a/tee-worker/identity/litentry/core/omni-account/src/lib.rs +++ b/tee-worker/identity/litentry/core/omni-account/src/lib.rs @@ -33,32 +33,19 @@ pub use in_memory_store::InMemoryStore; use alloc::{collections::btree_map::BTreeMap, vec::Vec}; use codec::Decode; use itp_types::parentchain::{AccountId, Hash, Header, ParentchainId}; -use litentry_primitives::Identity; +use litentry_primitives::MemberAccount; pub type OmniAccounts = BTreeMap; +#[derive(Debug, Clone)] +pub struct OmniAccountMembers { + pub member_accounts: Vec, + pub hash: Hash, +} + #[derive(Debug)] pub enum Error { LockPoisoning, NotFound, OCallApiError(&'static str), } - -// TODO: get this from core_primitives after the release-v0.9.19 branch has been updated -#[derive(Debug, Clone, Decode)] -pub enum MemberIdentity { - Public(Identity), - Private(Vec), -} - -#[derive(Debug, Clone, Decode)] -pub struct MemberAccount { - pub id: MemberIdentity, - pub hash: Hash, -} - -#[derive(Debug, Clone)] -pub struct OmniAccountMembers { - pub member_accounts: Vec, - pub hash: Hash, -} diff --git a/tee-worker/identity/litentry/core/omni-account/src/repository.rs b/tee-worker/identity/litentry/core/omni-account/src/repository.rs index 553e1e618c..b2d51e2ca8 100644 --- a/tee-worker/identity/litentry/core/omni-account/src/repository.rs +++ b/tee-worker/identity/litentry/core/omni-account/src/repository.rs @@ -1,6 +1,4 @@ -use crate::{ - AccountId, Error, Hash, Header, MemberAccount, OmniAccountMembers, OmniAccounts, ParentchainId, -}; +use crate::{AccountId, Error, Hash, Header, OmniAccountMembers, OmniAccounts, ParentchainId}; use alloc::vec::Vec; use codec::Encode; use frame_support::storage::storage_prefix; @@ -8,19 +6,9 @@ use itp_ocall_api::EnclaveOnChainOCallApi; use itp_storage::{ decode_storage_key, extract_blake2_128concat_key, storage_map_key, StorageHasher, }; +use litentry_primitives::{GetAccountStoreHash, MemberAccount}; use sp_core::blake2_256; -// TODO: get this from core_primitives after the release-v0.9.19 branch has been updated -pub trait GetAccountStoreHash { - fn hash(&self) -> Hash; -} -impl GetAccountStoreHash for Vec { - fn hash(&self) -> Hash { - let hashes: Vec = self.iter().map(|member| member.hash).collect(); - Hash::from(blake2_256(&hashes.encode())) - } -} - pub trait GetAccountStoresRepository { fn get_by_owner(&self, owner: AccountId) -> Result; fn get(&self) -> Result; From 45cb0ee6874c74b33d72eb8cf84080277388a0e5 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 9 Oct 2024 08:14:13 +0000 Subject: [PATCH 16/39] refactoring name --- .../litentry/core/omni-account/src/in_memory_store.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tee-worker/identity/litentry/core/omni-account/src/in_memory_store.rs b/tee-worker/identity/litentry/core/omni-account/src/in_memory_store.rs index eb49a948c3..4a8483e957 100644 --- a/tee-worker/identity/litentry/core/omni-account/src/in_memory_store.rs +++ b/tee-worker/identity/litentry/core/omni-account/src/in_memory_store.rs @@ -14,7 +14,7 @@ pub struct InMemoryStore; impl InMemoryStore { pub fn get(&self, owner: AccountId) -> Result { - let id_graph = STORE + let omni_account_members = STORE .read() .map_err(|_| { log::error!("[InMemoryStore] Lock poisoning"); @@ -23,7 +23,7 @@ impl InMemoryStore { .get(&owner) .cloned(); - id_graph.ok_or(Error::NotFound) + omni_account_members.ok_or(Error::NotFound) } pub fn insert( From 14e8e0dfd6dcaa28e48ff8febc71755c1742b813 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 9 Oct 2024 08:28:30 +0000 Subject: [PATCH 17/39] cleaning up unused dependencies --- tee-worker/Cargo.lock | 1 - tee-worker/identity/litentry/core/omni-account/Cargo.toml | 3 +-- tee-worker/identity/litentry/core/omni-account/src/lib.rs | 1 - .../identity/litentry/core/omni-account/src/repository.rs | 4 +--- 4 files changed, 2 insertions(+), 7 deletions(-) diff --git a/tee-worker/Cargo.lock b/tee-worker/Cargo.lock index 90541e7035..c7e160cbd1 100644 --- a/tee-worker/Cargo.lock +++ b/tee-worker/Cargo.lock @@ -5274,7 +5274,6 @@ dependencies = [ "lazy_static", "litentry-primitives", "log 0.4.20", - "parity-scale-codec", "sgx_tstd", "sp-core", ] diff --git a/tee-worker/identity/litentry/core/omni-account/Cargo.toml b/tee-worker/identity/litentry/core/omni-account/Cargo.toml index b8211e06f1..0b36e26d6e 100644 --- a/tee-worker/identity/litentry/core/omni-account/Cargo.toml +++ b/tee-worker/identity/litentry/core/omni-account/Cargo.toml @@ -11,11 +11,10 @@ itp-ocall-api = { workspace = true } itp-storage = { workspace = true } itp-types = { workspace = true } -codec = { package = "parity-scale-codec", workspace = true } frame-support = { workspace = true } lazy_static = { workspace = true } log = { workspace = true } -sp-core = { workspace = true, features = ["full_crypto"] } +sp-core = { workspace = true } sgx_tstd = { workspace = true, features = ["net", "thread"], optional = true } diff --git a/tee-worker/identity/litentry/core/omni-account/src/lib.rs b/tee-worker/identity/litentry/core/omni-account/src/lib.rs index ed007affc8..ba7b84afe8 100644 --- a/tee-worker/identity/litentry/core/omni-account/src/lib.rs +++ b/tee-worker/identity/litentry/core/omni-account/src/lib.rs @@ -31,7 +31,6 @@ mod in_memory_store; pub use in_memory_store::InMemoryStore; use alloc::{collections::btree_map::BTreeMap, vec::Vec}; -use codec::Decode; use itp_types::parentchain::{AccountId, Hash, Header, ParentchainId}; use litentry_primitives::MemberAccount; diff --git a/tee-worker/identity/litentry/core/omni-account/src/repository.rs b/tee-worker/identity/litentry/core/omni-account/src/repository.rs index b2d51e2ca8..49ef4b2be1 100644 --- a/tee-worker/identity/litentry/core/omni-account/src/repository.rs +++ b/tee-worker/identity/litentry/core/omni-account/src/repository.rs @@ -1,13 +1,11 @@ -use crate::{AccountId, Error, Hash, Header, OmniAccountMembers, OmniAccounts, ParentchainId}; +use crate::{AccountId, Error, Header, OmniAccountMembers, OmniAccounts, ParentchainId}; use alloc::vec::Vec; -use codec::Encode; use frame_support::storage::storage_prefix; use itp_ocall_api::EnclaveOnChainOCallApi; use itp_storage::{ decode_storage_key, extract_blake2_128concat_key, storage_map_key, StorageHasher, }; use litentry_primitives::{GetAccountStoreHash, MemberAccount}; -use sp_core::blake2_256; pub trait GetAccountStoresRepository { fn get_by_owner(&self, owner: AccountId) -> Result; From e62f5c9ab7e08eeebb220eb23a7ffa91d6ea7b67 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 9 Oct 2024 08:30:15 +0000 Subject: [PATCH 18/39] fix: allow clippy::too_many_arguments lint --- tee-worker/common/core-primitives/stf-interface/src/lib.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tee-worker/common/core-primitives/stf-interface/src/lib.rs b/tee-worker/common/core-primitives/stf-interface/src/lib.rs index 40692790c7..c57f352f41 100644 --- a/tee-worker/common/core-primitives/stf-interface/src/lib.rs +++ b/tee-worker/common/core-primitives/stf-interface/src/lib.rs @@ -90,7 +90,7 @@ pub trait StateCallInterface< /// 1. add a parameter to pass the top_hash around /// 2. returns the encoded rpc response value field that should be passed /// back to the requester when the call is triggered synchronously - // #[allow(clippy::too_many_arguments)] + #[allow(clippy::too_many_arguments)] fn execute_call( state: &mut State, shard: &ShardIdentifier, @@ -126,6 +126,7 @@ where /// /// Litentry: returns the encoded rpc response that should be passed back to /// the requester when the call is triggered synchronously + #[allow(clippy::too_many_arguments)] fn execute( self, shard: &ShardIdentifier, From 12cb3051cb97f852d07119154cf0891fcba21ee6 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 9 Oct 2024 10:10:19 +0000 Subject: [PATCH 19/39] updating comment --- .../identity/core-primitives/stf-executor/src/executor_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tee-worker/identity/core-primitives/stf-executor/src/executor_tests.rs b/tee-worker/identity/core-primitives/stf-executor/src/executor_tests.rs index b4249d5e49..cdf6be930e 100644 --- a/tee-worker/identity/core-primitives/stf-executor/src/executor_tests.rs +++ b/tee-worker/identity/core-primitives/stf-executor/src/executor_tests.rs @@ -18,9 +18,9 @@ use crate::{executor::StfExecutor, traits::StateUpdateProposer}; use codec::Encode; use itc_parentchain_test::ParentchainHeaderBuilder; -// TODO: use Aes256 when available use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; use itp_ocall_api::EnclaveAttestationOCallApi; +// TODO: use Aes256 when available use itp_sgx_crypto::{mocks::KeyRepositoryMock, Aes}; use itp_sgx_externalities::{SgxExternalities as State, SgxExternalitiesTrait}; use itp_sgx_io::SealedIO; From ad058bbd33ad67cff3d659e5547e7b33eac35d9a Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 9 Oct 2024 10:10:37 +0000 Subject: [PATCH 20/39] updating bitacross executor types --- tee-worker/Cargo.lock | 2 + tee-worker/bitacross/app-libs/stf/Cargo.toml | 4 + .../bitacross/app-libs/stf/src/stf_sgx.rs | 45 +++- .../app-libs/stf/src/stf_sgx_tests.rs | 16 +- .../app-libs/stf/src/trusted_call.rs | 15 +- .../stf-executor/src/executor.rs | 199 ++++++++++++++---- .../stf-executor/src/executor_tests.rs | 14 +- .../core-primitives/stf-executor/src/mocks.rs | 6 +- .../stf-executor/src/traits.rs | 6 +- .../offchain-worker-executor/src/executor.rs | 14 +- .../bitacross/enclave-runtime/Cargo.lock | 17 +- .../src/initialization/global_components.rs | 8 +- .../parentchain/integritee_parachain.rs | 14 +- .../parentchain/integritee_solochain.rs | 14 +- .../parentchain/target_a_parachain.rs | 18 +- .../parentchain/target_a_solochain.rs | 18 +- .../parentchain/target_b_parachain.rs | 18 +- .../parentchain/target_b_solochain.rs | 18 +- .../src/test/enclave_signer_tests.rs | 23 +- .../src/test/fixtures/test_setup.rs | 18 +- .../enclave-runtime/src/test/mocks/types.rs | 7 +- .../enclave-runtime/src/test/tests_main.rs | 40 +++- 22 files changed, 426 insertions(+), 108 deletions(-) diff --git a/tee-worker/Cargo.lock b/tee-worker/Cargo.lock index c7e160cbd1..d22045684d 100644 --- a/tee-worker/Cargo.lock +++ b/tee-worker/Cargo.lock @@ -445,6 +445,8 @@ dependencies = [ "hex-literal", "itp-hashing", "itp-node-api", + "itp-ocall-api", + "itp-sgx-crypto", "itp-sgx-externalities", "itp-stf-interface", "itp-stf-primitives", diff --git a/tee-worker/bitacross/app-libs/stf/Cargo.toml b/tee-worker/bitacross/app-libs/stf/Cargo.toml index d3016c539c..dabc854784 100644 --- a/tee-worker/bitacross/app-libs/stf/Cargo.toml +++ b/tee-worker/bitacross/app-libs/stf/Cargo.toml @@ -15,6 +15,8 @@ sgx_tstd = { workspace = true, features = ["untrusted_fs", "net", "backtrace"], itp-hashing = { workspace = true } itp-node-api = { workspace = true } itp-sgx-externalities = { workspace = true } +itp-ocall-api = { workspace = true } +itp-sgx-crypto = { workspace = true } itp-stf-interface = { workspace = true } itp-stf-primitives = { workspace = true } itp-storage = { workspace = true } @@ -47,6 +49,7 @@ sgx = [ "sp-io/sgx", "itp-node-api/sgx", "litentry-primitives/sgx", + "itp-sgx-crypto/sgx", ] std = [ # crates.io @@ -68,6 +71,7 @@ std = [ "pallet-parentchain/std", "sp-io/std", "litentry-primitives/std", + "itp-sgx-crypto/std", ] test = [] development = [ diff --git a/tee-worker/bitacross/app-libs/stf/src/stf_sgx.rs b/tee-worker/bitacross/app-libs/stf/src/stf_sgx.rs index 6412b5cf78..cbdc572c9c 100644 --- a/tee-worker/bitacross/app-libs/stf/src/stf_sgx.rs +++ b/tee-worker/bitacross/app-libs/stf/src/stf_sgx.rs @@ -27,6 +27,9 @@ use ita_sgx_runtime::{ Executive, ParentchainInstanceLitentry, ParentchainInstanceTargetA, ParentchainInstanceTargetB, }; use itp_node_api::metadata::{provider::AccessNodeMetadata, NodeMetadataTrait}; +use itp_ocall_api::EnclaveOnChainOCallApi; +// TODO: use use Aes256 when available +use itp_sgx_crypto::{key_repository::AccessKey, Aes}; use itp_sgx_externalities::SgxExternalitiesTrait; use itp_stf_interface::{ parentchain_pallet::ParentchainPalletInstancesInterface, @@ -46,7 +49,7 @@ use itp_types::{ }; use itp_utils::stringify::account_id_to_string; use log::*; -use sp_runtime::traits::StaticLookup; +use sp_runtime::traits::{Header as HeaderTrait, StaticLookup}; use std::{fmt::Debug, format, prelude::v1::*, sync::Arc, vec}; impl InitState for Stf @@ -135,11 +138,27 @@ where } } -impl - StateCallInterface for Stf +impl< + TCS, + G, + State, + Runtime, + NodeMetadataRepository, + OCallApi, + PH, + OnChainEncryptionKeyRepository, + > + StateCallInterface< + TCS, + State, + NodeMetadataRepository, + OCallApi, + PH, + OnChainEncryptionKeyRepository, + > for Stf where TCS: PartialEq - + ExecuteCall + + ExecuteCall + Encode + Decode + Debug @@ -150,6 +169,9 @@ where State: SgxExternalitiesTrait + Debug, NodeMetadataRepository: AccessNodeMetadata, NodeMetadataRepository::MetadataType: NodeMetadataTrait, + OCallApi: EnclaveOnChainOCallApi, + PH: HeaderTrait, + OnChainEncryptionKeyRepository: AccessKey, { type Error = TCS::Error; type Result = TCS::Result; @@ -161,8 +183,21 @@ where top_hash: H256, calls: &mut Vec, node_metadata_repo: Arc, + ocall_api: Arc, + parentchain_header: &PH, + on_chain_encryption_key_repo: Arc, ) -> Result { - state.execute_with(|| call.execute(shard, top_hash, calls, node_metadata_repo)) + state.execute_with(|| { + call.execute( + shard, + top_hash, + calls, + node_metadata_repo, + ocall_api, + parentchain_header, + on_chain_encryption_key_repo, + ) + }) } } diff --git a/tee-worker/bitacross/app-libs/stf/src/stf_sgx_tests.rs b/tee-worker/bitacross/app-libs/stf/src/stf_sgx_tests.rs index 479f3b9bb0..89feb2d132 100644 --- a/tee-worker/bitacross/app-libs/stf/src/stf_sgx_tests.rs +++ b/tee-worker/bitacross/app-libs/stf/src/stf_sgx_tests.rs @@ -18,21 +18,30 @@ use crate::{Getter, State, Stf, TrustedCall, TrustedCallSigned}; use ita_sgx_runtime::Runtime; use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; +use itp_ocall_api::mock::OnchainMock; +use itp_sgx_crypto::{key_repository::AccessKey, mocks::KeyRepositoryMock, Aes}; use itp_stf_interface::{ sudo_pallet::SudoPalletInterface, system_pallet::SystemPalletAccountInterface, InitState, StateCallInterface, }; use itp_stf_primitives::types::{AccountId, ShardIdentifier}; -use itp_types::parentchain::ParentchainId; +use itp_types::{parentchain::ParentchainId, Header}; use litentry_primitives::LitentryMultiSignature; use sp_core::{ ed25519::{Pair as Ed25519Pair, Signature as Ed25519Signature}, Pair, }; +use sp_runtime::traits::Header as HeaderTrait; use std::{sync::Arc, vec::Vec}; +type EncryptionKeyRepositoryMock = KeyRepositoryMock; + pub type StfState = Stf; +pub fn latest_parentchain_header() -> Header { + Header::new(1, Default::default(), Default::default(), [69; 32].into(), Default::default()) +} + pub fn enclave_account_initialization_works() { let enclave_account = AccountId::new([2u8; 32]); let mut state = StfState::init_state(enclave_account.clone()); @@ -48,6 +57,7 @@ pub fn shield_funds_increments_signer_account_nonce() { let enclave_call_signer = Ed25519Pair::from_seed(b"14672678901234567890123456789012"); let enclave_signer_account_id: AccountId = enclave_call_signer.public().into(); let mut state = StfState::init_state(enclave_signer_account_id.clone()); + let ocall_api = Arc::new(OnchainMock::default()); let shield_funds_call = TrustedCallSigned::new( TrustedCall::balance_shield( @@ -62,6 +72,7 @@ pub fn shield_funds_increments_signer_account_nonce() { let repo = Arc::new(NodeMetadataRepository::new(NodeMetadataMock::new())); let shard = ShardIdentifier::default(); + let encryption_key_repository = Arc::new(EncryptionKeyRepositoryMock::new(Aes::default())); StfState::execute_call( &mut state, &shard, @@ -69,6 +80,9 @@ pub fn shield_funds_increments_signer_account_nonce() { Default::default(), &mut Vec::new(), repo, + ocall_api.clone(), + &latest_parentchain_header(), + encryption_key_repository.clone(), ) .unwrap(); assert_eq!(1, StfState::get_account_nonce(&mut state, &enclave_signer_account_id)); diff --git a/tee-worker/bitacross/app-libs/stf/src/trusted_call.rs b/tee-worker/bitacross/app-libs/stf/src/trusted_call.rs index 8d8167d46b..003f1e005e 100644 --- a/tee-worker/bitacross/app-libs/stf/src/trusted_call.rs +++ b/tee-worker/bitacross/app-libs/stf/src/trusted_call.rs @@ -24,6 +24,9 @@ use codec::{Decode, Encode}; use frame_support::{ensure, traits::UnfilteredDispatchable}; pub use ita_sgx_runtime::{Balance, Index, Runtime, System}; use itp_node_api::metadata::{provider::AccessNodeMetadata, NodeMetadataTrait}; +use itp_ocall_api::EnclaveOnChainOCallApi; +// TODO: use use Aes256 when available +use itp_sgx_crypto::{key_repository::AccessKey, Aes}; use itp_stf_interface::ExecuteCall; use itp_stf_primitives::{ @@ -46,7 +49,7 @@ use sp_core::{ ed25519, }; use sp_io::hashing::blake2_256; -use sp_runtime::MultiAddress; +use sp_runtime::{traits::Header as HeaderTrait, MultiAddress}; use std::{format, prelude::v1::*, sync::Arc}; #[derive(Encode, Decode, Clone, Debug, PartialEq, Eq)] @@ -156,10 +159,15 @@ impl TrustedCallVerification for TrustedCallSigned { } } -impl ExecuteCall for TrustedCallSigned +impl + ExecuteCall + for TrustedCallSigned where NodeMetadataRepository: AccessNodeMetadata, NodeMetadataRepository::MetadataType: NodeMetadataTrait, + OCallApi: EnclaveOnChainOCallApi, + PH: HeaderTrait, + OnChainEncryptionKeyRepository: AccessKey, { type Error = StfError; type Result = TrustedCallResult; @@ -203,6 +211,9 @@ where _top_hash: H256, _calls: &mut Vec, _node_metadata_repo: Arc, + _ocall_api: Arc, + _parentchain_header: &PH, + _on_chain_encryption_key_repo: Arc, ) -> Result { let sender = self.call.sender_identity().clone(); let account_id: AccountId = sender.to_account_id().ok_or(Self::Error::InvalidAccount)?; diff --git a/tee-worker/bitacross/core-primitives/stf-executor/src/executor.rs b/tee-worker/bitacross/core-primitives/stf-executor/src/executor.rs index ffc6d92fce..80e15e4742 100644 --- a/tee-worker/bitacross/core-primitives/stf-executor/src/executor.rs +++ b/tee-worker/bitacross/core-primitives/stf-executor/src/executor.rs @@ -24,6 +24,8 @@ use codec::{Decode, Encode}; use itp_enclave_metrics::EnclaveMetric; use itp_node_api::metadata::{provider::AccessNodeMetadata, NodeMetadataTrait}; use itp_ocall_api::{EnclaveAttestationOCallApi, EnclaveMetricsOCallApi, EnclaveOnChainOCallApi}; +// TODO: use Aes256 when available +use itp_sgx_crypto::{key_repository::AccessKey, Aes}; use itp_sgx_externalities::{SgxExternalitiesTrait, StateHash}; use itp_stf_interface::{ parentchain_pallet::ParentchainPalletInstancesInterface, @@ -36,7 +38,7 @@ use itp_stf_primitives::{ use itp_stf_state_handler::{handle_state::HandleState, query_shard_state::QueryShardState}; use itp_time_utils::duration_now; use itp_types::{ - parentchain::{Header as ParentchainHeader, ParentchainCall, ParentchainId}, + parentchain::{ParentchainCall, ParentchainId}, storage::StorageEntryVerified, H256, }; @@ -47,20 +49,46 @@ use std::{ time::Duration, vec, vec::Vec, }; -pub struct StfExecutor -where +pub struct StfExecutor< + OCallApi, + StateHandler, + NodeMetadataRepository, + Stf, + TCS, + G, + PH, + OnChainEncryptionKeyRepository, +> where TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, { ocall_api: Arc, state_handler: Arc, node_metadata_repo: Arc, - _phantom: PhantomData<(Stf, TCS, G)>, + on_chain_encryption_key_repository: Arc, + _phantom: PhantomData<(Stf, TCS, G, PH)>, } -impl - StfExecutor -where +impl< + OCallApi, + StateHandler, + NodeMetadataRepository, + Stf, + TCS, + G, + PH, + OnChainEncryptionKeyRepository, + > + StfExecutor< + OCallApi, + StateHandler, + NodeMetadataRepository, + Stf, + TCS, + G, + PH, + OnChainEncryptionKeyRepository, + > where OCallApi: EnclaveAttestationOCallApi + EnclaveOnChainOCallApi + EnclaveMetricsOCallApi, StateHandler: HandleState, StateHandler::StateT: SgxExternalitiesTrait + Encode, @@ -69,19 +97,42 @@ where Stf: UpdateState< StateHandler::StateT, ::SgxExternalitiesDiffType, - > + StateCallInterface, + > + StateCallInterface< + TCS, + StateHandler::StateT, + NodeMetadataRepository, + OCallApi, + PH, + OnChainEncryptionKeyRepository, + >, ::SgxExternalitiesDiffType: IntoIterator, Option>)> + From, Option>>>, - >::Error: Debug, + >::Error: Debug, TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, + PH: HeaderTrait, + OnChainEncryptionKeyRepository: AccessKey, { pub fn new( ocall_api: Arc, state_handler: Arc, node_metadata_repo: Arc, + on_chain_encryption_key_repository: Arc, ) -> Self { - StfExecutor { ocall_api, state_handler, node_metadata_repo, _phantom: PhantomData } + StfExecutor { + ocall_api, + state_handler, + node_metadata_repo, + on_chain_encryption_key_repository, + _phantom: PhantomData, + } } /// Execute a trusted call on the STF @@ -90,17 +141,14 @@ where /// an invalid trusted call, which results in `Ok(ExecutionStatus::Failure)`. The latter /// can be used to remove the trusted call from a queue. In the former case we might keep the /// trusted call and just re-try the operation. - fn execute_trusted_call_on_stf( + fn execute_trusted_call_on_stf( &self, state: &mut StateHandler::StateT, trusted_operation: &TrustedOperation, - _header: &PH, + parentchain_header: &PH, shard: &ShardIdentifier, post_processing: StatePostProcessing, - ) -> Result> - where - PH: HeaderTrait, - { + ) -> Result> { debug!("query mrenclave of self"); let mrenclave = self.ocall_api.get_mrenclave_of_self()?; @@ -132,6 +180,9 @@ where trusted_operation.hash(), &mut extrinsic_call_backs, self.node_metadata_repo.clone(), + self.ocall_api.clone(), + parentchain_header, + self.on_chain_encryption_key_repository.clone(), ) { Err(e) => { if let Err(e) = @@ -180,10 +231,26 @@ where } } -impl - StfUpdateState - for StfExecutor -where +impl< + OCallApi, + StateHandler, + NodeMetadataRepository, + Stf, + TCS, + G, + PH, + OnChainEncryptionKeyRepository, + > StfUpdateState + for StfExecutor< + OCallApi, + StateHandler, + NodeMetadataRepository, + Stf, + TCS, + G, + PH, + OnChainEncryptionKeyRepository, + > where OCallApi: EnclaveAttestationOCallApi + EnclaveOnChainOCallApi, StateHandler: HandleState + QueryShardState, StateHandler::StateT: SgxExternalitiesTrait + Encode, @@ -191,21 +258,18 @@ where Stf: UpdateState< StateHandler::StateT, ::SgxExternalitiesDiffType, - > + ParentchainPalletInstancesInterface, + > + ParentchainPalletInstancesInterface, ::SgxExternalitiesDiffType: IntoIterator, Option>)>, - >::Error: - Debug, + >::Error: Debug, ::SgxExternalitiesDiffType: From, Option>>>, TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, + PH: HeaderTrait, + OnChainEncryptionKeyRepository: AccessKey, { - fn update_states( - &self, - header: &ParentchainHeader, - parentchain_id: &ParentchainId, - ) -> Result<()> { + fn update_states(&self, header: &PH, parentchain_id: &ParentchainId) -> Result<()> { debug!("Update STF storage upon block import!"); let storage_hashes = Stf::storage_hashes_to_update_on_block(parentchain_id); @@ -245,28 +309,46 @@ where } } -impl - StfExecutor -where +impl< + OCallApi, + StateHandler, + NodeMetadataRepository, + Stf, + TCS, + G, + PH, + OnChainEncryptionKeyRepository, + > + StfExecutor< + OCallApi, + StateHandler, + NodeMetadataRepository, + Stf, + TCS, + G, + PH, + OnChainEncryptionKeyRepository, + > where ::SgxExternalitiesDiffType: From, Option>>> + IntoIterator, Option>)>, - >::Error: - Debug, + >::Error: Debug, NodeMetadataRepository: AccessNodeMetadata, OCallApi: EnclaveAttestationOCallApi + EnclaveOnChainOCallApi, StateHandler: HandleState + QueryShardState, StateHandler::StateT: Encode + SgxExternalitiesTrait, - Stf: ParentchainPalletInstancesInterface + Stf: ParentchainPalletInstancesInterface + UpdateState< StateHandler::StateT, ::SgxExternalitiesDiffType, >, TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, + PH: HeaderTrait, + OnChainEncryptionKeyRepository: AccessKey, { fn initialize_new_shards( &self, - header: &ParentchainHeader, + header: &PH, state_diff_update: &BTreeMap, Option>>, shards: &Vec, ) -> Result<()> { @@ -295,9 +377,26 @@ where } } -impl StateUpdateProposer - for StfExecutor -where +impl< + OCallApi, + StateHandler, + NodeMetadataRepository, + Stf, + TCS, + G, + PH, + OnChainEncryptionKeyRepository, + > StateUpdateProposer + for StfExecutor< + OCallApi, + StateHandler, + NodeMetadataRepository, + Stf, + TCS, + G, + PH, + OnChainEncryptionKeyRepository, + > where OCallApi: EnclaveAttestationOCallApi + EnclaveOnChainOCallApi + EnclaveMetricsOCallApi, StateHandler: HandleState, StateHandler::StateT: SgxExternalitiesTrait + Encode + StateHash, @@ -307,20 +406,35 @@ where Stf: UpdateState< StateHandler::StateT, ::SgxExternalitiesDiffType, - > + StateCallInterface - + RuntimeUpgradeInterface, + > + StateCallInterface< + TCS, + StateHandler::StateT, + NodeMetadataRepository, + OCallApi, + PH, + OnChainEncryptionKeyRepository, + > + RuntimeUpgradeInterface, ::SgxExternalitiesDiffType: IntoIterator, Option>)>, ::SgxExternalitiesDiffType: From, Option>>>, - >::Error: Debug, + >::Error: Debug, >::Error: Debug, TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, + PH: HeaderTrait, + OnChainEncryptionKeyRepository: AccessKey, { type Externalities = StateHandler::StateT; - fn propose_state_update( + fn propose_state_update( &self, trusted_calls: &[TrustedOperation], header: &PH, @@ -329,7 +443,6 @@ where prepare_state_function: F, ) -> Result> where - PH: HeaderTrait, F: FnOnce(Self::Externalities) -> Self::Externalities, { let ends_at = duration_now() + max_exec_duration; diff --git a/tee-worker/bitacross/core-primitives/stf-executor/src/executor_tests.rs b/tee-worker/bitacross/core-primitives/stf-executor/src/executor_tests.rs index 2eb0185bcd..40e8e499f4 100644 --- a/tee-worker/bitacross/core-primitives/stf-executor/src/executor_tests.rs +++ b/tee-worker/bitacross/core-primitives/stf-executor/src/executor_tests.rs @@ -20,6 +20,8 @@ use codec::Encode; use itc_parentchain_test::ParentchainHeaderBuilder; use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; use itp_ocall_api::EnclaveAttestationOCallApi; +// TODO: use Aes256 when available +use itp_sgx_crypto::{mocks::KeyRepositoryMock, Aes}; use itp_sgx_externalities::{SgxExternalities as State, SgxExternalitiesTrait}; use itp_stf_primitives::{traits::TrustedCallSigning, types::ShardIdentifier}; use itp_stf_state_handler::handle_state::HandleState; @@ -28,7 +30,7 @@ use itp_test::mock::{ onchain_mock::OnchainMock, stf_mock::{GetterMock, StfMock, TrustedCallMock, TrustedCallSignedMock}, }; -use itp_types::H256; +use itp_types::{parentchain::Header as ParentchainHeader, H256}; use sp_core::{ed25519, Pair}; use sp_runtime::app_crypto::sp_core::blake2_256; use std::{sync::Arc, time::Duration, vec}; @@ -244,6 +246,8 @@ fn stf_executor() -> ( StfMock, TrustedCallSignedMock, GetterMock, + ParentchainHeader, + KeyRepositoryMock, >, Arc, Arc, @@ -251,7 +255,13 @@ fn stf_executor() -> ( let ocall_api = Arc::new(OnchainMock::default()); let state_handler = Arc::new(HandleStateMock::default()); let node_metadata_repo = Arc::new(NodeMetadataRepository::new(NodeMetadataMock::new())); - let executor = StfExecutor::new(ocall_api.clone(), state_handler.clone(), node_metadata_repo); + let encryption_key_repository = Arc::new(KeyRepositoryMock::new(Aes::default())); + let executor = StfExecutor::new( + ocall_api.clone(), + state_handler.clone(), + node_metadata_repo, + encryption_key_repository, + ); (executor, ocall_api, state_handler) } diff --git a/tee-worker/bitacross/core-primitives/stf-executor/src/mocks.rs b/tee-worker/bitacross/core-primitives/stf-executor/src/mocks.rs index d328a2e24e..96a554501b 100644 --- a/tee-worker/bitacross/core-primitives/stf-executor/src/mocks.rs +++ b/tee-worker/bitacross/core-primitives/stf-executor/src/mocks.rs @@ -59,15 +59,16 @@ impl StfExecutorMock { } } -impl StateUpdateProposer for StfExecutorMock +impl StateUpdateProposer for StfExecutorMock where State: SgxExternalitiesTrait + Encode + Clone, TCS: PartialEq + Encode + Decode + Clone + Debug + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Clone + Debug + Send + Sync, + PH: HeaderTrait, { type Externalities = State; - fn propose_state_update( + fn propose_state_update( &self, trusted_calls: &[TrustedOperation], _header: &PH, @@ -76,7 +77,6 @@ where prepare_state_function: F, ) -> Result> where - PH: HeaderTrait, F: FnOnce(Self::Externalities) -> Self::Externalities, { let mut lock = self.state.write().unwrap(); diff --git a/tee-worker/bitacross/core-primitives/stf-executor/src/traits.rs b/tee-worker/bitacross/core-primitives/stf-executor/src/traits.rs index 62e788141a..3b77b99588 100644 --- a/tee-worker/bitacross/core-primitives/stf-executor/src/traits.rs +++ b/tee-worker/bitacross/core-primitives/stf-executor/src/traits.rs @@ -55,10 +55,11 @@ where } /// Proposes a state update to `Externalities`. -pub trait StateUpdateProposer +pub trait StateUpdateProposer where TCS: PartialEq + Encode + Decode + Debug + Send + Sync, G: PartialEq + Encode + Decode + Debug + Send + Sync, + PH: HeaderTrait, { type Externalities: SgxExternalitiesTrait + Encode; @@ -66,7 +67,7 @@ where /// /// All executed call hashes and the mutated state are returned. /// If the time expires, any remaining trusted calls within the batch will be ignored. - fn propose_state_update( + fn propose_state_update( &self, trusted_calls: &[TrustedOperation], header: &PH, @@ -75,7 +76,6 @@ where prepare_state_function: F, ) -> Result> where - PH: HeaderTrait, F: FnOnce(Self::Externalities) -> Self::Externalities; } diff --git a/tee-worker/bitacross/core/offchain-worker-executor/src/executor.rs b/tee-worker/bitacross/core/offchain-worker-executor/src/executor.rs index 5cf3e778b8..51f9590e12 100644 --- a/tee-worker/bitacross/core/offchain-worker-executor/src/executor.rs +++ b/tee-worker/bitacross/core/offchain-worker-executor/src/executor.rs @@ -30,7 +30,7 @@ use itp_stf_state_handler::{handle_state::HandleState, query_shard_state::QueryS use itp_top_pool_author::traits::AuthorApi; use itp_types::{parentchain::ParentchainCall, OpaqueCall, ShardIdentifier, H256}; use log::*; -use sp_runtime::traits::Block; +use sp_runtime::traits::{Block, Header as HeaderTrait}; use std::{marker::PhantomData, sync::Arc, time::Duration, vec::Vec}; /// Off-chain worker executor implementation. @@ -51,13 +51,14 @@ pub struct Executor< Stf, TCS, G, + PH, > { top_pool_author: Arc, stf_executor: Arc, state_handler: Arc, validator_accessor: Arc, extrinsics_factory: Arc, - _phantom: PhantomData<(ParentchainBlock, Stf, TCS, G)>, + _phantom: PhantomData<(ParentchainBlock, Stf, TCS, G, PH)>, } impl< @@ -70,6 +71,7 @@ impl< Stf, TCS, G, + PH, > Executor< ParentchainBlock, @@ -81,9 +83,10 @@ impl< Stf, TCS, G, + PH, > where - ParentchainBlock: Block, - StfExecutor: StateUpdateProposer, + ParentchainBlock: Block, + StfExecutor: StateUpdateProposer, TopPoolAuthor: AuthorApi, StateHandler: QueryShardState + HandleState, ValidatorAccessor: ValidatorAccess + Send + Sync + 'static, @@ -92,6 +95,7 @@ impl< Stf: SystemPalletEventInterface, TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, + PH: HeaderTrait, { pub fn new( top_pool_author: Arc, @@ -186,7 +190,7 @@ impl< fn apply_state_update( &self, shard: &ShardIdentifier, - updated_state: >::Externalities, + updated_state: >::Externalities, ) -> Result<()> { self.state_handler.reset(updated_state, shard)?; Ok(()) diff --git a/tee-worker/bitacross/enclave-runtime/Cargo.lock b/tee-worker/bitacross/enclave-runtime/Cargo.lock index 0062a3972d..35e5242fa7 100644 --- a/tee-worker/bitacross/enclave-runtime/Cargo.lock +++ b/tee-worker/bitacross/enclave-runtime/Cargo.lock @@ -324,6 +324,8 @@ dependencies = [ "hex-literal", "itp-hashing", "itp-node-api", + "itp-ocall-api", + "itp-sgx-crypto", "itp-sgx-externalities", "itp-stf-interface", "itp-stf-primitives", @@ -969,7 +971,7 @@ checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" [[package]] name = "core-primitives" version = "0.1.0" -source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#ea133d42f915d6e3cbbc51304f534d0b9f42e5d3" +source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#84afa8035ad15a50b57ec9f7d3845d03bc9a426b" dependencies = [ "base58", "frame-support", @@ -980,6 +982,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", + "sp-core-hashing", "sp-io", "sp-runtime", "sp-std", @@ -2484,9 +2487,12 @@ version = "0.8.0" dependencies = [ "itp-node-api-metadata", "itp-node-api-metadata-provider", + "itp-ocall-api", + "itp-sgx-crypto", "itp-stf-primitives", "itp-types", "parity-scale-codec", + "sp-runtime", ] [[package]] @@ -2544,6 +2550,7 @@ dependencies = [ "frame-support", "hash-db 0.15.2", "itp-types", + "litentry-hex-utils 0.1.0", "parity-scale-codec", "sgx_tstd", "sp-core", @@ -2764,7 +2771,7 @@ dependencies = [ [[package]] name = "litentry-hex-utils" version = "0.1.0" -source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#ea133d42f915d6e3cbbc51304f534d0b9f42e5d3" +source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#84afa8035ad15a50b57ec9f7d3845d03bc9a426b" dependencies = [ "hex", ] @@ -2776,7 +2783,7 @@ version = "0.1.0" [[package]] name = "litentry-macros" version = "0.1.0" -source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#ea133d42f915d6e3cbbc51304f534d0b9f42e5d3" +source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#84afa8035ad15a50b57ec9f7d3845d03bc9a426b" [[package]] name = "litentry-primitives" @@ -2815,7 +2822,7 @@ dependencies = [ [[package]] name = "litentry-proc-macros" version = "0.1.0" -source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#ea133d42f915d6e3cbbc51304f534d0b9f42e5d3" +source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#84afa8035ad15a50b57ec9f7d3845d03bc9a426b" dependencies = [ "cargo_toml", "proc-macro2", @@ -3190,7 +3197,7 @@ dependencies = [ [[package]] name = "pallet-teebag" version = "0.1.0" -source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#ea133d42f915d6e3cbbc51304f534d0b9f42e5d3" +source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#84afa8035ad15a50b57ec9f7d3845d03bc9a426b" dependencies = [ "base64 0.13.1", "chrono 0.4.31", diff --git a/tee-worker/bitacross/enclave-runtime/src/initialization/global_components.rs b/tee-worker/bitacross/enclave-runtime/src/initialization/global_components.rs index 6e60d93af5..cb81f274bc 100644 --- a/tee-worker/bitacross/enclave-runtime/src/initialization/global_components.rs +++ b/tee-worker/bitacross/enclave-runtime/src/initialization/global_components.rs @@ -85,7 +85,10 @@ use itp_top_pool_author::{ api::SidechainApi, author::{Author, AuthorTopFilter}, }; -use itp_types::{Block as ParentchainBlock, SignedBlock as SignedParentchainBlock}; +use itp_types::{ + parentchain::Header as ParentchainHeader, Block as ParentchainBlock, + SignedBlock as SignedParentchainBlock, +}; use lazy_static::lazy_static; use sgx_crypto_helper::rsa3072::Rsa3072KeyPair; use sgx_tstd::vec::Vec; @@ -122,6 +125,8 @@ pub type EnclaveStfExecutor = StfExecutor< EnclaveStf, EnclaveTrustedCallSigned, EnclaveGetter, + ParentchainHeader, + EnclaveStateKeyRepository, // TODO: use new aes256 key repository when available >; pub type EnclaveStfEnclaveSigner = StfEnclaveSigner< EnclaveOCallApi, @@ -328,6 +333,7 @@ pub type EnclaveOffchainWorkerExecutor = itc_offchain_worker_executor::executor: EnclaveStf, EnclaveTrustedCallSigned, EnclaveGetter, + ParentchainHeader, >; // Base component instances diff --git a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/integritee_parachain.rs b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/integritee_parachain.rs index f0cc06a94b..608a48088e 100644 --- a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/integritee_parachain.rs +++ b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/integritee_parachain.rs @@ -19,12 +19,17 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, - EnclaveStfExecutor, EnclaveValidatorAccessor, + EnclaveExtrinsicsFactory, + EnclaveNodeMetadataRepository, + EnclaveOCallApi, + EnclaveStfExecutor, + EnclaveValidatorAccessor, IntegriteeParentchainBlockImportDispatcher, GLOBAL_INTEGRITEE_PARENTCHAIN_LIGHT_CLIENT_SEAL, - GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE, GLOBAL_OCALL_API_COMPONENT, + GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE, + GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, + GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, // TODO: use global for aes256 key repository }, parentchain::common::{ create_extrinsics_factory, create_integritee_offchain_immediate_import_dispatcher, @@ -78,10 +83,13 @@ impl IntegriteeParachainHandler { node_metadata_repository.clone(), )?; + let on_chain_encryption_key_repository = GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.get()?; + let stf_executor = Arc::new(EnclaveStfExecutor::new( ocall_api, state_handler, node_metadata_repository.clone(), + on_chain_encryption_key_repository, )); let block_importer = create_integritee_parentchain_block_importer( diff --git a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs index ee5697967f..88c9d7d4d0 100644 --- a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs +++ b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs @@ -19,12 +19,17 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, - EnclaveStfExecutor, EnclaveValidatorAccessor, + EnclaveExtrinsicsFactory, + EnclaveNodeMetadataRepository, + EnclaveOCallApi, + EnclaveStfExecutor, + EnclaveValidatorAccessor, IntegriteeParentchainBlockImportDispatcher, GLOBAL_INTEGRITEE_PARENTCHAIN_LIGHT_CLIENT_SEAL, - GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE, GLOBAL_OCALL_API_COMPONENT, + GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE, + GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, + GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, // TODO: use global for aes256 key repository }, parentchain::common::{ create_extrinsics_factory, create_integritee_offchain_immediate_import_dispatcher, @@ -77,10 +82,13 @@ impl IntegriteeSolochainHandler { node_metadata_repository.clone(), )?; + let on_chain_encryption_key_repository = GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.get()?; + let stf_executor = Arc::new(EnclaveStfExecutor::new( ocall_api, state_handler, node_metadata_repository.clone(), + on_chain_encryption_key_repository, )); let block_importer = create_integritee_parentchain_block_importer( diff --git a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_a_parachain.rs b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_a_parachain.rs index 32de87cfba..99e25d1b26 100644 --- a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_a_parachain.rs +++ b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_a_parachain.rs @@ -25,10 +25,17 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, - EnclaveStfExecutor, EnclaveValidatorAccessor, TargetAParentchainBlockImportDispatcher, - GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE, + EnclaveExtrinsicsFactory, + EnclaveNodeMetadataRepository, + EnclaveOCallApi, + EnclaveStfExecutor, + EnclaveValidatorAccessor, + TargetAParentchainBlockImportDispatcher, + GLOBAL_OCALL_API_COMPONENT, + GLOBAL_STATE_HANDLER_COMPONENT, + GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, // TODO: use global for aes256 key repository + GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL, + GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE, }, parentchain::common::{ create_extrinsics_factory, create_target_a_offchain_immediate_import_dispatcher, @@ -82,10 +89,13 @@ impl TargetAParachainHandler { node_metadata_repository.clone(), )?; + let on_chain_encryption_key_repository = GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.get()?; + let stf_executor = Arc::new(EnclaveStfExecutor::new( ocall_api, state_handler, node_metadata_repository.clone(), + on_chain_encryption_key_repository, )); let block_importer = create_target_a_parentchain_block_importer( diff --git a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs index bd76a450f6..3ad0f870a0 100644 --- a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs +++ b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs @@ -19,10 +19,17 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, - EnclaveStfExecutor, EnclaveValidatorAccessor, TargetAParentchainBlockImportDispatcher, - GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE, + EnclaveExtrinsicsFactory, + EnclaveNodeMetadataRepository, + EnclaveOCallApi, + EnclaveStfExecutor, + EnclaveValidatorAccessor, + TargetAParentchainBlockImportDispatcher, + GLOBAL_OCALL_API_COMPONENT, + GLOBAL_STATE_HANDLER_COMPONENT, + GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, // TODO: use global for aes256 key repository + GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL, + GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE, }, parentchain::common::{ create_extrinsics_factory, create_target_a_offchain_immediate_import_dispatcher, @@ -75,10 +82,13 @@ impl TargetASolochainHandler { node_metadata_repository.clone(), )?; + let on_chain_encryption_key_repository = GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.get()?; + let stf_executor = Arc::new(EnclaveStfExecutor::new( ocall_api, state_handler, node_metadata_repository.clone(), + on_chain_encryption_key_repository, )); let block_importer = create_target_a_parentchain_block_importer( diff --git a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_b_parachain.rs b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_b_parachain.rs index 221a37b0c0..8e1962ca55 100644 --- a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_b_parachain.rs +++ b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_b_parachain.rs @@ -25,10 +25,17 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, - EnclaveStfExecutor, EnclaveValidatorAccessor, TargetBParentchainBlockImportDispatcher, - GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE, + EnclaveExtrinsicsFactory, + EnclaveNodeMetadataRepository, + EnclaveOCallApi, + EnclaveStfExecutor, + EnclaveValidatorAccessor, + TargetBParentchainBlockImportDispatcher, + GLOBAL_OCALL_API_COMPONENT, + GLOBAL_STATE_HANDLER_COMPONENT, + GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, // TODO: use global for aes256 key repository + GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL, + GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE, }, parentchain::common::{ create_extrinsics_factory, create_target_b_offchain_immediate_import_dispatcher, @@ -82,10 +89,13 @@ impl TargetBParachainHandler { node_metadata_repository.clone(), )?; + let on_chain_encryption_key_repository = GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.get()?; + let stf_executor = Arc::new(EnclaveStfExecutor::new( ocall_api, state_handler, node_metadata_repository.clone(), + on_chain_encryption_key_repository, )); let block_importer = create_target_b_parentchain_block_importer( diff --git a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs index 0953d15779..2b13e07d9b 100644 --- a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs +++ b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs @@ -19,10 +19,17 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, - EnclaveStfExecutor, EnclaveValidatorAccessor, TargetBParentchainBlockImportDispatcher, - GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE, + EnclaveExtrinsicsFactory, + EnclaveNodeMetadataRepository, + EnclaveOCallApi, + EnclaveStfExecutor, + EnclaveValidatorAccessor, + TargetBParentchainBlockImportDispatcher, + GLOBAL_OCALL_API_COMPONENT, + GLOBAL_STATE_HANDLER_COMPONENT, + GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, // TODO: use global for aes256 key repository + GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL, + GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE, }, parentchain::common::{ create_extrinsics_factory, create_target_b_offchain_immediate_import_dispatcher, @@ -75,10 +82,13 @@ impl TargetBSolochainHandler { node_metadata_repository.clone(), )?; + let on_chain_encryption_key_repository = GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.get()?; + let stf_executor = Arc::new(EnclaveStfExecutor::new( ocall_api, state_handler, node_metadata_repository.clone(), + on_chain_encryption_key_repository, )); let block_importer = create_target_b_parentchain_block_importer( diff --git a/tee-worker/bitacross/enclave-runtime/src/test/enclave_signer_tests.rs b/tee-worker/bitacross/enclave-runtime/src/test/enclave_signer_tests.rs index b76af97d4a..6198befd7a 100644 --- a/tee-worker/bitacross/enclave-runtime/src/test/enclave_signer_tests.rs +++ b/tee-worker/bitacross/enclave-runtime/src/test/enclave_signer_tests.rs @@ -20,7 +20,10 @@ use ita_stf::{Getter, Stf, TrustedCall, TrustedCallSigned}; use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; use itp_ocall_api::EnclaveAttestationOCallApi; use itp_sgx_crypto::{ - ed25519_derivation::DeriveEd25519, key_repository::AccessKey, mocks::KeyRepositoryMock, + ed25519_derivation::DeriveEd25519, + key_repository::AccessKey, + mocks::KeyRepositoryMock, + Aes, // TODO: use Aes256 when available }; use itp_sgx_externalities::SgxExternalities; use itp_stf_executor::{enclave_signer::StfEnclaveSigner, traits::StfEnclaveSigning}; @@ -35,14 +38,20 @@ use itp_stf_primitives::{ use itp_stf_state_observer::mock::ObserveStateMock; use itp_test::mock::onchain_mock::OnchainMock; use itp_top_pool_author::{mocks::AuthorApiMock, traits::AuthorApi}; -use itp_types::{parentchain::ParentchainId, RsaRequest}; +use itp_types::{parentchain::ParentchainId, Header, RsaRequest}; use litentry_primitives::Identity; use sgx_crypto_helper::{rsa3072::Rsa3072KeyPair, RsaKeyPair}; use sp_core::Pair; +use sp_runtime::traits::Header as HeaderTrait; use std::{sync::Arc, vec::Vec}; type ShieldingKeyRepositoryMock = KeyRepositoryMock; type TestStf = Stf; +type OnChainEncryptionKeyRepositoryMock = KeyRepositoryMock; + +pub fn latest_parentchain_header() -> Header { + Header::new(1, Default::default(), Default::default(), [69; 32].into(), Default::default()) +} pub fn derive_key_is_deterministic() { let rsa_key = Rsa3072KeyPair::new().unwrap(); @@ -103,7 +112,7 @@ pub fn nonce_is_computed_correctly() { let shard = ShardIdentifier::default(); let enclave_signer = StfEnclaveSigner::<_, _, _, TestStf, _, TrustedCallSigned, Getter>::new( state_observer, - ocall_api, + ocall_api.clone(), shielding_key_repo, top_pool_author.clone(), ); @@ -149,6 +158,8 @@ pub fn nonce_is_computed_correctly() { assert_eq!(0, TestStf::get_account_nonce(&mut state, &enclave_account)); let repo = Arc::new(NodeMetadataRepository::new(NodeMetadataMock::new())); + let on_chain_encryption_key_repository = + Arc::new(OnChainEncryptionKeyRepositoryMock::new(Aes::default())); assert!(TestStf::execute_call( &mut state, &shard, @@ -156,6 +167,9 @@ pub fn nonce_is_computed_correctly() { Default::default(), &mut Vec::new(), repo.clone(), + ocall_api.clone(), + &latest_parentchain_header(), + on_chain_encryption_key_repository.clone() ) .is_ok()); @@ -166,6 +180,9 @@ pub fn nonce_is_computed_correctly() { Default::default(), &mut Vec::new(), repo, + ocall_api, + &latest_parentchain_header(), + on_chain_encryption_key_repository ) .is_ok()); assert_eq!(2, TestStf::get_account_nonce(&mut state, &enclave_account)); diff --git a/tee-worker/bitacross/enclave-runtime/src/test/fixtures/test_setup.rs b/tee-worker/bitacross/enclave-runtime/src/test/fixtures/test_setup.rs index b9a357eab5..fb594dd696 100644 --- a/tee-worker/bitacross/enclave-runtime/src/test/fixtures/test_setup.rs +++ b/tee-worker/bitacross/enclave-runtime/src/test/fixtures/test_setup.rs @@ -24,7 +24,11 @@ use ita_sgx_runtime::Runtime; use ita_stf::{Getter, State, Stf, TrustedCallSigned}; use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; use itp_ocall_api::EnclaveAttestationOCallApi; -use itp_sgx_crypto::{ed25519_derivation::DeriveEd25519, mocks::KeyRepositoryMock}; +use itp_sgx_crypto::{ + ed25519_derivation::DeriveEd25519, + mocks::KeyRepositoryMock, + Aes, // TODO: use Aes256 when available +}; use itp_sgx_externalities::SgxExternalities; use itp_stf_executor::executor::StfExecutor; use itp_stf_primitives::types::{ShardIdentifier, TrustedOperation}; @@ -33,9 +37,10 @@ use itp_test::mock::{ }; use itp_top_pool::{basic_pool::BasicPool, pool::ExtrinsicHash}; use itp_top_pool_author::{api::SidechainApi, author::Author, top_filter::AllowAllTopsFilter}; -use itp_types::{Block, MrEnclave}; +use itp_types::{parentchain::Header as ParentchainHeader, Block, MrEnclave}; use sp_core::{crypto::Pair, ed25519 as spEd25519}; use std::sync::Arc; + pub type TestRpcResponder = RpcResponderMock>>; pub type TestTopPool = BasicPool< SidechainApi, @@ -54,6 +59,8 @@ pub type TestTopPoolAuthor = Author< >; pub type TestStf = Stf; +type TestOnChainEncryptionKeyRepository = KeyRepositoryMock; + pub type TestStfExecutor = StfExecutor< OcallApi, HandleStateMock, @@ -61,6 +68,8 @@ pub type TestStfExecutor = StfExecutor< TestStf, TrustedCallSigned, Getter, + ParentchainHeader, + TestOnChainEncryptionKeyRepository, >; /// Returns all the things that are commonly used in tests and runs @@ -73,6 +82,7 @@ pub fn test_setup() -> ( ShieldingCryptoMock, Arc, Arc, + Arc, ) { let shielding_key = ShieldingCryptoMock::default(); let shielding_key_repo = Arc::new(KeyRepositoryMock::new(shielding_key.clone())); @@ -84,10 +94,13 @@ pub fn test_setup() -> ( let mrenclave = OcallApi.get_mrenclave_of_self().unwrap().m; let node_metadata_repo = Arc::new(NodeMetadataRepository::new(NodeMetadataMock::new())); + let on_chain_encryption_key_repository = KeyRepositoryMock::new(Aes::default()); + let stf_executor = Arc::new(TestStfExecutor::new( Arc::new(OcallApi), state_handler.clone(), node_metadata_repo, + Arc::new(on_chain_encryption_key_repository), )); ( @@ -103,6 +116,7 @@ pub fn test_setup() -> ( shielding_key, state_handler, stf_executor, + Arc::new(OcallApi), ) } diff --git a/tee-worker/bitacross/enclave-runtime/src/test/mocks/types.rs b/tee-worker/bitacross/enclave-runtime/src/test/mocks/types.rs index 1ffe90a2fd..c92a39d3f6 100644 --- a/tee-worker/bitacross/enclave-runtime/src/test/mocks/types.rs +++ b/tee-worker/bitacross/enclave-runtime/src/test/mocks/types.rs @@ -30,7 +30,10 @@ use itp_stf_primitives::types::TrustedOperation; use itp_test::mock::{handle_state_mock::HandleStateMock, onchain_mock::OnchainMock}; use itp_top_pool::basic_pool::BasicPool; use itp_top_pool_author::{api::SidechainApi, author::Author, top_filter::AllowAllTopsFilter}; -use itp_types::{Block as ParentchainBlock, SignedBlock as SignedParentchainBlock}; +use itp_types::{ + parentchain::Header as ParentchainHeader, Block as ParentchainBlock, + SignedBlock as SignedParentchainBlock, +}; use primitive_types::H256; use sgx_crypto_helper::rsa3072::Rsa3072KeyPair; use sp_core::ed25519 as spEd25519; @@ -63,6 +66,8 @@ pub type TestStfExecutor = StfExecutor< TestStf, TrustedCallSigned, Getter, + ParentchainHeader, + TestStateKeyRepo, >; pub type TestRpcResponder = RpcResponderMock; diff --git a/tee-worker/bitacross/enclave-runtime/src/test/tests_main.rs b/tee-worker/bitacross/enclave-runtime/src/test/tests_main.rs index 0e44a1937b..de9ebd3e2c 100644 --- a/tee-worker/bitacross/enclave-runtime/src/test/tests_main.rs +++ b/tee-worker/bitacross/enclave-runtime/src/test/tests_main.rs @@ -36,7 +36,7 @@ use ita_stf::{ Getter, State, TrustedCall, TrustedCallSigned, TrustedGetter, }; use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; -use itp_sgx_crypto::{Aes, StateCrypto}; +use itp_sgx_crypto::{mocks::KeyRepositoryMock, Aes, StateCrypto}; use itp_sgx_externalities::{SgxExternalitiesDiffType, SgxExternalitiesTrait}; use itp_stf_executor::{ executor_tests as stf_executor_tests, traits::StateUpdateProposer, BatchExecutionResult, @@ -279,7 +279,7 @@ fn test_differentiate_getter_and_call_works() { fn test_executing_call_updates_account_nonce() { // given - let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor) = test_setup(); + let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor, ..) = test_setup(); let sender = funded_pair(); let receiver = unfunded_public(); @@ -312,7 +312,7 @@ fn test_executing_call_updates_account_nonce() { } fn test_call_set_update_parentchain_block() { - let (_, _, shard, _, _, state_handler, _) = test_setup(); + let (_, _, shard, _, _, state_handler, _, ..) = test_setup(); let (mut state, _) = state_handler.load_cloned(&shard).unwrap(); let block_number = 3; @@ -335,7 +335,7 @@ fn test_call_set_update_parentchain_block() { fn test_signature_must_match_public_sender_in_call() { // given - let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor) = test_setup(); + let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor, ..) = test_setup(); // create accounts let sender = funded_pair(); @@ -365,7 +365,7 @@ fn test_signature_must_match_public_sender_in_call() { fn test_invalid_nonce_call_is_not_executed() { // given - let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor) = test_setup(); + let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor, ..) = test_setup(); // create accounts let sender = funded_pair(); @@ -395,7 +395,8 @@ fn test_invalid_nonce_call_is_not_executed() { fn test_non_root_shielding_call_is_not_executed() { // given - let (top_pool_author, _state, shard, mrenclave, shielding_key, _, stf_executor) = test_setup(); + let (top_pool_author, _state, shard, mrenclave, shielding_key, _, stf_executor, ..) = + test_setup(); let sender = funded_pair(); let sender_acc: AccountId = sender.public().into(); @@ -424,7 +425,8 @@ fn test_non_root_shielding_call_is_not_executed() { } fn test_shielding_call_with_enclave_self_is_executed() { - let (top_pool_author, _state, shard, mrenclave, shielding_key, _, stf_executor) = test_setup(); + let (top_pool_author, _state, shard, mrenclave, shielding_key, _, stf_executor, ..) = + test_setup(); let sender = funded_pair(); let sender_account: AccountId = sender.public().into(); @@ -459,7 +461,8 @@ fn test_shielding_call_with_enclave_self_is_executed() { pub fn test_retrieve_events() { // given - let (_, mut state, shard, mrenclave, ..) = test_setup(); + let (_, mut state, shard, mrenclave, _shielding_key, _state_handler, _stf_executor, ocall_api) = + test_setup(); let mut opaque_vec = Vec::new(); let sender = funded_pair(); let receiver = unendowed_account(); @@ -476,6 +479,8 @@ pub fn test_retrieve_events() { .sign(&sender.into(), 0, &mrenclave, &shard); let repo = Arc::new(NodeMetadataRepository::::default()); let shard = ShardIdentifier::default(); + let on_chain_encryption_key_repository = + Arc::new(KeyRepositoryMock::::new(Aes::default())); TestStf::execute_call( &mut state, &shard, @@ -483,6 +488,9 @@ pub fn test_retrieve_events() { Default::default(), &mut opaque_vec, repo, + ocall_api, + &latest_parentchain_header(), + on_chain_encryption_key_repository, ) .unwrap(); @@ -490,7 +498,8 @@ pub fn test_retrieve_events() { } pub fn test_retrieve_event_count() { - let (_, mut state, shard, mrenclave, ..) = test_setup(); + let (_, mut state, shard, mrenclave, _shielding_key, _state_handler, _stf_executor, ocall_api) = + test_setup(); let mut opaque_vec = Vec::new(); let sender = funded_pair(); let receiver = unendowed_account(); @@ -509,6 +518,8 @@ pub fn test_retrieve_event_count() { // when let repo = Arc::new(NodeMetadataRepository::::default()); let shard = ShardIdentifier::default(); + let on_chain_encryption_key_repository = + Arc::new(KeyRepositoryMock::::new(Aes::default())); TestStf::execute_call( &mut state, &shard, @@ -516,6 +527,9 @@ pub fn test_retrieve_event_count() { Default::default(), &mut opaque_vec, repo, + ocall_api, + &latest_parentchain_header(), + on_chain_encryption_key_repository, ) .unwrap(); @@ -524,7 +538,8 @@ pub fn test_retrieve_event_count() { } pub fn test_reset_events() { - let (_, mut state, shard, mrenclave, ..) = test_setup(); + let (_, mut state, shard, mrenclave, _shielding_key, _state_handler, _stf_executor, ocall_api) = + test_setup(); let mut opaque_vec = Vec::new(); let sender = funded_pair(); let receiver = unendowed_account(); @@ -540,6 +555,8 @@ pub fn test_reset_events() { .sign(&sender.into(), 0, &mrenclave, &shard); let repo = Arc::new(NodeMetadataRepository::::default()); let shard = ShardIdentifier::default(); + let on_chain_encryption_key_repository = + Arc::new(KeyRepositoryMock::::new(Aes::default())); TestStf::execute_call( &mut state, &shard, @@ -547,6 +564,9 @@ pub fn test_reset_events() { Default::default(), &mut opaque_vec, repo, + ocall_api, + &latest_parentchain_header(), + on_chain_encryption_key_repository, ) .unwrap(); let receiver_acc_info = TestStf::get_account_data(&mut state, &receiver.public().into()); From 1da6286d9551c8c9942128fc956ea62855c29e32 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 9 Oct 2024 12:24:48 +0000 Subject: [PATCH 21/39] fixing fmt issue --- tee-worker/bitacross/app-libs/stf/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tee-worker/bitacross/app-libs/stf/Cargo.toml b/tee-worker/bitacross/app-libs/stf/Cargo.toml index dabc854784..727b2c4610 100644 --- a/tee-worker/bitacross/app-libs/stf/Cargo.toml +++ b/tee-worker/bitacross/app-libs/stf/Cargo.toml @@ -14,9 +14,9 @@ sgx_tstd = { workspace = true, features = ["untrusted_fs", "net", "backtrace"], itp-hashing = { workspace = true } itp-node-api = { workspace = true } -itp-sgx-externalities = { workspace = true } itp-ocall-api = { workspace = true } itp-sgx-crypto = { workspace = true } +itp-sgx-externalities = { workspace = true } itp-stf-interface = { workspace = true } itp-stf-primitives = { workspace = true } itp-storage = { workspace = true } From 32ffc5e0318fb7f482c71db41978354e280765e6 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 9 Oct 2024 14:07:38 +0000 Subject: [PATCH 22/39] fixing tests --- .../bitacross/core/offchain-worker-executor/src/executor.rs | 5 ++++- .../identity/core/offchain-worker-executor/src/executor.rs | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/tee-worker/bitacross/core/offchain-worker-executor/src/executor.rs b/tee-worker/bitacross/core/offchain-worker-executor/src/executor.rs index 51f9590e12..9f9f1a84c3 100644 --- a/tee-worker/bitacross/core/offchain-worker-executor/src/executor.rs +++ b/tee-worker/bitacross/core/offchain-worker-executor/src/executor.rs @@ -265,7 +265,9 @@ mod tests { stf_mock::{GetterMock, TrustedCallSignedMock}, }; use itp_top_pool_author::mocks::AuthorApiMock; - use itp_types::{Block as ParentchainBlock, RsaRequest}; + use itp_types::{ + parentchain::Header as ParentchainHeader, Block as ParentchainBlock, RsaRequest, + }; use itp_test::mock::stf_mock::mock_top_indirect_trusted_call_signed; use std::boxed::Box; @@ -287,6 +289,7 @@ mod tests { TestStfInterface, TrustedCallSignedMock, GetterMock, + ParentchainHeader, >; const EVENT_COUNT_KEY: &[u8] = b"event_count"; diff --git a/tee-worker/identity/core/offchain-worker-executor/src/executor.rs b/tee-worker/identity/core/offchain-worker-executor/src/executor.rs index 51f9590e12..9f9f1a84c3 100644 --- a/tee-worker/identity/core/offchain-worker-executor/src/executor.rs +++ b/tee-worker/identity/core/offchain-worker-executor/src/executor.rs @@ -265,7 +265,9 @@ mod tests { stf_mock::{GetterMock, TrustedCallSignedMock}, }; use itp_top_pool_author::mocks::AuthorApiMock; - use itp_types::{Block as ParentchainBlock, RsaRequest}; + use itp_types::{ + parentchain::Header as ParentchainHeader, Block as ParentchainBlock, RsaRequest, + }; use itp_test::mock::stf_mock::mock_top_indirect_trusted_call_signed; use std::boxed::Box; @@ -287,6 +289,7 @@ mod tests { TestStfInterface, TrustedCallSignedMock, GetterMock, + ParentchainHeader, >; const EVENT_COUNT_KEY: &[u8] = b"event_count"; From 2fcf96c48cd4cd1f736f7ba1f9b229bfd301fa02 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 10 Oct 2024 09:28:01 +0000 Subject: [PATCH 23/39] chore: add GPL license headers to source files --- common/primitives/core/src/omni_account.rs | 16 ++++++++++++++++ .../core/omni-account/src/in_memory_store.rs | 16 ++++++++++++++++ .../litentry/core/omni-account/src/repository.rs | 16 ++++++++++++++++ 3 files changed, 48 insertions(+) diff --git a/common/primitives/core/src/omni_account.rs b/common/primitives/core/src/omni_account.rs index 514ae890c5..71c3a5784d 100644 --- a/common/primitives/core/src/omni_account.rs +++ b/common/primitives/core/src/omni_account.rs @@ -1,3 +1,19 @@ +// Copyright 2020-2024 Trust Computing GmbH. +// This file is part of Litentry. +// +// Litentry is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// Litentry is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Litentry. If not, see . + use crate::{Hash, Identity, Vec}; use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; diff --git a/tee-worker/identity/litentry/core/omni-account/src/in_memory_store.rs b/tee-worker/identity/litentry/core/omni-account/src/in_memory_store.rs index 4a8483e957..12572f5dba 100644 --- a/tee-worker/identity/litentry/core/omni-account/src/in_memory_store.rs +++ b/tee-worker/identity/litentry/core/omni-account/src/in_memory_store.rs @@ -1,3 +1,19 @@ +// Copyright 2020-2024 Trust Computing GmbH. +// This file is part of Litentry. +// +// Litentry is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// Litentry is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Litentry. If not, see . + use crate::{AccountId, BTreeMap, Error, OmniAccountMembers, OmniAccounts}; use lazy_static::lazy_static; diff --git a/tee-worker/identity/litentry/core/omni-account/src/repository.rs b/tee-worker/identity/litentry/core/omni-account/src/repository.rs index 49ef4b2be1..6aad248d29 100644 --- a/tee-worker/identity/litentry/core/omni-account/src/repository.rs +++ b/tee-worker/identity/litentry/core/omni-account/src/repository.rs @@ -1,3 +1,19 @@ +// Copyright 2020-2024 Trust Computing GmbH. +// This file is part of Litentry. +// +// Litentry is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// Litentry is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Litentry. If not, see . + use crate::{AccountId, Error, Header, OmniAccountMembers, OmniAccounts, ParentchainId}; use alloc::vec::Vec; use frame_support::storage::storage_prefix; From 039bbeab3d5f63cb8265c19436c2fb147e846485 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 10 Oct 2024 09:42:45 +0000 Subject: [PATCH 24/39] removing unused import --- .../identity/enclave-runtime/src/test/fixtures/test_setup.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/tee-worker/identity/enclave-runtime/src/test/fixtures/test_setup.rs b/tee-worker/identity/enclave-runtime/src/test/fixtures/test_setup.rs index 570b3e589e..e413053f74 100644 --- a/tee-worker/identity/enclave-runtime/src/test/fixtures/test_setup.rs +++ b/tee-worker/identity/enclave-runtime/src/test/fixtures/test_setup.rs @@ -26,7 +26,6 @@ use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMet use itp_ocall_api::EnclaveAttestationOCallApi; use itp_sgx_crypto::{ ed25519_derivation::DeriveEd25519, - key_repository::KeyRepository, mocks::KeyRepositoryMock, Aes, // TODO: use Aes256 when available }; From 5fc38748edf822a9f9e6868c2d2a21cbd6501d97 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 10 Oct 2024 09:48:15 +0000 Subject: [PATCH 25/39] refactor: update get_storage_keys to accept optional header --- tee-worker/common/core-primitives/ocall-api/src/lib.rs | 6 +++++- .../common/core-primitives/ocall-api/src/mock.rs | 6 +++++- .../core-primitives/test/src/mock/onchain_mock.rs | 6 +++++- .../enclave-runtime/src/ocall/on_chain_ocall.rs | 10 +++++++--- .../src/test/mocks/propose_to_import_call_mock.rs | 6 +++++- .../identity/litentry/core/assertion-build/src/a13.rs | 3 ++- .../litentry/core/omni-account/src/repository.rs | 2 +- 7 files changed, 30 insertions(+), 9 deletions(-) diff --git a/tee-worker/common/core-primitives/ocall-api/src/lib.rs b/tee-worker/common/core-primitives/ocall-api/src/lib.rs index e3168a19cf..8e196fdf99 100644 --- a/tee-worker/common/core-primitives/ocall-api/src/lib.rs +++ b/tee-worker/common/core-primitives/ocall-api/src/lib.rs @@ -121,7 +121,11 @@ pub trait EnclaveOnChainOCallApi: Clone + Send + Sync { // Litentry // given a key prefix, get all storage keys - fn get_storage_keys(&self, key_prefix: Vec) -> Result>>; + fn get_storage_keys>( + &self, + key_prefix: Vec, + header: Option<&H>, + ) -> Result>>; } /// Trait for sending metric updates. diff --git a/tee-worker/common/core-primitives/ocall-api/src/mock.rs b/tee-worker/common/core-primitives/ocall-api/src/mock.rs index c746865a93..fd6da98d47 100644 --- a/tee-worker/common/core-primitives/ocall-api/src/mock.rs +++ b/tee-worker/common/core-primitives/ocall-api/src/mock.rs @@ -94,7 +94,11 @@ impl EnclaveOnChainOCallApi for OnchainMock { Ok(entries) } - fn get_storage_keys(&self, _key_prefix: Vec) -> Result>, OCallApiError> { + fn get_storage_keys>( + &self, + _key_prefix: Vec, + _header: Option<&H>, + ) -> Result>, OCallApiError> { Ok(Default::default()) } } diff --git a/tee-worker/common/core-primitives/test/src/mock/onchain_mock.rs b/tee-worker/common/core-primitives/test/src/mock/onchain_mock.rs index a0163f8df0..021875620e 100644 --- a/tee-worker/common/core-primitives/test/src/mock/onchain_mock.rs +++ b/tee-worker/common/core-primitives/test/src/mock/onchain_mock.rs @@ -223,7 +223,11 @@ impl EnclaveOnChainOCallApi for OnchainMock { Ok(entries) } - fn get_storage_keys(&self, _key_prefix: Vec) -> Result>, itp_ocall_api::Error> { + fn get_storage_keys>( + &self, + _key_prefix: Vec, + _header: Option<&H>, + ) -> Result>, itp_ocall_api::Error> { Ok(Default::default()) } } diff --git a/tee-worker/identity/enclave-runtime/src/ocall/on_chain_ocall.rs b/tee-worker/identity/enclave-runtime/src/ocall/on_chain_ocall.rs index e80c1fb112..124f7fabd9 100644 --- a/tee-worker/identity/enclave-runtime/src/ocall/on_chain_ocall.rs +++ b/tee-worker/identity/enclave-runtime/src/ocall/on_chain_ocall.rs @@ -125,9 +125,13 @@ impl EnclaveOnChainOCallApi for OcallApi { Ok(storage_entries) } - fn get_storage_keys(&self, key_prefix: Vec) -> Result>> { - // always using the latest state - we need to support optional header - let requests = vec![WorkerRequest::ChainStorageKeys(key_prefix, None)]; + fn get_storage_keys>( + &self, + key_prefix: Vec, + header: Option<&H>, + ) -> Result>> { + let header_hash = header.map(|h| h.hash()); + let requests = vec![WorkerRequest::ChainStorageKeys(key_prefix, header_hash)]; let responses: Vec>> = self .worker_request::>(requests, &ParentchainId::Litentry)? diff --git a/tee-worker/identity/enclave-runtime/src/test/mocks/propose_to_import_call_mock.rs b/tee-worker/identity/enclave-runtime/src/test/mocks/propose_to_import_call_mock.rs index 7f68b55a69..67a1b4ea64 100644 --- a/tee-worker/identity/enclave-runtime/src/test/mocks/propose_to_import_call_mock.rs +++ b/tee-worker/identity/enclave-runtime/src/test/mocks/propose_to_import_call_mock.rs @@ -84,7 +84,11 @@ impl EnclaveOnChainOCallApi for ProposeToImportOCallApi { todo!() } - fn get_storage_keys(&self, _key_prefix: Vec) -> Result>> { + fn get_storage_keys>( + &self, + _key_prefix: Vec, + _header: Option<&H>, + ) -> Result>> { todo!() } } diff --git a/tee-worker/identity/litentry/core/assertion-build/src/a13.rs b/tee-worker/identity/litentry/core/assertion-build/src/a13.rs index 0f46664799..8c1cd1904a 100644 --- a/tee-worker/identity/litentry/core/assertion-build/src/a13.rs +++ b/tee-worker/identity/litentry/core/assertion-build/src/a13.rs @@ -24,6 +24,7 @@ use crate::*; use codec::Decode; use frame_support::storage::storage_prefix; use itp_ocall_api::EnclaveOnChainOCallApi; +use itp_types::parentchain::Header; use lc_credentials::IssuerRuntimeVersion; use litentry_primitives::Address32; @@ -39,7 +40,7 @@ pub fn build( debug!("Assertion A13 build, who: {:?}", account_id_to_string(&who)); let key_prefix = storage_prefix(b"VCManagement", b"Delegatee"); - let response = ocall_api.get_storage_keys(key_prefix.into()).map_err(|_| { + let response = ocall_api.get_storage_keys::
(key_prefix.into(), None).map_err(|_| { Error::RequestVCFailed(Assertion::A13(who.clone()), ErrorDetail::ParseError) })?; let keys: Vec = response diff --git a/tee-worker/identity/litentry/core/omni-account/src/repository.rs b/tee-worker/identity/litentry/core/omni-account/src/repository.rs index 6aad248d29..9360a35a03 100644 --- a/tee-worker/identity/litentry/core/omni-account/src/repository.rs +++ b/tee-worker/identity/litentry/core/omni-account/src/repository.rs @@ -68,7 +68,7 @@ impl GetAccountStoresRepository let account_store_key_prefix = storage_prefix(b"OmniAccount", b"AccountStore"); let account_store_storage_keys_response = self .ocall_api - .get_storage_keys(account_store_key_prefix.into()) + .get_storage_keys(account_store_key_prefix.into(), Some(&self.header)) .map_err(|_| Error::OCallApiError("Failed to get storage keys"))?; let account_store_storage_keys = account_store_storage_keys_response .into_iter() From cdac91f85d21173caacfaf8b31efa466c83561c5 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 10 Oct 2024 12:26:15 +0000 Subject: [PATCH 26/39] cleaning up imports --- tee-worker/bitacross/app-libs/stf/src/stf_sgx_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tee-worker/bitacross/app-libs/stf/src/stf_sgx_tests.rs b/tee-worker/bitacross/app-libs/stf/src/stf_sgx_tests.rs index 89feb2d132..77d14062c2 100644 --- a/tee-worker/bitacross/app-libs/stf/src/stf_sgx_tests.rs +++ b/tee-worker/bitacross/app-libs/stf/src/stf_sgx_tests.rs @@ -19,7 +19,7 @@ use crate::{Getter, State, Stf, TrustedCall, TrustedCallSigned}; use ita_sgx_runtime::Runtime; use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; use itp_ocall_api::mock::OnchainMock; -use itp_sgx_crypto::{key_repository::AccessKey, mocks::KeyRepositoryMock, Aes}; +use itp_sgx_crypto::{mocks::KeyRepositoryMock, Aes}; use itp_stf_interface::{ sudo_pallet::SudoPalletInterface, system_pallet::SystemPalletAccountInterface, InitState, StateCallInterface, From f68aa0acabd1363e07e6f31bc13dda9466302b84 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 10 Oct 2024 12:26:26 +0000 Subject: [PATCH 27/39] updating bitacross on_chain_ocall --- .../enclave-runtime/src/ocall/on_chain_ocall.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/tee-worker/bitacross/enclave-runtime/src/ocall/on_chain_ocall.rs b/tee-worker/bitacross/enclave-runtime/src/ocall/on_chain_ocall.rs index e80c1fb112..124f7fabd9 100644 --- a/tee-worker/bitacross/enclave-runtime/src/ocall/on_chain_ocall.rs +++ b/tee-worker/bitacross/enclave-runtime/src/ocall/on_chain_ocall.rs @@ -125,9 +125,13 @@ impl EnclaveOnChainOCallApi for OcallApi { Ok(storage_entries) } - fn get_storage_keys(&self, key_prefix: Vec) -> Result>> { - // always using the latest state - we need to support optional header - let requests = vec![WorkerRequest::ChainStorageKeys(key_prefix, None)]; + fn get_storage_keys>( + &self, + key_prefix: Vec, + header: Option<&H>, + ) -> Result>> { + let header_hash = header.map(|h| h.hash()); + let requests = vec![WorkerRequest::ChainStorageKeys(key_prefix, header_hash)]; let responses: Vec>> = self .worker_request::>(requests, &ParentchainId::Litentry)? From ceb899a71e7c80fe325d4a0293f9681191255113 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 10 Oct 2024 15:11:10 +0000 Subject: [PATCH 28/39] Revert "updating bitacross executor types" This reverts commit ad058bbd33ad67cff3d659e5547e7b33eac35d9a. --- tee-worker/bitacross/app-libs/stf/Cargo.toml | 2 - .../bitacross/app-libs/stf/src/stf_sgx.rs | 45 +--- .../app-libs/stf/src/stf_sgx_tests.rs | 14 +- .../app-libs/stf/src/trusted_call.rs | 15 +- .../stf-executor/src/executor.rs | 199 ++++-------------- .../stf-executor/src/executor_tests.rs | 14 +- .../core-primitives/stf-executor/src/mocks.rs | 6 +- .../stf-executor/src/traits.rs | 6 +- .../offchain-worker-executor/src/executor.rs | 14 +- .../bitacross/enclave-runtime/Cargo.lock | 11 +- .../src/initialization/global_components.rs | 8 +- .../parentchain/integritee_parachain.rs | 14 +- .../parentchain/integritee_solochain.rs | 14 +- .../parentchain/target_a_parachain.rs | 18 +- .../parentchain/target_a_solochain.rs | 18 +- .../parentchain/target_b_parachain.rs | 18 +- .../parentchain/target_b_solochain.rs | 18 +- .../src/test/enclave_signer_tests.rs | 23 +- .../src/test/fixtures/test_setup.rs | 18 +- .../enclave-runtime/src/test/mocks/types.rs | 7 +- .../enclave-runtime/src/test/tests_main.rs | 40 +--- 21 files changed, 108 insertions(+), 414 deletions(-) diff --git a/tee-worker/bitacross/app-libs/stf/Cargo.toml b/tee-worker/bitacross/app-libs/stf/Cargo.toml index 727b2c4610..d43d9a633a 100644 --- a/tee-worker/bitacross/app-libs/stf/Cargo.toml +++ b/tee-worker/bitacross/app-libs/stf/Cargo.toml @@ -49,7 +49,6 @@ sgx = [ "sp-io/sgx", "itp-node-api/sgx", "litentry-primitives/sgx", - "itp-sgx-crypto/sgx", ] std = [ # crates.io @@ -71,7 +70,6 @@ std = [ "pallet-parentchain/std", "sp-io/std", "litentry-primitives/std", - "itp-sgx-crypto/std", ] test = [] development = [ diff --git a/tee-worker/bitacross/app-libs/stf/src/stf_sgx.rs b/tee-worker/bitacross/app-libs/stf/src/stf_sgx.rs index cbdc572c9c..6412b5cf78 100644 --- a/tee-worker/bitacross/app-libs/stf/src/stf_sgx.rs +++ b/tee-worker/bitacross/app-libs/stf/src/stf_sgx.rs @@ -27,9 +27,6 @@ use ita_sgx_runtime::{ Executive, ParentchainInstanceLitentry, ParentchainInstanceTargetA, ParentchainInstanceTargetB, }; use itp_node_api::metadata::{provider::AccessNodeMetadata, NodeMetadataTrait}; -use itp_ocall_api::EnclaveOnChainOCallApi; -// TODO: use use Aes256 when available -use itp_sgx_crypto::{key_repository::AccessKey, Aes}; use itp_sgx_externalities::SgxExternalitiesTrait; use itp_stf_interface::{ parentchain_pallet::ParentchainPalletInstancesInterface, @@ -49,7 +46,7 @@ use itp_types::{ }; use itp_utils::stringify::account_id_to_string; use log::*; -use sp_runtime::traits::{Header as HeaderTrait, StaticLookup}; +use sp_runtime::traits::StaticLookup; use std::{fmt::Debug, format, prelude::v1::*, sync::Arc, vec}; impl InitState for Stf @@ -138,27 +135,11 @@ where } } -impl< - TCS, - G, - State, - Runtime, - NodeMetadataRepository, - OCallApi, - PH, - OnChainEncryptionKeyRepository, - > - StateCallInterface< - TCS, - State, - NodeMetadataRepository, - OCallApi, - PH, - OnChainEncryptionKeyRepository, - > for Stf +impl + StateCallInterface for Stf where TCS: PartialEq - + ExecuteCall + + ExecuteCall + Encode + Decode + Debug @@ -169,9 +150,6 @@ where State: SgxExternalitiesTrait + Debug, NodeMetadataRepository: AccessNodeMetadata, NodeMetadataRepository::MetadataType: NodeMetadataTrait, - OCallApi: EnclaveOnChainOCallApi, - PH: HeaderTrait, - OnChainEncryptionKeyRepository: AccessKey, { type Error = TCS::Error; type Result = TCS::Result; @@ -183,21 +161,8 @@ where top_hash: H256, calls: &mut Vec, node_metadata_repo: Arc, - ocall_api: Arc, - parentchain_header: &PH, - on_chain_encryption_key_repo: Arc, ) -> Result { - state.execute_with(|| { - call.execute( - shard, - top_hash, - calls, - node_metadata_repo, - ocall_api, - parentchain_header, - on_chain_encryption_key_repo, - ) - }) + state.execute_with(|| call.execute(shard, top_hash, calls, node_metadata_repo)) } } diff --git a/tee-worker/bitacross/app-libs/stf/src/stf_sgx_tests.rs b/tee-worker/bitacross/app-libs/stf/src/stf_sgx_tests.rs index 77d14062c2..8a5eb0c111 100644 --- a/tee-worker/bitacross/app-libs/stf/src/stf_sgx_tests.rs +++ b/tee-worker/bitacross/app-libs/stf/src/stf_sgx_tests.rs @@ -25,23 +25,16 @@ use itp_stf_interface::{ StateCallInterface, }; use itp_stf_primitives::types::{AccountId, ShardIdentifier}; -use itp_types::{parentchain::ParentchainId, Header}; +use itp_types::parentchain::ParentchainId; use litentry_primitives::LitentryMultiSignature; use sp_core::{ ed25519::{Pair as Ed25519Pair, Signature as Ed25519Signature}, Pair, }; -use sp_runtime::traits::Header as HeaderTrait; use std::{sync::Arc, vec::Vec}; -type EncryptionKeyRepositoryMock = KeyRepositoryMock; - pub type StfState = Stf; -pub fn latest_parentchain_header() -> Header { - Header::new(1, Default::default(), Default::default(), [69; 32].into(), Default::default()) -} - pub fn enclave_account_initialization_works() { let enclave_account = AccountId::new([2u8; 32]); let mut state = StfState::init_state(enclave_account.clone()); @@ -57,7 +50,6 @@ pub fn shield_funds_increments_signer_account_nonce() { let enclave_call_signer = Ed25519Pair::from_seed(b"14672678901234567890123456789012"); let enclave_signer_account_id: AccountId = enclave_call_signer.public().into(); let mut state = StfState::init_state(enclave_signer_account_id.clone()); - let ocall_api = Arc::new(OnchainMock::default()); let shield_funds_call = TrustedCallSigned::new( TrustedCall::balance_shield( @@ -72,7 +64,6 @@ pub fn shield_funds_increments_signer_account_nonce() { let repo = Arc::new(NodeMetadataRepository::new(NodeMetadataMock::new())); let shard = ShardIdentifier::default(); - let encryption_key_repository = Arc::new(EncryptionKeyRepositoryMock::new(Aes::default())); StfState::execute_call( &mut state, &shard, @@ -80,9 +71,6 @@ pub fn shield_funds_increments_signer_account_nonce() { Default::default(), &mut Vec::new(), repo, - ocall_api.clone(), - &latest_parentchain_header(), - encryption_key_repository.clone(), ) .unwrap(); assert_eq!(1, StfState::get_account_nonce(&mut state, &enclave_signer_account_id)); diff --git a/tee-worker/bitacross/app-libs/stf/src/trusted_call.rs b/tee-worker/bitacross/app-libs/stf/src/trusted_call.rs index 003f1e005e..8d8167d46b 100644 --- a/tee-worker/bitacross/app-libs/stf/src/trusted_call.rs +++ b/tee-worker/bitacross/app-libs/stf/src/trusted_call.rs @@ -24,9 +24,6 @@ use codec::{Decode, Encode}; use frame_support::{ensure, traits::UnfilteredDispatchable}; pub use ita_sgx_runtime::{Balance, Index, Runtime, System}; use itp_node_api::metadata::{provider::AccessNodeMetadata, NodeMetadataTrait}; -use itp_ocall_api::EnclaveOnChainOCallApi; -// TODO: use use Aes256 when available -use itp_sgx_crypto::{key_repository::AccessKey, Aes}; use itp_stf_interface::ExecuteCall; use itp_stf_primitives::{ @@ -49,7 +46,7 @@ use sp_core::{ ed25519, }; use sp_io::hashing::blake2_256; -use sp_runtime::{traits::Header as HeaderTrait, MultiAddress}; +use sp_runtime::MultiAddress; use std::{format, prelude::v1::*, sync::Arc}; #[derive(Encode, Decode, Clone, Debug, PartialEq, Eq)] @@ -159,15 +156,10 @@ impl TrustedCallVerification for TrustedCallSigned { } } -impl - ExecuteCall - for TrustedCallSigned +impl ExecuteCall for TrustedCallSigned where NodeMetadataRepository: AccessNodeMetadata, NodeMetadataRepository::MetadataType: NodeMetadataTrait, - OCallApi: EnclaveOnChainOCallApi, - PH: HeaderTrait, - OnChainEncryptionKeyRepository: AccessKey, { type Error = StfError; type Result = TrustedCallResult; @@ -211,9 +203,6 @@ where _top_hash: H256, _calls: &mut Vec, _node_metadata_repo: Arc, - _ocall_api: Arc, - _parentchain_header: &PH, - _on_chain_encryption_key_repo: Arc, ) -> Result { let sender = self.call.sender_identity().clone(); let account_id: AccountId = sender.to_account_id().ok_or(Self::Error::InvalidAccount)?; diff --git a/tee-worker/bitacross/core-primitives/stf-executor/src/executor.rs b/tee-worker/bitacross/core-primitives/stf-executor/src/executor.rs index 80e15e4742..ffc6d92fce 100644 --- a/tee-worker/bitacross/core-primitives/stf-executor/src/executor.rs +++ b/tee-worker/bitacross/core-primitives/stf-executor/src/executor.rs @@ -24,8 +24,6 @@ use codec::{Decode, Encode}; use itp_enclave_metrics::EnclaveMetric; use itp_node_api::metadata::{provider::AccessNodeMetadata, NodeMetadataTrait}; use itp_ocall_api::{EnclaveAttestationOCallApi, EnclaveMetricsOCallApi, EnclaveOnChainOCallApi}; -// TODO: use Aes256 when available -use itp_sgx_crypto::{key_repository::AccessKey, Aes}; use itp_sgx_externalities::{SgxExternalitiesTrait, StateHash}; use itp_stf_interface::{ parentchain_pallet::ParentchainPalletInstancesInterface, @@ -38,7 +36,7 @@ use itp_stf_primitives::{ use itp_stf_state_handler::{handle_state::HandleState, query_shard_state::QueryShardState}; use itp_time_utils::duration_now; use itp_types::{ - parentchain::{ParentchainCall, ParentchainId}, + parentchain::{Header as ParentchainHeader, ParentchainCall, ParentchainId}, storage::StorageEntryVerified, H256, }; @@ -49,46 +47,20 @@ use std::{ time::Duration, vec, vec::Vec, }; -pub struct StfExecutor< - OCallApi, - StateHandler, - NodeMetadataRepository, - Stf, - TCS, - G, - PH, - OnChainEncryptionKeyRepository, -> where +pub struct StfExecutor +where TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, { ocall_api: Arc, state_handler: Arc, node_metadata_repo: Arc, - on_chain_encryption_key_repository: Arc, - _phantom: PhantomData<(Stf, TCS, G, PH)>, + _phantom: PhantomData<(Stf, TCS, G)>, } -impl< - OCallApi, - StateHandler, - NodeMetadataRepository, - Stf, - TCS, - G, - PH, - OnChainEncryptionKeyRepository, - > - StfExecutor< - OCallApi, - StateHandler, - NodeMetadataRepository, - Stf, - TCS, - G, - PH, - OnChainEncryptionKeyRepository, - > where +impl + StfExecutor +where OCallApi: EnclaveAttestationOCallApi + EnclaveOnChainOCallApi + EnclaveMetricsOCallApi, StateHandler: HandleState, StateHandler::StateT: SgxExternalitiesTrait + Encode, @@ -97,42 +69,19 @@ impl< Stf: UpdateState< StateHandler::StateT, ::SgxExternalitiesDiffType, - > + StateCallInterface< - TCS, - StateHandler::StateT, - NodeMetadataRepository, - OCallApi, - PH, - OnChainEncryptionKeyRepository, - >, + > + StateCallInterface, ::SgxExternalitiesDiffType: IntoIterator, Option>)> + From, Option>>>, - >::Error: Debug, + >::Error: Debug, TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, - PH: HeaderTrait, - OnChainEncryptionKeyRepository: AccessKey, { pub fn new( ocall_api: Arc, state_handler: Arc, node_metadata_repo: Arc, - on_chain_encryption_key_repository: Arc, ) -> Self { - StfExecutor { - ocall_api, - state_handler, - node_metadata_repo, - on_chain_encryption_key_repository, - _phantom: PhantomData, - } + StfExecutor { ocall_api, state_handler, node_metadata_repo, _phantom: PhantomData } } /// Execute a trusted call on the STF @@ -141,14 +90,17 @@ impl< /// an invalid trusted call, which results in `Ok(ExecutionStatus::Failure)`. The latter /// can be used to remove the trusted call from a queue. In the former case we might keep the /// trusted call and just re-try the operation. - fn execute_trusted_call_on_stf( + fn execute_trusted_call_on_stf( &self, state: &mut StateHandler::StateT, trusted_operation: &TrustedOperation, - parentchain_header: &PH, + _header: &PH, shard: &ShardIdentifier, post_processing: StatePostProcessing, - ) -> Result> { + ) -> Result> + where + PH: HeaderTrait, + { debug!("query mrenclave of self"); let mrenclave = self.ocall_api.get_mrenclave_of_self()?; @@ -180,9 +132,6 @@ impl< trusted_operation.hash(), &mut extrinsic_call_backs, self.node_metadata_repo.clone(), - self.ocall_api.clone(), - parentchain_header, - self.on_chain_encryption_key_repository.clone(), ) { Err(e) => { if let Err(e) = @@ -231,26 +180,10 @@ impl< } } -impl< - OCallApi, - StateHandler, - NodeMetadataRepository, - Stf, - TCS, - G, - PH, - OnChainEncryptionKeyRepository, - > StfUpdateState - for StfExecutor< - OCallApi, - StateHandler, - NodeMetadataRepository, - Stf, - TCS, - G, - PH, - OnChainEncryptionKeyRepository, - > where +impl + StfUpdateState + for StfExecutor +where OCallApi: EnclaveAttestationOCallApi + EnclaveOnChainOCallApi, StateHandler: HandleState + QueryShardState, StateHandler::StateT: SgxExternalitiesTrait + Encode, @@ -258,18 +191,21 @@ impl< Stf: UpdateState< StateHandler::StateT, ::SgxExternalitiesDiffType, - > + ParentchainPalletInstancesInterface, + > + ParentchainPalletInstancesInterface, ::SgxExternalitiesDiffType: IntoIterator, Option>)>, - >::Error: Debug, + >::Error: + Debug, ::SgxExternalitiesDiffType: From, Option>>>, TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, - PH: HeaderTrait, - OnChainEncryptionKeyRepository: AccessKey, { - fn update_states(&self, header: &PH, parentchain_id: &ParentchainId) -> Result<()> { + fn update_states( + &self, + header: &ParentchainHeader, + parentchain_id: &ParentchainId, + ) -> Result<()> { debug!("Update STF storage upon block import!"); let storage_hashes = Stf::storage_hashes_to_update_on_block(parentchain_id); @@ -309,46 +245,28 @@ impl< } } -impl< - OCallApi, - StateHandler, - NodeMetadataRepository, - Stf, - TCS, - G, - PH, - OnChainEncryptionKeyRepository, - > - StfExecutor< - OCallApi, - StateHandler, - NodeMetadataRepository, - Stf, - TCS, - G, - PH, - OnChainEncryptionKeyRepository, - > where +impl + StfExecutor +where ::SgxExternalitiesDiffType: From, Option>>> + IntoIterator, Option>)>, - >::Error: Debug, + >::Error: + Debug, NodeMetadataRepository: AccessNodeMetadata, OCallApi: EnclaveAttestationOCallApi + EnclaveOnChainOCallApi, StateHandler: HandleState + QueryShardState, StateHandler::StateT: Encode + SgxExternalitiesTrait, - Stf: ParentchainPalletInstancesInterface + Stf: ParentchainPalletInstancesInterface + UpdateState< StateHandler::StateT, ::SgxExternalitiesDiffType, >, TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, - PH: HeaderTrait, - OnChainEncryptionKeyRepository: AccessKey, { fn initialize_new_shards( &self, - header: &PH, + header: &ParentchainHeader, state_diff_update: &BTreeMap, Option>>, shards: &Vec, ) -> Result<()> { @@ -377,26 +295,9 @@ impl< } } -impl< - OCallApi, - StateHandler, - NodeMetadataRepository, - Stf, - TCS, - G, - PH, - OnChainEncryptionKeyRepository, - > StateUpdateProposer - for StfExecutor< - OCallApi, - StateHandler, - NodeMetadataRepository, - Stf, - TCS, - G, - PH, - OnChainEncryptionKeyRepository, - > where +impl StateUpdateProposer + for StfExecutor +where OCallApi: EnclaveAttestationOCallApi + EnclaveOnChainOCallApi + EnclaveMetricsOCallApi, StateHandler: HandleState, StateHandler::StateT: SgxExternalitiesTrait + Encode + StateHash, @@ -406,35 +307,20 @@ impl< Stf: UpdateState< StateHandler::StateT, ::SgxExternalitiesDiffType, - > + StateCallInterface< - TCS, - StateHandler::StateT, - NodeMetadataRepository, - OCallApi, - PH, - OnChainEncryptionKeyRepository, - > + RuntimeUpgradeInterface, + > + StateCallInterface + + RuntimeUpgradeInterface, ::SgxExternalitiesDiffType: IntoIterator, Option>)>, ::SgxExternalitiesDiffType: From, Option>>>, - >::Error: Debug, + >::Error: Debug, >::Error: Debug, TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, - PH: HeaderTrait, - OnChainEncryptionKeyRepository: AccessKey, { type Externalities = StateHandler::StateT; - fn propose_state_update( + fn propose_state_update( &self, trusted_calls: &[TrustedOperation], header: &PH, @@ -443,6 +329,7 @@ impl< prepare_state_function: F, ) -> Result> where + PH: HeaderTrait, F: FnOnce(Self::Externalities) -> Self::Externalities, { let ends_at = duration_now() + max_exec_duration; diff --git a/tee-worker/bitacross/core-primitives/stf-executor/src/executor_tests.rs b/tee-worker/bitacross/core-primitives/stf-executor/src/executor_tests.rs index 40e8e499f4..2eb0185bcd 100644 --- a/tee-worker/bitacross/core-primitives/stf-executor/src/executor_tests.rs +++ b/tee-worker/bitacross/core-primitives/stf-executor/src/executor_tests.rs @@ -20,8 +20,6 @@ use codec::Encode; use itc_parentchain_test::ParentchainHeaderBuilder; use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; use itp_ocall_api::EnclaveAttestationOCallApi; -// TODO: use Aes256 when available -use itp_sgx_crypto::{mocks::KeyRepositoryMock, Aes}; use itp_sgx_externalities::{SgxExternalities as State, SgxExternalitiesTrait}; use itp_stf_primitives::{traits::TrustedCallSigning, types::ShardIdentifier}; use itp_stf_state_handler::handle_state::HandleState; @@ -30,7 +28,7 @@ use itp_test::mock::{ onchain_mock::OnchainMock, stf_mock::{GetterMock, StfMock, TrustedCallMock, TrustedCallSignedMock}, }; -use itp_types::{parentchain::Header as ParentchainHeader, H256}; +use itp_types::H256; use sp_core::{ed25519, Pair}; use sp_runtime::app_crypto::sp_core::blake2_256; use std::{sync::Arc, time::Duration, vec}; @@ -246,8 +244,6 @@ fn stf_executor() -> ( StfMock, TrustedCallSignedMock, GetterMock, - ParentchainHeader, - KeyRepositoryMock, >, Arc, Arc, @@ -255,13 +251,7 @@ fn stf_executor() -> ( let ocall_api = Arc::new(OnchainMock::default()); let state_handler = Arc::new(HandleStateMock::default()); let node_metadata_repo = Arc::new(NodeMetadataRepository::new(NodeMetadataMock::new())); - let encryption_key_repository = Arc::new(KeyRepositoryMock::new(Aes::default())); - let executor = StfExecutor::new( - ocall_api.clone(), - state_handler.clone(), - node_metadata_repo, - encryption_key_repository, - ); + let executor = StfExecutor::new(ocall_api.clone(), state_handler.clone(), node_metadata_repo); (executor, ocall_api, state_handler) } diff --git a/tee-worker/bitacross/core-primitives/stf-executor/src/mocks.rs b/tee-worker/bitacross/core-primitives/stf-executor/src/mocks.rs index 96a554501b..d328a2e24e 100644 --- a/tee-worker/bitacross/core-primitives/stf-executor/src/mocks.rs +++ b/tee-worker/bitacross/core-primitives/stf-executor/src/mocks.rs @@ -59,16 +59,15 @@ impl StfExecutorMock { } } -impl StateUpdateProposer for StfExecutorMock +impl StateUpdateProposer for StfExecutorMock where State: SgxExternalitiesTrait + Encode + Clone, TCS: PartialEq + Encode + Decode + Clone + Debug + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Clone + Debug + Send + Sync, - PH: HeaderTrait, { type Externalities = State; - fn propose_state_update( + fn propose_state_update( &self, trusted_calls: &[TrustedOperation], _header: &PH, @@ -77,6 +76,7 @@ where prepare_state_function: F, ) -> Result> where + PH: HeaderTrait, F: FnOnce(Self::Externalities) -> Self::Externalities, { let mut lock = self.state.write().unwrap(); diff --git a/tee-worker/bitacross/core-primitives/stf-executor/src/traits.rs b/tee-worker/bitacross/core-primitives/stf-executor/src/traits.rs index 3b77b99588..62e788141a 100644 --- a/tee-worker/bitacross/core-primitives/stf-executor/src/traits.rs +++ b/tee-worker/bitacross/core-primitives/stf-executor/src/traits.rs @@ -55,11 +55,10 @@ where } /// Proposes a state update to `Externalities`. -pub trait StateUpdateProposer +pub trait StateUpdateProposer where TCS: PartialEq + Encode + Decode + Debug + Send + Sync, G: PartialEq + Encode + Decode + Debug + Send + Sync, - PH: HeaderTrait, { type Externalities: SgxExternalitiesTrait + Encode; @@ -67,7 +66,7 @@ where /// /// All executed call hashes and the mutated state are returned. /// If the time expires, any remaining trusted calls within the batch will be ignored. - fn propose_state_update( + fn propose_state_update( &self, trusted_calls: &[TrustedOperation], header: &PH, @@ -76,6 +75,7 @@ where prepare_state_function: F, ) -> Result> where + PH: HeaderTrait, F: FnOnce(Self::Externalities) -> Self::Externalities; } diff --git a/tee-worker/bitacross/core/offchain-worker-executor/src/executor.rs b/tee-worker/bitacross/core/offchain-worker-executor/src/executor.rs index 9f9f1a84c3..a9fcee8f66 100644 --- a/tee-worker/bitacross/core/offchain-worker-executor/src/executor.rs +++ b/tee-worker/bitacross/core/offchain-worker-executor/src/executor.rs @@ -30,7 +30,7 @@ use itp_stf_state_handler::{handle_state::HandleState, query_shard_state::QueryS use itp_top_pool_author::traits::AuthorApi; use itp_types::{parentchain::ParentchainCall, OpaqueCall, ShardIdentifier, H256}; use log::*; -use sp_runtime::traits::{Block, Header as HeaderTrait}; +use sp_runtime::traits::Block; use std::{marker::PhantomData, sync::Arc, time::Duration, vec::Vec}; /// Off-chain worker executor implementation. @@ -51,14 +51,13 @@ pub struct Executor< Stf, TCS, G, - PH, > { top_pool_author: Arc, stf_executor: Arc, state_handler: Arc, validator_accessor: Arc, extrinsics_factory: Arc, - _phantom: PhantomData<(ParentchainBlock, Stf, TCS, G, PH)>, + _phantom: PhantomData<(ParentchainBlock, Stf, TCS, G)>, } impl< @@ -71,7 +70,6 @@ impl< Stf, TCS, G, - PH, > Executor< ParentchainBlock, @@ -83,10 +81,9 @@ impl< Stf, TCS, G, - PH, > where - ParentchainBlock: Block, - StfExecutor: StateUpdateProposer, + ParentchainBlock: Block, + StfExecutor: StateUpdateProposer, TopPoolAuthor: AuthorApi, StateHandler: QueryShardState + HandleState, ValidatorAccessor: ValidatorAccess + Send + Sync + 'static, @@ -95,7 +92,6 @@ impl< Stf: SystemPalletEventInterface, TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, - PH: HeaderTrait, { pub fn new( top_pool_author: Arc, @@ -190,7 +186,7 @@ impl< fn apply_state_update( &self, shard: &ShardIdentifier, - updated_state: >::Externalities, + updated_state: >::Externalities, ) -> Result<()> { self.state_handler.reset(updated_state, shard)?; Ok(()) diff --git a/tee-worker/bitacross/enclave-runtime/Cargo.lock b/tee-worker/bitacross/enclave-runtime/Cargo.lock index 35e5242fa7..0456b271f9 100644 --- a/tee-worker/bitacross/enclave-runtime/Cargo.lock +++ b/tee-worker/bitacross/enclave-runtime/Cargo.lock @@ -971,7 +971,7 @@ checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" [[package]] name = "core-primitives" version = "0.1.0" -source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#84afa8035ad15a50b57ec9f7d3845d03bc9a426b" +source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#ea133d42f915d6e3cbbc51304f534d0b9f42e5d3" dependencies = [ "base58", "frame-support", @@ -982,7 +982,6 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", - "sp-core-hashing", "sp-io", "sp-runtime", "sp-std", @@ -2771,7 +2770,7 @@ dependencies = [ [[package]] name = "litentry-hex-utils" version = "0.1.0" -source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#84afa8035ad15a50b57ec9f7d3845d03bc9a426b" +source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#ea133d42f915d6e3cbbc51304f534d0b9f42e5d3" dependencies = [ "hex", ] @@ -2783,7 +2782,7 @@ version = "0.1.0" [[package]] name = "litentry-macros" version = "0.1.0" -source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#84afa8035ad15a50b57ec9f7d3845d03bc9a426b" +source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#ea133d42f915d6e3cbbc51304f534d0b9f42e5d3" [[package]] name = "litentry-primitives" @@ -2822,7 +2821,7 @@ dependencies = [ [[package]] name = "litentry-proc-macros" version = "0.1.0" -source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#84afa8035ad15a50b57ec9f7d3845d03bc9a426b" +source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#ea133d42f915d6e3cbbc51304f534d0b9f42e5d3" dependencies = [ "cargo_toml", "proc-macro2", @@ -3197,7 +3196,7 @@ dependencies = [ [[package]] name = "pallet-teebag" version = "0.1.0" -source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#84afa8035ad15a50b57ec9f7d3845d03bc9a426b" +source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#ea133d42f915d6e3cbbc51304f534d0b9f42e5d3" dependencies = [ "base64 0.13.1", "chrono 0.4.31", diff --git a/tee-worker/bitacross/enclave-runtime/src/initialization/global_components.rs b/tee-worker/bitacross/enclave-runtime/src/initialization/global_components.rs index cb81f274bc..6e60d93af5 100644 --- a/tee-worker/bitacross/enclave-runtime/src/initialization/global_components.rs +++ b/tee-worker/bitacross/enclave-runtime/src/initialization/global_components.rs @@ -85,10 +85,7 @@ use itp_top_pool_author::{ api::SidechainApi, author::{Author, AuthorTopFilter}, }; -use itp_types::{ - parentchain::Header as ParentchainHeader, Block as ParentchainBlock, - SignedBlock as SignedParentchainBlock, -}; +use itp_types::{Block as ParentchainBlock, SignedBlock as SignedParentchainBlock}; use lazy_static::lazy_static; use sgx_crypto_helper::rsa3072::Rsa3072KeyPair; use sgx_tstd::vec::Vec; @@ -125,8 +122,6 @@ pub type EnclaveStfExecutor = StfExecutor< EnclaveStf, EnclaveTrustedCallSigned, EnclaveGetter, - ParentchainHeader, - EnclaveStateKeyRepository, // TODO: use new aes256 key repository when available >; pub type EnclaveStfEnclaveSigner = StfEnclaveSigner< EnclaveOCallApi, @@ -333,7 +328,6 @@ pub type EnclaveOffchainWorkerExecutor = itc_offchain_worker_executor::executor: EnclaveStf, EnclaveTrustedCallSigned, EnclaveGetter, - ParentchainHeader, >; // Base component instances diff --git a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/integritee_parachain.rs b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/integritee_parachain.rs index 608a48088e..f0cc06a94b 100644 --- a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/integritee_parachain.rs +++ b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/integritee_parachain.rs @@ -19,17 +19,12 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, - EnclaveNodeMetadataRepository, - EnclaveOCallApi, - EnclaveStfExecutor, - EnclaveValidatorAccessor, + EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, + EnclaveStfExecutor, EnclaveValidatorAccessor, IntegriteeParentchainBlockImportDispatcher, GLOBAL_INTEGRITEE_PARENTCHAIN_LIGHT_CLIENT_SEAL, - GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE, - GLOBAL_OCALL_API_COMPONENT, + GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE, GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, // TODO: use global for aes256 key repository }, parentchain::common::{ create_extrinsics_factory, create_integritee_offchain_immediate_import_dispatcher, @@ -83,13 +78,10 @@ impl IntegriteeParachainHandler { node_metadata_repository.clone(), )?; - let on_chain_encryption_key_repository = GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.get()?; - let stf_executor = Arc::new(EnclaveStfExecutor::new( ocall_api, state_handler, node_metadata_repository.clone(), - on_chain_encryption_key_repository, )); let block_importer = create_integritee_parentchain_block_importer( diff --git a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs index 88c9d7d4d0..ee5697967f 100644 --- a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs +++ b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs @@ -19,17 +19,12 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, - EnclaveNodeMetadataRepository, - EnclaveOCallApi, - EnclaveStfExecutor, - EnclaveValidatorAccessor, + EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, + EnclaveStfExecutor, EnclaveValidatorAccessor, IntegriteeParentchainBlockImportDispatcher, GLOBAL_INTEGRITEE_PARENTCHAIN_LIGHT_CLIENT_SEAL, - GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE, - GLOBAL_OCALL_API_COMPONENT, + GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE, GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, // TODO: use global for aes256 key repository }, parentchain::common::{ create_extrinsics_factory, create_integritee_offchain_immediate_import_dispatcher, @@ -82,13 +77,10 @@ impl IntegriteeSolochainHandler { node_metadata_repository.clone(), )?; - let on_chain_encryption_key_repository = GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.get()?; - let stf_executor = Arc::new(EnclaveStfExecutor::new( ocall_api, state_handler, node_metadata_repository.clone(), - on_chain_encryption_key_repository, )); let block_importer = create_integritee_parentchain_block_importer( diff --git a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_a_parachain.rs b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_a_parachain.rs index 99e25d1b26..32de87cfba 100644 --- a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_a_parachain.rs +++ b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_a_parachain.rs @@ -25,17 +25,10 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, - EnclaveNodeMetadataRepository, - EnclaveOCallApi, - EnclaveStfExecutor, - EnclaveValidatorAccessor, - TargetAParentchainBlockImportDispatcher, - GLOBAL_OCALL_API_COMPONENT, - GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, // TODO: use global for aes256 key repository - GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL, - GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE, + EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, + EnclaveStfExecutor, EnclaveValidatorAccessor, TargetAParentchainBlockImportDispatcher, + GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, + GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE, }, parentchain::common::{ create_extrinsics_factory, create_target_a_offchain_immediate_import_dispatcher, @@ -89,13 +82,10 @@ impl TargetAParachainHandler { node_metadata_repository.clone(), )?; - let on_chain_encryption_key_repository = GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.get()?; - let stf_executor = Arc::new(EnclaveStfExecutor::new( ocall_api, state_handler, node_metadata_repository.clone(), - on_chain_encryption_key_repository, )); let block_importer = create_target_a_parentchain_block_importer( diff --git a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs index 3ad0f870a0..bd76a450f6 100644 --- a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs +++ b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs @@ -19,17 +19,10 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, - EnclaveNodeMetadataRepository, - EnclaveOCallApi, - EnclaveStfExecutor, - EnclaveValidatorAccessor, - TargetAParentchainBlockImportDispatcher, - GLOBAL_OCALL_API_COMPONENT, - GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, // TODO: use global for aes256 key repository - GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL, - GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE, + EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, + EnclaveStfExecutor, EnclaveValidatorAccessor, TargetAParentchainBlockImportDispatcher, + GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, + GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE, }, parentchain::common::{ create_extrinsics_factory, create_target_a_offchain_immediate_import_dispatcher, @@ -82,13 +75,10 @@ impl TargetASolochainHandler { node_metadata_repository.clone(), )?; - let on_chain_encryption_key_repository = GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.get()?; - let stf_executor = Arc::new(EnclaveStfExecutor::new( ocall_api, state_handler, node_metadata_repository.clone(), - on_chain_encryption_key_repository, )); let block_importer = create_target_a_parentchain_block_importer( diff --git a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_b_parachain.rs b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_b_parachain.rs index 8e1962ca55..221a37b0c0 100644 --- a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_b_parachain.rs +++ b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_b_parachain.rs @@ -25,17 +25,10 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, - EnclaveNodeMetadataRepository, - EnclaveOCallApi, - EnclaveStfExecutor, - EnclaveValidatorAccessor, - TargetBParentchainBlockImportDispatcher, - GLOBAL_OCALL_API_COMPONENT, - GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, // TODO: use global for aes256 key repository - GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL, - GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE, + EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, + EnclaveStfExecutor, EnclaveValidatorAccessor, TargetBParentchainBlockImportDispatcher, + GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, + GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE, }, parentchain::common::{ create_extrinsics_factory, create_target_b_offchain_immediate_import_dispatcher, @@ -89,13 +82,10 @@ impl TargetBParachainHandler { node_metadata_repository.clone(), )?; - let on_chain_encryption_key_repository = GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.get()?; - let stf_executor = Arc::new(EnclaveStfExecutor::new( ocall_api, state_handler, node_metadata_repository.clone(), - on_chain_encryption_key_repository, )); let block_importer = create_target_b_parentchain_block_importer( diff --git a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs index 2b13e07d9b..0953d15779 100644 --- a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs +++ b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs @@ -19,17 +19,10 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, - EnclaveNodeMetadataRepository, - EnclaveOCallApi, - EnclaveStfExecutor, - EnclaveValidatorAccessor, - TargetBParentchainBlockImportDispatcher, - GLOBAL_OCALL_API_COMPONENT, - GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, // TODO: use global for aes256 key repository - GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL, - GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE, + EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, + EnclaveStfExecutor, EnclaveValidatorAccessor, TargetBParentchainBlockImportDispatcher, + GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, + GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE, }, parentchain::common::{ create_extrinsics_factory, create_target_b_offchain_immediate_import_dispatcher, @@ -82,13 +75,10 @@ impl TargetBSolochainHandler { node_metadata_repository.clone(), )?; - let on_chain_encryption_key_repository = GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.get()?; - let stf_executor = Arc::new(EnclaveStfExecutor::new( ocall_api, state_handler, node_metadata_repository.clone(), - on_chain_encryption_key_repository, )); let block_importer = create_target_b_parentchain_block_importer( diff --git a/tee-worker/bitacross/enclave-runtime/src/test/enclave_signer_tests.rs b/tee-worker/bitacross/enclave-runtime/src/test/enclave_signer_tests.rs index 6198befd7a..b76af97d4a 100644 --- a/tee-worker/bitacross/enclave-runtime/src/test/enclave_signer_tests.rs +++ b/tee-worker/bitacross/enclave-runtime/src/test/enclave_signer_tests.rs @@ -20,10 +20,7 @@ use ita_stf::{Getter, Stf, TrustedCall, TrustedCallSigned}; use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; use itp_ocall_api::EnclaveAttestationOCallApi; use itp_sgx_crypto::{ - ed25519_derivation::DeriveEd25519, - key_repository::AccessKey, - mocks::KeyRepositoryMock, - Aes, // TODO: use Aes256 when available + ed25519_derivation::DeriveEd25519, key_repository::AccessKey, mocks::KeyRepositoryMock, }; use itp_sgx_externalities::SgxExternalities; use itp_stf_executor::{enclave_signer::StfEnclaveSigner, traits::StfEnclaveSigning}; @@ -38,20 +35,14 @@ use itp_stf_primitives::{ use itp_stf_state_observer::mock::ObserveStateMock; use itp_test::mock::onchain_mock::OnchainMock; use itp_top_pool_author::{mocks::AuthorApiMock, traits::AuthorApi}; -use itp_types::{parentchain::ParentchainId, Header, RsaRequest}; +use itp_types::{parentchain::ParentchainId, RsaRequest}; use litentry_primitives::Identity; use sgx_crypto_helper::{rsa3072::Rsa3072KeyPair, RsaKeyPair}; use sp_core::Pair; -use sp_runtime::traits::Header as HeaderTrait; use std::{sync::Arc, vec::Vec}; type ShieldingKeyRepositoryMock = KeyRepositoryMock; type TestStf = Stf; -type OnChainEncryptionKeyRepositoryMock = KeyRepositoryMock; - -pub fn latest_parentchain_header() -> Header { - Header::new(1, Default::default(), Default::default(), [69; 32].into(), Default::default()) -} pub fn derive_key_is_deterministic() { let rsa_key = Rsa3072KeyPair::new().unwrap(); @@ -112,7 +103,7 @@ pub fn nonce_is_computed_correctly() { let shard = ShardIdentifier::default(); let enclave_signer = StfEnclaveSigner::<_, _, _, TestStf, _, TrustedCallSigned, Getter>::new( state_observer, - ocall_api.clone(), + ocall_api, shielding_key_repo, top_pool_author.clone(), ); @@ -158,8 +149,6 @@ pub fn nonce_is_computed_correctly() { assert_eq!(0, TestStf::get_account_nonce(&mut state, &enclave_account)); let repo = Arc::new(NodeMetadataRepository::new(NodeMetadataMock::new())); - let on_chain_encryption_key_repository = - Arc::new(OnChainEncryptionKeyRepositoryMock::new(Aes::default())); assert!(TestStf::execute_call( &mut state, &shard, @@ -167,9 +156,6 @@ pub fn nonce_is_computed_correctly() { Default::default(), &mut Vec::new(), repo.clone(), - ocall_api.clone(), - &latest_parentchain_header(), - on_chain_encryption_key_repository.clone() ) .is_ok()); @@ -180,9 +166,6 @@ pub fn nonce_is_computed_correctly() { Default::default(), &mut Vec::new(), repo, - ocall_api, - &latest_parentchain_header(), - on_chain_encryption_key_repository ) .is_ok()); assert_eq!(2, TestStf::get_account_nonce(&mut state, &enclave_account)); diff --git a/tee-worker/bitacross/enclave-runtime/src/test/fixtures/test_setup.rs b/tee-worker/bitacross/enclave-runtime/src/test/fixtures/test_setup.rs index fb594dd696..b9a357eab5 100644 --- a/tee-worker/bitacross/enclave-runtime/src/test/fixtures/test_setup.rs +++ b/tee-worker/bitacross/enclave-runtime/src/test/fixtures/test_setup.rs @@ -24,11 +24,7 @@ use ita_sgx_runtime::Runtime; use ita_stf::{Getter, State, Stf, TrustedCallSigned}; use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; use itp_ocall_api::EnclaveAttestationOCallApi; -use itp_sgx_crypto::{ - ed25519_derivation::DeriveEd25519, - mocks::KeyRepositoryMock, - Aes, // TODO: use Aes256 when available -}; +use itp_sgx_crypto::{ed25519_derivation::DeriveEd25519, mocks::KeyRepositoryMock}; use itp_sgx_externalities::SgxExternalities; use itp_stf_executor::executor::StfExecutor; use itp_stf_primitives::types::{ShardIdentifier, TrustedOperation}; @@ -37,10 +33,9 @@ use itp_test::mock::{ }; use itp_top_pool::{basic_pool::BasicPool, pool::ExtrinsicHash}; use itp_top_pool_author::{api::SidechainApi, author::Author, top_filter::AllowAllTopsFilter}; -use itp_types::{parentchain::Header as ParentchainHeader, Block, MrEnclave}; +use itp_types::{Block, MrEnclave}; use sp_core::{crypto::Pair, ed25519 as spEd25519}; use std::sync::Arc; - pub type TestRpcResponder = RpcResponderMock>>; pub type TestTopPool = BasicPool< SidechainApi, @@ -59,8 +54,6 @@ pub type TestTopPoolAuthor = Author< >; pub type TestStf = Stf; -type TestOnChainEncryptionKeyRepository = KeyRepositoryMock; - pub type TestStfExecutor = StfExecutor< OcallApi, HandleStateMock, @@ -68,8 +61,6 @@ pub type TestStfExecutor = StfExecutor< TestStf, TrustedCallSigned, Getter, - ParentchainHeader, - TestOnChainEncryptionKeyRepository, >; /// Returns all the things that are commonly used in tests and runs @@ -82,7 +73,6 @@ pub fn test_setup() -> ( ShieldingCryptoMock, Arc, Arc, - Arc, ) { let shielding_key = ShieldingCryptoMock::default(); let shielding_key_repo = Arc::new(KeyRepositoryMock::new(shielding_key.clone())); @@ -94,13 +84,10 @@ pub fn test_setup() -> ( let mrenclave = OcallApi.get_mrenclave_of_self().unwrap().m; let node_metadata_repo = Arc::new(NodeMetadataRepository::new(NodeMetadataMock::new())); - let on_chain_encryption_key_repository = KeyRepositoryMock::new(Aes::default()); - let stf_executor = Arc::new(TestStfExecutor::new( Arc::new(OcallApi), state_handler.clone(), node_metadata_repo, - Arc::new(on_chain_encryption_key_repository), )); ( @@ -116,7 +103,6 @@ pub fn test_setup() -> ( shielding_key, state_handler, stf_executor, - Arc::new(OcallApi), ) } diff --git a/tee-worker/bitacross/enclave-runtime/src/test/mocks/types.rs b/tee-worker/bitacross/enclave-runtime/src/test/mocks/types.rs index c92a39d3f6..1ffe90a2fd 100644 --- a/tee-worker/bitacross/enclave-runtime/src/test/mocks/types.rs +++ b/tee-worker/bitacross/enclave-runtime/src/test/mocks/types.rs @@ -30,10 +30,7 @@ use itp_stf_primitives::types::TrustedOperation; use itp_test::mock::{handle_state_mock::HandleStateMock, onchain_mock::OnchainMock}; use itp_top_pool::basic_pool::BasicPool; use itp_top_pool_author::{api::SidechainApi, author::Author, top_filter::AllowAllTopsFilter}; -use itp_types::{ - parentchain::Header as ParentchainHeader, Block as ParentchainBlock, - SignedBlock as SignedParentchainBlock, -}; +use itp_types::{Block as ParentchainBlock, SignedBlock as SignedParentchainBlock}; use primitive_types::H256; use sgx_crypto_helper::rsa3072::Rsa3072KeyPair; use sp_core::ed25519 as spEd25519; @@ -66,8 +63,6 @@ pub type TestStfExecutor = StfExecutor< TestStf, TrustedCallSigned, Getter, - ParentchainHeader, - TestStateKeyRepo, >; pub type TestRpcResponder = RpcResponderMock; diff --git a/tee-worker/bitacross/enclave-runtime/src/test/tests_main.rs b/tee-worker/bitacross/enclave-runtime/src/test/tests_main.rs index de9ebd3e2c..0e44a1937b 100644 --- a/tee-worker/bitacross/enclave-runtime/src/test/tests_main.rs +++ b/tee-worker/bitacross/enclave-runtime/src/test/tests_main.rs @@ -36,7 +36,7 @@ use ita_stf::{ Getter, State, TrustedCall, TrustedCallSigned, TrustedGetter, }; use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; -use itp_sgx_crypto::{mocks::KeyRepositoryMock, Aes, StateCrypto}; +use itp_sgx_crypto::{Aes, StateCrypto}; use itp_sgx_externalities::{SgxExternalitiesDiffType, SgxExternalitiesTrait}; use itp_stf_executor::{ executor_tests as stf_executor_tests, traits::StateUpdateProposer, BatchExecutionResult, @@ -279,7 +279,7 @@ fn test_differentiate_getter_and_call_works() { fn test_executing_call_updates_account_nonce() { // given - let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor, ..) = test_setup(); + let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor) = test_setup(); let sender = funded_pair(); let receiver = unfunded_public(); @@ -312,7 +312,7 @@ fn test_executing_call_updates_account_nonce() { } fn test_call_set_update_parentchain_block() { - let (_, _, shard, _, _, state_handler, _, ..) = test_setup(); + let (_, _, shard, _, _, state_handler, _) = test_setup(); let (mut state, _) = state_handler.load_cloned(&shard).unwrap(); let block_number = 3; @@ -335,7 +335,7 @@ fn test_call_set_update_parentchain_block() { fn test_signature_must_match_public_sender_in_call() { // given - let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor, ..) = test_setup(); + let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor) = test_setup(); // create accounts let sender = funded_pair(); @@ -365,7 +365,7 @@ fn test_signature_must_match_public_sender_in_call() { fn test_invalid_nonce_call_is_not_executed() { // given - let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor, ..) = test_setup(); + let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor) = test_setup(); // create accounts let sender = funded_pair(); @@ -395,8 +395,7 @@ fn test_invalid_nonce_call_is_not_executed() { fn test_non_root_shielding_call_is_not_executed() { // given - let (top_pool_author, _state, shard, mrenclave, shielding_key, _, stf_executor, ..) = - test_setup(); + let (top_pool_author, _state, shard, mrenclave, shielding_key, _, stf_executor) = test_setup(); let sender = funded_pair(); let sender_acc: AccountId = sender.public().into(); @@ -425,8 +424,7 @@ fn test_non_root_shielding_call_is_not_executed() { } fn test_shielding_call_with_enclave_self_is_executed() { - let (top_pool_author, _state, shard, mrenclave, shielding_key, _, stf_executor, ..) = - test_setup(); + let (top_pool_author, _state, shard, mrenclave, shielding_key, _, stf_executor) = test_setup(); let sender = funded_pair(); let sender_account: AccountId = sender.public().into(); @@ -461,8 +459,7 @@ fn test_shielding_call_with_enclave_self_is_executed() { pub fn test_retrieve_events() { // given - let (_, mut state, shard, mrenclave, _shielding_key, _state_handler, _stf_executor, ocall_api) = - test_setup(); + let (_, mut state, shard, mrenclave, ..) = test_setup(); let mut opaque_vec = Vec::new(); let sender = funded_pair(); let receiver = unendowed_account(); @@ -479,8 +476,6 @@ pub fn test_retrieve_events() { .sign(&sender.into(), 0, &mrenclave, &shard); let repo = Arc::new(NodeMetadataRepository::::default()); let shard = ShardIdentifier::default(); - let on_chain_encryption_key_repository = - Arc::new(KeyRepositoryMock::::new(Aes::default())); TestStf::execute_call( &mut state, &shard, @@ -488,9 +483,6 @@ pub fn test_retrieve_events() { Default::default(), &mut opaque_vec, repo, - ocall_api, - &latest_parentchain_header(), - on_chain_encryption_key_repository, ) .unwrap(); @@ -498,8 +490,7 @@ pub fn test_retrieve_events() { } pub fn test_retrieve_event_count() { - let (_, mut state, shard, mrenclave, _shielding_key, _state_handler, _stf_executor, ocall_api) = - test_setup(); + let (_, mut state, shard, mrenclave, ..) = test_setup(); let mut opaque_vec = Vec::new(); let sender = funded_pair(); let receiver = unendowed_account(); @@ -518,8 +509,6 @@ pub fn test_retrieve_event_count() { // when let repo = Arc::new(NodeMetadataRepository::::default()); let shard = ShardIdentifier::default(); - let on_chain_encryption_key_repository = - Arc::new(KeyRepositoryMock::::new(Aes::default())); TestStf::execute_call( &mut state, &shard, @@ -527,9 +516,6 @@ pub fn test_retrieve_event_count() { Default::default(), &mut opaque_vec, repo, - ocall_api, - &latest_parentchain_header(), - on_chain_encryption_key_repository, ) .unwrap(); @@ -538,8 +524,7 @@ pub fn test_retrieve_event_count() { } pub fn test_reset_events() { - let (_, mut state, shard, mrenclave, _shielding_key, _state_handler, _stf_executor, ocall_api) = - test_setup(); + let (_, mut state, shard, mrenclave, ..) = test_setup(); let mut opaque_vec = Vec::new(); let sender = funded_pair(); let receiver = unendowed_account(); @@ -555,8 +540,6 @@ pub fn test_reset_events() { .sign(&sender.into(), 0, &mrenclave, &shard); let repo = Arc::new(NodeMetadataRepository::::default()); let shard = ShardIdentifier::default(); - let on_chain_encryption_key_repository = - Arc::new(KeyRepositoryMock::::new(Aes::default())); TestStf::execute_call( &mut state, &shard, @@ -564,9 +547,6 @@ pub fn test_reset_events() { Default::default(), &mut opaque_vec, repo, - ocall_api, - &latest_parentchain_header(), - on_chain_encryption_key_repository, ) .unwrap(); let receiver_acc_info = TestStf::get_account_data(&mut state, &receiver.public().into()); From 5ef031c2471f9ba04fdd1c8456dacf354fe689c0 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 10 Oct 2024 15:18:29 +0000 Subject: [PATCH 29/39] Revert "injecting OnChainEncryptionKeyRepository and parentchain header to the" This reverts commit 9fba6d1a380b63d6634e4a3bcb038706795ebc1a. --- tee-worker/Cargo.lock | 3 - .../bitacross/enclave-runtime/Cargo.lock | 3 - .../core-primitives/ocall-api/Cargo.toml | 1 - .../core-primitives/ocall-api/src/lib.rs | 3 - .../core-primitives/stf-interface/Cargo.toml | 14 +- .../core-primitives/stf-interface/src/lib.rs | 30 +-- .../stf-interface/src/mocks.rs | 33 +-- .../common/core-primitives/test/Cargo.toml | 2 +- .../core-primitives/test/src/mock/stf_mock.rs | 44 +--- tee-worker/identity/app-libs/stf/Cargo.toml | 2 - .../identity/app-libs/stf/src/stf_sgx.rs | 45 +--- .../identity/app-libs/stf/src/trusted_call.rs | 18 +- .../stf-executor/src/executor.rs | 199 ++++-------------- .../stf-executor/src/executor_tests.rs | 15 +- .../core-primitives/stf-executor/src/mocks.rs | 6 +- .../stf-executor/src/traits.rs | 6 +- .../offchain-worker-executor/src/executor.rs | 14 +- .../identity/enclave-runtime/Cargo.lock | 3 - .../src/initialization/global_components.rs | 8 +- .../parentchain/integritee_parachain.rs | 14 +- .../parentchain/integritee_solochain.rs | 14 +- .../parentchain/target_a_parachain.rs | 18 +- .../parentchain/target_a_solochain.rs | 18 +- .../parentchain/target_b_parachain.rs | 18 +- .../parentchain/target_b_solochain.rs | 18 +- .../src/test/enclave_signer_tests.rs | 23 +- .../src/test/fixtures/test_setup.rs | 17 +- .../enclave-runtime/src/test/mocks/types.rs | 7 +- .../src/test/sidechain_aura_tests.rs | 1 - .../src/test/sidechain_event_tests.rs | 1 - .../enclave-runtime/src/test/tests_main.rs | 41 +--- .../enclave-runtime/src/top_pool_execution.rs | 2 +- .../consensus/aura/src/proposer_factory.rs | 25 +-- .../consensus/aura/src/slot_proposer.rs | 24 +-- 34 files changed, 137 insertions(+), 553 deletions(-) diff --git a/tee-worker/Cargo.lock b/tee-worker/Cargo.lock index d22045684d..5ff2ee7d1a 100644 --- a/tee-worker/Cargo.lock +++ b/tee-worker/Cargo.lock @@ -4332,12 +4332,9 @@ version = "0.8.0" dependencies = [ "itp-node-api-metadata", "itp-node-api-metadata-provider", - "itp-ocall-api", - "itp-sgx-crypto", "itp-stf-primitives", "itp-types", "parity-scale-codec", - "sp-runtime", ] [[package]] diff --git a/tee-worker/bitacross/enclave-runtime/Cargo.lock b/tee-worker/bitacross/enclave-runtime/Cargo.lock index 0456b271f9..949176f1aa 100644 --- a/tee-worker/bitacross/enclave-runtime/Cargo.lock +++ b/tee-worker/bitacross/enclave-runtime/Cargo.lock @@ -2486,12 +2486,9 @@ version = "0.8.0" dependencies = [ "itp-node-api-metadata", "itp-node-api-metadata-provider", - "itp-ocall-api", - "itp-sgx-crypto", "itp-stf-primitives", "itp-types", "parity-scale-codec", - "sp-runtime", ] [[package]] diff --git a/tee-worker/common/core-primitives/ocall-api/Cargo.toml b/tee-worker/common/core-primitives/ocall-api/Cargo.toml index e678a539bc..655bedbc9a 100644 --- a/tee-worker/common/core-primitives/ocall-api/Cargo.toml +++ b/tee-worker/common/core-primitives/ocall-api/Cargo.toml @@ -27,4 +27,3 @@ std = [ "itp-storage/std", "itp-types/std", ] -mocks = [] diff --git a/tee-worker/common/core-primitives/ocall-api/src/lib.rs b/tee-worker/common/core-primitives/ocall-api/src/lib.rs index 8e196fdf99..ca5090e88c 100644 --- a/tee-worker/common/core-primitives/ocall-api/src/lib.rs +++ b/tee-worker/common/core-primitives/ocall-api/src/lib.rs @@ -17,9 +17,6 @@ #![cfg_attr(not(feature = "std"), no_std)] -#[cfg(feature = "mocks")] -pub mod mock; - pub extern crate alloc; use alloc::{string::String, vec::Vec}; diff --git a/tee-worker/common/core-primitives/stf-interface/Cargo.toml b/tee-worker/common/core-primitives/stf-interface/Cargo.toml index 510df17f9c..a46749521d 100644 --- a/tee-worker/common/core-primitives/stf-interface/Cargo.toml +++ b/tee-worker/common/core-primitives/stf-interface/Cargo.toml @@ -9,13 +9,9 @@ codec = { package = "parity-scale-codec", workspace = true } itp-node-api-metadata = { workspace = true, features = ["mocks"] } itp-node-api-metadata-provider = { workspace = true } -itp-ocall-api = { workspace = true } -itp-sgx-crypto = { workspace = true } itp-stf-primitives = { workspace = true } itp-types = { workspace = true } -sp-runtime = { workspace = true } - [features] default = ["std"] std = [ @@ -23,12 +19,6 @@ std = [ "itp-node-api-metadata-provider/std", "itp-stf-primitives/std", "itp-types/std", - "itp-sgx-crypto/std", -] -sgx = [ - "itp-sgx-crypto/sgx", -] -mocks = [ - "itp-ocall-api/mocks", - "itp-sgx-crypto/mocks", ] +sgx = [] +mocks = [] diff --git a/tee-worker/common/core-primitives/stf-interface/src/lib.rs b/tee-worker/common/core-primitives/stf-interface/src/lib.rs index c57f352f41..179adf6504 100644 --- a/tee-worker/common/core-primitives/stf-interface/src/lib.rs +++ b/tee-worker/common/core-primitives/stf-interface/src/lib.rs @@ -27,15 +27,11 @@ use codec::{Decode, Encode}; use core::fmt::Debug; use itp_node_api_metadata::NodeMetadataTrait; use itp_node_api_metadata_provider::AccessNodeMetadata; -use itp_ocall_api::EnclaveOnChainOCallApi; -// TODO: use Aes256 when available -use itp_sgx_crypto::{aes::Aes, key_repository::AccessKey}; use itp_stf_primitives::traits::TrustedCallVerification; use itp_types::{ parentchain::{BlockHash, BlockNumber, ParentchainCall, ParentchainId}, ShardIdentifier, H256, }; -use sp_runtime::traits::Header as HeaderTrait; #[cfg(feature = "mocks")] pub mod mocks; @@ -66,20 +62,11 @@ pub trait UpdateState { } /// Interface to execute state mutating calls on a state. -pub trait StateCallInterface< - TCS, - State, - NodeMetadataRepository, - OCallApi, - PH, - OnChainEncryptionKeyRepository, -> where +pub trait StateCallInterface +where NodeMetadataRepository: AccessNodeMetadata, NodeMetadataRepository::MetadataType: NodeMetadataTrait, TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, - OCallApi: EnclaveOnChainOCallApi, - PH: HeaderTrait, - OnChainEncryptionKeyRepository: AccessKey, { type Error: Encode; type Result: StfExecutionResult; @@ -90,7 +77,6 @@ pub trait StateCallInterface< /// 1. add a parameter to pass the top_hash around /// 2. returns the encoded rpc response value field that should be passed /// back to the requester when the call is triggered synchronously - #[allow(clippy::too_many_arguments)] fn execute_call( state: &mut State, shard: &ShardIdentifier, @@ -98,9 +84,6 @@ pub trait StateCallInterface< top_hash: H256, calls: &mut Vec, node_metadata_repo: Arc, - ocall_api: Arc, - parentchain_header: &PH, - on_chain_encryption_key_repo: Arc, ) -> Result; } @@ -111,13 +94,10 @@ pub trait StateGetterInterface { } /// Trait used to abstract the call execution. -pub trait ExecuteCall +pub trait ExecuteCall where NodeMetadataRepository: AccessNodeMetadata, NodeMetadataRepository::MetadataType: NodeMetadataTrait, - OCallApi: EnclaveOnChainOCallApi, - PH: HeaderTrait, - OnChainEncryptionKeyRepository: AccessKey, { type Error: Encode; type Result: StfExecutionResult; @@ -126,16 +106,12 @@ where /// /// Litentry: returns the encoded rpc response that should be passed back to /// the requester when the call is triggered synchronously - #[allow(clippy::too_many_arguments)] fn execute( self, shard: &ShardIdentifier, top_hash: H256, calls: &mut Vec, node_metadata_repo: Arc, - ocall_api: Arc, - parentchain_header: &PH, - on_chain_encryption_key_repo: Arc, ) -> Result; /// Get storages hashes that should be updated for a specific call. diff --git a/tee-worker/common/core-primitives/stf-interface/src/mocks.rs b/tee-worker/common/core-primitives/stf-interface/src/mocks.rs index 1e2810b5a1..44bda77d36 100644 --- a/tee-worker/common/core-primitives/stf-interface/src/mocks.rs +++ b/tee-worker/common/core-primitives/stf-interface/src/mocks.rs @@ -27,18 +27,11 @@ use codec::{Decode, Encode}; use core::{fmt::Debug, marker::PhantomData}; use itp_node_api_metadata::metadata_mocks::NodeMetadataMock; use itp_node_api_metadata_provider::NodeMetadataRepository; -use itp_ocall_api::mock::OnchainMock; -// TODO: use Aes256 when available -use itp_sgx_crypto::{mocks::KeyRepositoryMock, Aes}; use itp_stf_primitives::traits::TrustedCallVerification; use itp_types::{ parentchain::{ParentchainCall, ParentchainId}, AccountId, Index, ShardIdentifier, H256, }; -use sp_runtime::{generic::Header, traits::BlakeTwo256}; - -type BlockNumber = u32; -pub type ParentchainHeader = Header; #[derive(Default)] pub struct StateInterfaceMock { @@ -63,15 +56,8 @@ impl UpdateState for StateInterfaceMock - StateCallInterface< - TCS, - State, - NodeMetadataRepository, - OnchainMock, - ParentchainHeader, - KeyRepositoryMock, - > for StateInterfaceMock +impl StateCallInterface> + for StateInterfaceMock where TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, { @@ -85,9 +71,6 @@ where _top_hash: H256, _calls: &mut Vec, _node_metadata_repo: Arc>, - _ocall_api: Arc, - _parentchain_header: &ParentchainHeader, - _key_repository: Arc>, ) -> Result { unimplemented!() } @@ -117,14 +100,7 @@ impl SystemPalletAccountInterface pub struct CallExecutorMock; -impl - ExecuteCall< - NodeMetadataRepository, - OnchainMock, - ParentchainHeader, - KeyRepositoryMock, - > for CallExecutorMock -{ +impl ExecuteCall> for CallExecutorMock { type Error = String; type Result = (); @@ -134,9 +110,6 @@ impl _top_hash: H256, _calls: &mut Vec, _node_metadata_repo: Arc>, - _ocall_api: Arc, - _parentchain_header: &ParentchainHeader, - _key_repository: Arc>, ) -> Result<(), Self::Error> { unimplemented!() } diff --git a/tee-worker/common/core-primitives/test/Cargo.toml b/tee-worker/common/core-primitives/test/Cargo.toml index acfa543348..a738a22b15 100644 --- a/tee-worker/common/core-primitives/test/Cargo.toml +++ b/tee-worker/common/core-primitives/test/Cargo.toml @@ -20,7 +20,7 @@ sp-std = { workspace = true } itp-node-api = { workspace = true } itp-node-api-metadata-provider = { workspace = true } itp-ocall-api = { workspace = true } -itp-sgx-crypto = { workspace = true, features = ["mocks"] } +itp-sgx-crypto = { workspace = true } itp-sgx-externalities = { workspace = true } itp-stf-interface = { workspace = true } itp-stf-primitives = { workspace = true } diff --git a/tee-worker/common/core-primitives/test/src/mock/stf_mock.rs b/tee-worker/common/core-primitives/test/src/mock/stf_mock.rs index 9d5c29022d..40b9225761 100644 --- a/tee-worker/common/core-primitives/test/src/mock/stf_mock.rs +++ b/tee-worker/common/core-primitives/test/src/mock/stf_mock.rs @@ -14,14 +14,11 @@ limitations under the License. */ -use super::onchain_mock::OnchainMock; use alloc::{boxed::Box, sync::Arc}; use codec::{Decode, Encode}; use core::fmt::Debug; use itp_node_api::metadata::metadata_mocks::NodeMetadataMock; use itp_node_api_metadata_provider::NodeMetadataRepository; -// TODO: use Aes256 when available -use itp_sgx_crypto::{mocks::KeyRepositoryMock, Aes}; use itp_sgx_externalities::{SgxExternalities, SgxExternalitiesDiffType, SgxExternalitiesTrait}; use itp_stf_interface::{ runtime_upgrade::RuntimeUpgradeInterface, ExecuteCall, InitState, StateCallInterface, @@ -40,18 +37,14 @@ use itp_types::{ use litentry_primitives::{Identity, LitentryMultiSignature}; use log::*; use sp_core::{sr25519, Pair}; -use sp_runtime::{ - generic::Header, - traits::BlakeTwo256, - transaction_validity::{TransactionValidityError, UnknownTransaction, ValidTransaction}, +use sp_runtime::transaction_validity::{ + TransactionValidityError, UnknownTransaction, ValidTransaction, }; use sp_std::{vec, vec::Vec}; use std::{thread::sleep, time::Duration}; // a few dummy types type NodeMetadataRepositoryMock = NodeMetadataRepository; -type BlockNumber = u32; -pub type ParentchainHeader = Header; #[derive(Debug, PartialEq, Eq, Encode)] pub enum StfMockError { @@ -70,15 +63,8 @@ impl UpdateState for StfMock { } } -impl - StateCallInterface< - TrustedCallSignedMock, - SgxExternalities, - NodeMetadataRepositoryMock, - OnchainMock, - ParentchainHeader, - KeyRepositoryMock, - > for StfMock +impl StateCallInterface + for StfMock { type Error = StfMockError; type Result = (); @@ -90,21 +76,8 @@ impl top_hash: H256, calls: &mut Vec, node_metadata_repo: Arc, - ocall_api: Arc, - parentchain_header: &ParentchainHeader, - key_repository: Arc>, ) -> Result<(), Self::Error> { - state.execute_with(|| { - call.execute( - shard, - top_hash, - calls, - node_metadata_repo, - ocall_api, - parentchain_header, - key_repository, - ) - }) + state.execute_with(|| call.execute(shard, top_hash, calls, node_metadata_repo)) } } @@ -197,9 +170,7 @@ impl Default for TrustedCallSignedMock { } } -impl ExecuteCall> - for TrustedCallSignedMock -{ +impl ExecuteCall for TrustedCallSignedMock { type Error = StfMockError; type Result = (); @@ -209,9 +180,6 @@ impl ExecuteCall, _node_metadata_repo: Arc, - _ocall_api: Arc, - _parentchain_header: &ParentchainHeader, - _on_chain_encryption_key_repo: Arc>, ) -> Result<(), Self::Error> { match self.call { TrustedCallMock::noop(_) => Ok(()), diff --git a/tee-worker/identity/app-libs/stf/Cargo.toml b/tee-worker/identity/app-libs/stf/Cargo.toml index 13af43351b..a19b15ca1f 100644 --- a/tee-worker/identity/app-libs/stf/Cargo.toml +++ b/tee-worker/identity/app-libs/stf/Cargo.toml @@ -59,7 +59,6 @@ sgx = [ "litentry-primitives/sgx", "lc-stf-task-sender/sgx", "itp-node-api-metadata-provider/sgx", - "itp-sgx-crypto/sgx", ] std = [ "codec/std", @@ -83,7 +82,6 @@ std = [ "litentry-primitives/std", "lc-stf-task-sender/std", "itp-node-api-metadata-provider/std", - "itp-sgx-crypto/std", ] test = [] development = [ diff --git a/tee-worker/identity/app-libs/stf/src/stf_sgx.rs b/tee-worker/identity/app-libs/stf/src/stf_sgx.rs index c6436bffb9..7e99061839 100644 --- a/tee-worker/identity/app-libs/stf/src/stf_sgx.rs +++ b/tee-worker/identity/app-libs/stf/src/stf_sgx.rs @@ -28,9 +28,6 @@ use ita_sgx_runtime::{ Executive, ParentchainInstanceLitentry, ParentchainInstanceTargetA, ParentchainInstanceTargetB, }; use itp_node_api::metadata::{provider::AccessNodeMetadata, NodeMetadataTrait}; -use itp_ocall_api::EnclaveOnChainOCallApi; -// TODO: use Aes256 when available -use itp_sgx_crypto::{aes::Aes, key_repository::AccessKey}; use itp_sgx_externalities::SgxExternalitiesTrait; use itp_stf_interface::{ parentchain_pallet::ParentchainPalletInstancesInterface, @@ -50,7 +47,7 @@ use itp_types::{ }; use itp_utils::stringify::account_id_to_string; use log::*; -use sp_runtime::traits::{Header as HeaderTrait, StaticLookup}; +use sp_runtime::traits::StaticLookup; impl InitState for Stf where @@ -137,27 +134,11 @@ where } } -impl< - TCS, - G, - State, - Runtime, - NodeMetadataRepository, - OCallApi, - PH, - OnChainEncryptionKeyRepository, - > - StateCallInterface< - TCS, - State, - NodeMetadataRepository, - OCallApi, - PH, - OnChainEncryptionKeyRepository, - > for Stf +impl + StateCallInterface for Stf where TCS: PartialEq - + ExecuteCall + + ExecuteCall + Encode + Decode + Debug @@ -168,9 +149,6 @@ where State: SgxExternalitiesTrait + Debug, NodeMetadataRepository: AccessNodeMetadata, NodeMetadataRepository::MetadataType: NodeMetadataTrait, - OCallApi: EnclaveOnChainOCallApi, - PH: HeaderTrait, - OnChainEncryptionKeyRepository: AccessKey, { type Error = TCS::Error; type Result = TCS::Result; @@ -182,21 +160,8 @@ where top_hash: H256, calls: &mut Vec, node_metadata_repo: Arc, - ocall_api: Arc, - parentchain_header: &PH, - on_chain_encryption_key_repo: Arc, ) -> Result { - state.execute_with(|| { - call.execute( - shard, - top_hash, - calls, - node_metadata_repo, - ocall_api, - parentchain_header, - on_chain_encryption_key_repo, - ) - }) + state.execute_with(|| call.execute(shard, top_hash, calls, node_metadata_repo)) } } diff --git a/tee-worker/identity/app-libs/stf/src/trusted_call.rs b/tee-worker/identity/app-libs/stf/src/trusted_call.rs index 06b4c5d200..567069faf9 100644 --- a/tee-worker/identity/app-libs/stf/src/trusted_call.rs +++ b/tee-worker/identity/app-libs/stf/src/trusted_call.rs @@ -39,9 +39,6 @@ pub use ita_sgx_runtime::{ }; use itp_node_api::metadata::{provider::AccessNodeMetadata, NodeMetadataTrait}; use itp_node_api_metadata::{pallet_imp::IMPCallIndexes, pallet_vcmp::VCMPCallIndexes}; -use itp_ocall_api::EnclaveOnChainOCallApi; -// TODO: use Aes256 when available -use itp_sgx_crypto::{key_repository::AccessKey, Aes}; use itp_stf_interface::ExecuteCall; use itp_stf_primitives::{ error::StfError, @@ -65,10 +62,7 @@ use sp_core::{ ed25519, }; use sp_io::hashing::blake2_256; -use sp_runtime::{ - traits::{ConstU32, Header as HeaderTrait}, - BoundedVec, MultiAddress, -}; +use sp_runtime::{traits::ConstU32, BoundedVec, MultiAddress}; pub type IMTCall = ita_sgx_runtime::IdentityManagementCall; pub type IMT = ita_sgx_runtime::pallet_identity_management_tee::Pallet; @@ -350,15 +344,10 @@ impl TrustedCallVerification for TrustedCallSigned { } } -impl - ExecuteCall - for TrustedCallSigned +impl ExecuteCall for TrustedCallSigned where NodeMetadataRepository: AccessNodeMetadata, NodeMetadataRepository::MetadataType: NodeMetadataTrait, - OCallApi: EnclaveOnChainOCallApi, - PH: HeaderTrait, - OnChainEncryptionKeyRepository: AccessKey, { type Error = StfError; type Result = TrustedCallResult; @@ -402,9 +391,6 @@ where top_hash: H256, calls: &mut Vec, node_metadata_repo: Arc, - _ocall_api: Arc, - _parentchain_header: &PH, - _on_chain_encryption_key_repo: Arc, ) -> Result { let sender = self.call.sender_identity().clone(); let account_id: AccountId = sender.to_account_id().ok_or(Self::Error::InvalidAccount)?; diff --git a/tee-worker/identity/core-primitives/stf-executor/src/executor.rs b/tee-worker/identity/core-primitives/stf-executor/src/executor.rs index 3e98e06214..ffc6d92fce 100644 --- a/tee-worker/identity/core-primitives/stf-executor/src/executor.rs +++ b/tee-worker/identity/core-primitives/stf-executor/src/executor.rs @@ -24,8 +24,6 @@ use codec::{Decode, Encode}; use itp_enclave_metrics::EnclaveMetric; use itp_node_api::metadata::{provider::AccessNodeMetadata, NodeMetadataTrait}; use itp_ocall_api::{EnclaveAttestationOCallApi, EnclaveMetricsOCallApi, EnclaveOnChainOCallApi}; -// TODO: use Aes256 when available -use itp_sgx_crypto::{aes::Aes, key_repository::AccessKey}; use itp_sgx_externalities::{SgxExternalitiesTrait, StateHash}; use itp_stf_interface::{ parentchain_pallet::ParentchainPalletInstancesInterface, @@ -38,7 +36,7 @@ use itp_stf_primitives::{ use itp_stf_state_handler::{handle_state::HandleState, query_shard_state::QueryShardState}; use itp_time_utils::duration_now; use itp_types::{ - parentchain::{ParentchainCall, ParentchainId}, + parentchain::{Header as ParentchainHeader, ParentchainCall, ParentchainId}, storage::StorageEntryVerified, H256, }; @@ -49,46 +47,20 @@ use std::{ time::Duration, vec, vec::Vec, }; -pub struct StfExecutor< - OCallApi, - StateHandler, - NodeMetadataRepository, - Stf, - TCS, - G, - PH, - OnChainEncryptionKeyRepository, -> where +pub struct StfExecutor +where TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, { ocall_api: Arc, state_handler: Arc, node_metadata_repo: Arc, - on_chain_encryption_key_repository: Arc, - _phantom: PhantomData<(Stf, TCS, G, PH)>, + _phantom: PhantomData<(Stf, TCS, G)>, } -impl< - OCallApi, - StateHandler, - NodeMetadataRepository, - Stf, - TCS, - G, - PH, - OnChainEncryptionKeyRepository, - > - StfExecutor< - OCallApi, - StateHandler, - NodeMetadataRepository, - Stf, - TCS, - G, - PH, - OnChainEncryptionKeyRepository, - > where +impl + StfExecutor +where OCallApi: EnclaveAttestationOCallApi + EnclaveOnChainOCallApi + EnclaveMetricsOCallApi, StateHandler: HandleState, StateHandler::StateT: SgxExternalitiesTrait + Encode, @@ -97,42 +69,19 @@ impl< Stf: UpdateState< StateHandler::StateT, ::SgxExternalitiesDiffType, - > + StateCallInterface< - TCS, - StateHandler::StateT, - NodeMetadataRepository, - OCallApi, - PH, - OnChainEncryptionKeyRepository, - >, + > + StateCallInterface, ::SgxExternalitiesDiffType: IntoIterator, Option>)> + From, Option>>>, - >::Error: Debug, + >::Error: Debug, TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, - PH: HeaderTrait, - OnChainEncryptionKeyRepository: AccessKey, { pub fn new( ocall_api: Arc, state_handler: Arc, node_metadata_repo: Arc, - on_chain_encryption_key_repository: Arc, ) -> Self { - StfExecutor { - ocall_api, - state_handler, - node_metadata_repo, - on_chain_encryption_key_repository, - _phantom: PhantomData, - } + StfExecutor { ocall_api, state_handler, node_metadata_repo, _phantom: PhantomData } } /// Execute a trusted call on the STF @@ -141,14 +90,17 @@ impl< /// an invalid trusted call, which results in `Ok(ExecutionStatus::Failure)`. The latter /// can be used to remove the trusted call from a queue. In the former case we might keep the /// trusted call and just re-try the operation. - fn execute_trusted_call_on_stf( + fn execute_trusted_call_on_stf( &self, state: &mut StateHandler::StateT, trusted_operation: &TrustedOperation, - parentchain_header: &PH, + _header: &PH, shard: &ShardIdentifier, post_processing: StatePostProcessing, - ) -> Result> { + ) -> Result> + where + PH: HeaderTrait, + { debug!("query mrenclave of self"); let mrenclave = self.ocall_api.get_mrenclave_of_self()?; @@ -180,9 +132,6 @@ impl< trusted_operation.hash(), &mut extrinsic_call_backs, self.node_metadata_repo.clone(), - self.ocall_api.clone(), - parentchain_header, - self.on_chain_encryption_key_repository.clone(), ) { Err(e) => { if let Err(e) = @@ -231,26 +180,10 @@ impl< } } -impl< - OCallApi, - StateHandler, - NodeMetadataRepository, - Stf, - TCS, - G, - PH, - OnChainEncryptionKeyRepository, - > StfUpdateState - for StfExecutor< - OCallApi, - StateHandler, - NodeMetadataRepository, - Stf, - TCS, - G, - PH, - OnChainEncryptionKeyRepository, - > where +impl + StfUpdateState + for StfExecutor +where OCallApi: EnclaveAttestationOCallApi + EnclaveOnChainOCallApi, StateHandler: HandleState + QueryShardState, StateHandler::StateT: SgxExternalitiesTrait + Encode, @@ -258,18 +191,21 @@ impl< Stf: UpdateState< StateHandler::StateT, ::SgxExternalitiesDiffType, - > + ParentchainPalletInstancesInterface, + > + ParentchainPalletInstancesInterface, ::SgxExternalitiesDiffType: IntoIterator, Option>)>, - >::Error: Debug, + >::Error: + Debug, ::SgxExternalitiesDiffType: From, Option>>>, TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, - PH: HeaderTrait, - OnChainEncryptionKeyRepository: AccessKey, { - fn update_states(&self, header: &PH, parentchain_id: &ParentchainId) -> Result<()> { + fn update_states( + &self, + header: &ParentchainHeader, + parentchain_id: &ParentchainId, + ) -> Result<()> { debug!("Update STF storage upon block import!"); let storage_hashes = Stf::storage_hashes_to_update_on_block(parentchain_id); @@ -309,46 +245,28 @@ impl< } } -impl< - OCallApi, - StateHandler, - NodeMetadataRepository, - Stf, - TCS, - G, - PH, - OnChainEncryptionKeyRepository, - > - StfExecutor< - OCallApi, - StateHandler, - NodeMetadataRepository, - Stf, - TCS, - G, - PH, - OnChainEncryptionKeyRepository, - > where +impl + StfExecutor +where ::SgxExternalitiesDiffType: From, Option>>> + IntoIterator, Option>)>, - >::Error: Debug, + >::Error: + Debug, NodeMetadataRepository: AccessNodeMetadata, OCallApi: EnclaveAttestationOCallApi + EnclaveOnChainOCallApi, StateHandler: HandleState + QueryShardState, StateHandler::StateT: Encode + SgxExternalitiesTrait, - Stf: ParentchainPalletInstancesInterface + Stf: ParentchainPalletInstancesInterface + UpdateState< StateHandler::StateT, ::SgxExternalitiesDiffType, >, TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, - PH: HeaderTrait, - OnChainEncryptionKeyRepository: AccessKey, { fn initialize_new_shards( &self, - header: &PH, + header: &ParentchainHeader, state_diff_update: &BTreeMap, Option>>, shards: &Vec, ) -> Result<()> { @@ -377,26 +295,9 @@ impl< } } -impl< - OCallApi, - StateHandler, - NodeMetadataRepository, - Stf, - TCS, - G, - PH, - OnChainEncryptionKeyRepository, - > StateUpdateProposer - for StfExecutor< - OCallApi, - StateHandler, - NodeMetadataRepository, - Stf, - TCS, - G, - PH, - OnChainEncryptionKeyRepository, - > where +impl StateUpdateProposer + for StfExecutor +where OCallApi: EnclaveAttestationOCallApi + EnclaveOnChainOCallApi + EnclaveMetricsOCallApi, StateHandler: HandleState, StateHandler::StateT: SgxExternalitiesTrait + Encode + StateHash, @@ -406,35 +307,20 @@ impl< Stf: UpdateState< StateHandler::StateT, ::SgxExternalitiesDiffType, - > + StateCallInterface< - TCS, - StateHandler::StateT, - NodeMetadataRepository, - OCallApi, - PH, - OnChainEncryptionKeyRepository, - > + RuntimeUpgradeInterface, + > + StateCallInterface + + RuntimeUpgradeInterface, ::SgxExternalitiesDiffType: IntoIterator, Option>)>, ::SgxExternalitiesDiffType: From, Option>>>, - >::Error: Debug, + >::Error: Debug, >::Error: Debug, TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, - PH: HeaderTrait, - OnChainEncryptionKeyRepository: AccessKey, { type Externalities = StateHandler::StateT; - fn propose_state_update( + fn propose_state_update( &self, trusted_calls: &[TrustedOperation], header: &PH, @@ -443,6 +329,7 @@ impl< prepare_state_function: F, ) -> Result> where + PH: HeaderTrait, F: FnOnce(Self::Externalities) -> Self::Externalities, { let ends_at = duration_now() + max_exec_duration; diff --git a/tee-worker/identity/core-primitives/stf-executor/src/executor_tests.rs b/tee-worker/identity/core-primitives/stf-executor/src/executor_tests.rs index cdf6be930e..2eb0185bcd 100644 --- a/tee-worker/identity/core-primitives/stf-executor/src/executor_tests.rs +++ b/tee-worker/identity/core-primitives/stf-executor/src/executor_tests.rs @@ -20,10 +20,7 @@ use codec::Encode; use itc_parentchain_test::ParentchainHeaderBuilder; use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; use itp_ocall_api::EnclaveAttestationOCallApi; -// TODO: use Aes256 when available -use itp_sgx_crypto::{mocks::KeyRepositoryMock, Aes}; use itp_sgx_externalities::{SgxExternalities as State, SgxExternalitiesTrait}; -use itp_sgx_io::SealedIO; use itp_stf_primitives::{traits::TrustedCallSigning, types::ShardIdentifier}; use itp_stf_state_handler::handle_state::HandleState; use itp_test::mock::{ @@ -31,7 +28,7 @@ use itp_test::mock::{ onchain_mock::OnchainMock, stf_mock::{GetterMock, StfMock, TrustedCallMock, TrustedCallSignedMock}, }; -use itp_types::{parentchain::Header as ParentchainHeader, H256}; +use itp_types::H256; use sp_core::{ed25519, Pair}; use sp_runtime::app_crypto::sp_core::blake2_256; use std::{sync::Arc, time::Duration, vec}; @@ -247,8 +244,6 @@ fn stf_executor() -> ( StfMock, TrustedCallSignedMock, GetterMock, - ParentchainHeader, - KeyRepositoryMock, >, Arc, Arc, @@ -256,13 +251,7 @@ fn stf_executor() -> ( let ocall_api = Arc::new(OnchainMock::default()); let state_handler = Arc::new(HandleStateMock::default()); let node_metadata_repo = Arc::new(NodeMetadataRepository::new(NodeMetadataMock::new())); - let encryption_key_repository = Arc::new(KeyRepositoryMock::new(Aes::default())); - let executor = StfExecutor::new( - ocall_api.clone(), - state_handler.clone(), - node_metadata_repo, - encryption_key_repository, - ); + let executor = StfExecutor::new(ocall_api.clone(), state_handler.clone(), node_metadata_repo); (executor, ocall_api, state_handler) } diff --git a/tee-worker/identity/core-primitives/stf-executor/src/mocks.rs b/tee-worker/identity/core-primitives/stf-executor/src/mocks.rs index 96a554501b..d328a2e24e 100644 --- a/tee-worker/identity/core-primitives/stf-executor/src/mocks.rs +++ b/tee-worker/identity/core-primitives/stf-executor/src/mocks.rs @@ -59,16 +59,15 @@ impl StfExecutorMock { } } -impl StateUpdateProposer for StfExecutorMock +impl StateUpdateProposer for StfExecutorMock where State: SgxExternalitiesTrait + Encode + Clone, TCS: PartialEq + Encode + Decode + Clone + Debug + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Clone + Debug + Send + Sync, - PH: HeaderTrait, { type Externalities = State; - fn propose_state_update( + fn propose_state_update( &self, trusted_calls: &[TrustedOperation], _header: &PH, @@ -77,6 +76,7 @@ where prepare_state_function: F, ) -> Result> where + PH: HeaderTrait, F: FnOnce(Self::Externalities) -> Self::Externalities, { let mut lock = self.state.write().unwrap(); diff --git a/tee-worker/identity/core-primitives/stf-executor/src/traits.rs b/tee-worker/identity/core-primitives/stf-executor/src/traits.rs index 3b77b99588..62e788141a 100644 --- a/tee-worker/identity/core-primitives/stf-executor/src/traits.rs +++ b/tee-worker/identity/core-primitives/stf-executor/src/traits.rs @@ -55,11 +55,10 @@ where } /// Proposes a state update to `Externalities`. -pub trait StateUpdateProposer +pub trait StateUpdateProposer where TCS: PartialEq + Encode + Decode + Debug + Send + Sync, G: PartialEq + Encode + Decode + Debug + Send + Sync, - PH: HeaderTrait, { type Externalities: SgxExternalitiesTrait + Encode; @@ -67,7 +66,7 @@ where /// /// All executed call hashes and the mutated state are returned. /// If the time expires, any remaining trusted calls within the batch will be ignored. - fn propose_state_update( + fn propose_state_update( &self, trusted_calls: &[TrustedOperation], header: &PH, @@ -76,6 +75,7 @@ where prepare_state_function: F, ) -> Result> where + PH: HeaderTrait, F: FnOnce(Self::Externalities) -> Self::Externalities; } diff --git a/tee-worker/identity/core/offchain-worker-executor/src/executor.rs b/tee-worker/identity/core/offchain-worker-executor/src/executor.rs index 9f9f1a84c3..a9fcee8f66 100644 --- a/tee-worker/identity/core/offchain-worker-executor/src/executor.rs +++ b/tee-worker/identity/core/offchain-worker-executor/src/executor.rs @@ -30,7 +30,7 @@ use itp_stf_state_handler::{handle_state::HandleState, query_shard_state::QueryS use itp_top_pool_author::traits::AuthorApi; use itp_types::{parentchain::ParentchainCall, OpaqueCall, ShardIdentifier, H256}; use log::*; -use sp_runtime::traits::{Block, Header as HeaderTrait}; +use sp_runtime::traits::Block; use std::{marker::PhantomData, sync::Arc, time::Duration, vec::Vec}; /// Off-chain worker executor implementation. @@ -51,14 +51,13 @@ pub struct Executor< Stf, TCS, G, - PH, > { top_pool_author: Arc, stf_executor: Arc, state_handler: Arc, validator_accessor: Arc, extrinsics_factory: Arc, - _phantom: PhantomData<(ParentchainBlock, Stf, TCS, G, PH)>, + _phantom: PhantomData<(ParentchainBlock, Stf, TCS, G)>, } impl< @@ -71,7 +70,6 @@ impl< Stf, TCS, G, - PH, > Executor< ParentchainBlock, @@ -83,10 +81,9 @@ impl< Stf, TCS, G, - PH, > where - ParentchainBlock: Block, - StfExecutor: StateUpdateProposer, + ParentchainBlock: Block, + StfExecutor: StateUpdateProposer, TopPoolAuthor: AuthorApi, StateHandler: QueryShardState + HandleState, ValidatorAccessor: ValidatorAccess + Send + Sync + 'static, @@ -95,7 +92,6 @@ impl< Stf: SystemPalletEventInterface, TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, - PH: HeaderTrait, { pub fn new( top_pool_author: Arc, @@ -190,7 +186,7 @@ impl< fn apply_state_update( &self, shard: &ShardIdentifier, - updated_state: >::Externalities, + updated_state: >::Externalities, ) -> Result<()> { self.state_handler.reset(updated_state, shard)?; Ok(()) diff --git a/tee-worker/identity/enclave-runtime/Cargo.lock b/tee-worker/identity/enclave-runtime/Cargo.lock index 6db2c0ed82..af0fdff788 100644 --- a/tee-worker/identity/enclave-runtime/Cargo.lock +++ b/tee-worker/identity/enclave-runtime/Cargo.lock @@ -2611,12 +2611,9 @@ version = "0.8.0" dependencies = [ "itp-node-api-metadata", "itp-node-api-metadata-provider", - "itp-ocall-api", - "itp-sgx-crypto", "itp-stf-primitives", "itp-types", "parity-scale-codec", - "sp-runtime", ] [[package]] diff --git a/tee-worker/identity/enclave-runtime/src/initialization/global_components.rs b/tee-worker/identity/enclave-runtime/src/initialization/global_components.rs index 188eb8c6c8..5255d5303e 100644 --- a/tee-worker/identity/enclave-runtime/src/initialization/global_components.rs +++ b/tee-worker/identity/enclave-runtime/src/initialization/global_components.rs @@ -79,10 +79,7 @@ use itp_top_pool_author::{ api::SidechainApi, author::{Author, AuthorTopFilter, BroadcastedTopFilter}, }; -use itp_types::{ - parentchain::Header as ParentchainHeader, Block as ParentchainBlock, - SignedBlock as SignedParentchainBlock, -}; +use itp_types::{Block as ParentchainBlock, SignedBlock as SignedParentchainBlock}; use its_primitives::{ traits::{Block as SidechainBlockTrait, SignedBlock as SignedSidechainBlockTrait}, types::block::SignedBlock as SignedSidechainBlock, @@ -129,8 +126,6 @@ pub type EnclaveStfExecutor = StfExecutor< EnclaveStf, EnclaveTrustedCallSigned, EnclaveGetter, - ParentchainHeader, - EnclaveStateKeyRepository, // TODO: use new aes256 key repository when available >; pub type EnclaveStfEnclaveSigner = StfEnclaveSigner< EnclaveOCallApi, @@ -367,7 +362,6 @@ pub type EnclaveOffchainWorkerExecutor = itc_offchain_worker_executor::executor: EnclaveStf, EnclaveTrustedCallSigned, EnclaveGetter, - ParentchainHeader, >; // Base component instances diff --git a/tee-worker/identity/enclave-runtime/src/initialization/parentchain/integritee_parachain.rs b/tee-worker/identity/enclave-runtime/src/initialization/parentchain/integritee_parachain.rs index ebaf69177e..62e7bb6d67 100644 --- a/tee-worker/identity/enclave-runtime/src/initialization/parentchain/integritee_parachain.rs +++ b/tee-worker/identity/enclave-runtime/src/initialization/parentchain/integritee_parachain.rs @@ -19,17 +19,12 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, - EnclaveNodeMetadataRepository, - EnclaveOCallApi, - EnclaveStfExecutor, - EnclaveValidatorAccessor, + EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, + EnclaveStfExecutor, EnclaveValidatorAccessor, IntegriteeParentchainBlockImportDispatcher, GLOBAL_INTEGRITEE_PARENTCHAIN_LIGHT_CLIENT_SEAL, - GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE, - GLOBAL_OCALL_API_COMPONENT, + GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE, GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, // TODO: use global for aes256 key repository }, parentchain::common::{ create_extrinsics_factory, create_integritee_offchain_immediate_import_dispatcher, @@ -85,13 +80,10 @@ impl IntegriteeParachainHandler { node_metadata_repository.clone(), )?; - let on_chain_encryption_key_repository = GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.get()?; - let stf_executor = Arc::new(EnclaveStfExecutor::new( ocall_api, state_handler, node_metadata_repository.clone(), - on_chain_encryption_key_repository, )); let block_importer = create_integritee_parentchain_block_importer( diff --git a/tee-worker/identity/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs b/tee-worker/identity/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs index f9a7c4df25..f8c8d512d7 100644 --- a/tee-worker/identity/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs +++ b/tee-worker/identity/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs @@ -19,17 +19,12 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, - EnclaveNodeMetadataRepository, - EnclaveOCallApi, - EnclaveStfExecutor, - EnclaveValidatorAccessor, + EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, + EnclaveStfExecutor, EnclaveValidatorAccessor, IntegriteeParentchainBlockImportDispatcher, GLOBAL_INTEGRITEE_PARENTCHAIN_LIGHT_CLIENT_SEAL, - GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE, - GLOBAL_OCALL_API_COMPONENT, + GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE, GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, // TODO: use global for aes256 key repository }, parentchain::common::{ create_extrinsics_factory, create_integritee_offchain_immediate_import_dispatcher, @@ -84,13 +79,10 @@ impl IntegriteeSolochainHandler { node_metadata_repository.clone(), )?; - let on_chain_encryption_key_repository = GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.get()?; - let stf_executor = Arc::new(EnclaveStfExecutor::new( ocall_api, state_handler, node_metadata_repository.clone(), - on_chain_encryption_key_repository, )); let block_importer = create_integritee_parentchain_block_importer( diff --git a/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_a_parachain.rs b/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_a_parachain.rs index 0d74df3e5f..59921c14af 100644 --- a/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_a_parachain.rs +++ b/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_a_parachain.rs @@ -25,17 +25,10 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, - EnclaveNodeMetadataRepository, - EnclaveOCallApi, - EnclaveStfExecutor, - EnclaveValidatorAccessor, - TargetAParentchainBlockImportDispatcher, - GLOBAL_OCALL_API_COMPONENT, - GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, // TODO: use global for aes256 key repository - GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL, - GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE, + EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, + EnclaveStfExecutor, EnclaveValidatorAccessor, TargetAParentchainBlockImportDispatcher, + GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, + GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE, }, parentchain::common::{ create_extrinsics_factory, create_sidechain_triggered_import_dispatcher_for_target_a, @@ -91,13 +84,10 @@ impl TargetAParachainHandler { node_metadata_repository.clone(), )?; - let on_chain_encryption_key_repository = GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.get()?; - let stf_executor = Arc::new(EnclaveStfExecutor::new( ocall_api, state_handler, node_metadata_repository.clone(), - on_chain_encryption_key_repository, )); let block_importer = create_target_a_parentchain_block_importer( diff --git a/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs b/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs index 3836780052..41a12bbbf8 100644 --- a/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs +++ b/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs @@ -19,17 +19,10 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, - EnclaveNodeMetadataRepository, - EnclaveOCallApi, - EnclaveStfExecutor, - EnclaveValidatorAccessor, - TargetAParentchainBlockImportDispatcher, - GLOBAL_OCALL_API_COMPONENT, - GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, // TODO: use global for aes256 key repository - GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL, - GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE, + EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, + EnclaveStfExecutor, EnclaveValidatorAccessor, TargetAParentchainBlockImportDispatcher, + GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, + GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE, }, parentchain::common::{ create_extrinsics_factory, create_sidechain_triggered_import_dispatcher_for_target_a, @@ -84,13 +77,10 @@ impl TargetASolochainHandler { node_metadata_repository.clone(), )?; - let on_chain_encryption_key_repository = GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.get()?; - let stf_executor = Arc::new(EnclaveStfExecutor::new( ocall_api, state_handler, node_metadata_repository.clone(), - on_chain_encryption_key_repository, )); let block_importer = create_target_a_parentchain_block_importer( diff --git a/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_b_parachain.rs b/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_b_parachain.rs index e4ec762651..21b729a456 100644 --- a/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_b_parachain.rs +++ b/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_b_parachain.rs @@ -25,17 +25,10 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, - EnclaveNodeMetadataRepository, - EnclaveOCallApi, - EnclaveStfExecutor, - EnclaveValidatorAccessor, - TargetBParentchainBlockImportDispatcher, - GLOBAL_OCALL_API_COMPONENT, - GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, // TODO: use global for aes256 key repository - GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL, - GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE, + EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, + EnclaveStfExecutor, EnclaveValidatorAccessor, TargetBParentchainBlockImportDispatcher, + GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, + GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE, }, parentchain::common::{ create_extrinsics_factory, create_sidechain_triggered_import_dispatcher_for_target_b, @@ -91,13 +84,10 @@ impl TargetBParachainHandler { node_metadata_repository.clone(), )?; - let on_chain_encryption_key_repository = GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.get()?; - let stf_executor = Arc::new(EnclaveStfExecutor::new( ocall_api, state_handler, node_metadata_repository.clone(), - on_chain_encryption_key_repository, )); let block_importer = create_target_b_parentchain_block_importer( diff --git a/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs b/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs index e457a24b44..954fe436c8 100644 --- a/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs +++ b/tee-worker/identity/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs @@ -19,17 +19,10 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, - EnclaveNodeMetadataRepository, - EnclaveOCallApi, - EnclaveStfExecutor, - EnclaveValidatorAccessor, - TargetBParentchainBlockImportDispatcher, - GLOBAL_OCALL_API_COMPONENT, - GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, // TODO: use global for aes256 key repository - GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL, - GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE, + EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, + EnclaveStfExecutor, EnclaveValidatorAccessor, TargetBParentchainBlockImportDispatcher, + GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, + GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE, }, parentchain::common::{ create_extrinsics_factory, create_sidechain_triggered_import_dispatcher_for_target_b, @@ -84,13 +77,10 @@ impl TargetBSolochainHandler { node_metadata_repository.clone(), )?; - let on_chain_encryption_key_repository = GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.get()?; - let stf_executor = Arc::new(EnclaveStfExecutor::new( ocall_api, state_handler, node_metadata_repository.clone(), - on_chain_encryption_key_repository, )); let block_importer = create_target_b_parentchain_block_importer( diff --git a/tee-worker/identity/enclave-runtime/src/test/enclave_signer_tests.rs b/tee-worker/identity/enclave-runtime/src/test/enclave_signer_tests.rs index e2fdd419ab..8f20f23a86 100644 --- a/tee-worker/identity/enclave-runtime/src/test/enclave_signer_tests.rs +++ b/tee-worker/identity/enclave-runtime/src/test/enclave_signer_tests.rs @@ -20,10 +20,7 @@ use ita_stf::{Getter, Stf, TrustedCall, TrustedCallSigned}; use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; use itp_ocall_api::EnclaveAttestationOCallApi; use itp_sgx_crypto::{ - ed25519_derivation::DeriveEd25519, - key_repository::AccessKey, - mocks::KeyRepositoryMock, - Aes, // TODO: use Aes256 when available + ed25519_derivation::DeriveEd25519, key_repository::AccessKey, mocks::KeyRepositoryMock, }; use itp_sgx_externalities::SgxExternalities; use itp_stf_executor::{enclave_signer::StfEnclaveSigner, traits::StfEnclaveSigning}; @@ -38,21 +35,15 @@ use itp_stf_primitives::{ use itp_stf_state_observer::mock::ObserveStateMock; use itp_test::mock::onchain_mock::OnchainMock; use itp_top_pool_author::{mocks::AuthorApiMock, traits::AuthorApi}; -use itp_types::{Header, RsaRequest}; +use itp_types::RsaRequest; use litentry_primitives::Identity; use sgx_crypto_helper::{rsa3072::Rsa3072KeyPair, RsaKeyPair}; use sp_core::Pair; -use sp_runtime::traits::Header as HeaderTrait; use std::{sync::Arc, vec::Vec}; type ShieldingKeyRepositoryMock = KeyRepositoryMock; -type OnChainEncryptionKeyRepositoryMock = KeyRepositoryMock; type TestStf = Stf; -pub fn latest_parentchain_header() -> Header { - Header::new(1, Default::default(), Default::default(), [69; 32].into(), Default::default()) -} - pub fn derive_key_is_deterministic() { let rsa_key = Rsa3072KeyPair::new().unwrap(); @@ -107,7 +98,7 @@ pub fn nonce_is_computed_correctly() { let shard = ShardIdentifier::default(); let enclave_signer = StfEnclaveSigner::<_, _, _, TestStf, _, TrustedCallSigned, Getter>::new( state_observer, - ocall_api.clone(), + ocall_api, shielding_key_repo, top_pool_author.clone(), ); @@ -143,8 +134,6 @@ pub fn nonce_is_computed_correctly() { assert_eq!(0, TestStf::get_account_nonce(&mut state, &enclave_account)); let repo = Arc::new(NodeMetadataRepository::new(NodeMetadataMock::new())); - let on_chain_encryption_key_repository = - Arc::new(OnChainEncryptionKeyRepositoryMock::new(Aes::default())); assert!(TestStf::execute_call( &mut state, &shard, @@ -152,9 +141,6 @@ pub fn nonce_is_computed_correctly() { Default::default(), &mut Vec::new(), repo.clone(), - ocall_api.clone(), - &latest_parentchain_header(), - on_chain_encryption_key_repository.clone() ) .is_ok()); @@ -165,9 +151,6 @@ pub fn nonce_is_computed_correctly() { Default::default(), &mut Vec::new(), repo, - ocall_api, - &latest_parentchain_header(), - on_chain_encryption_key_repository ) .is_ok()); assert_eq!(2, TestStf::get_account_nonce(&mut state, &enclave_account)); diff --git a/tee-worker/identity/enclave-runtime/src/test/fixtures/test_setup.rs b/tee-worker/identity/enclave-runtime/src/test/fixtures/test_setup.rs index e413053f74..78c2bef328 100644 --- a/tee-worker/identity/enclave-runtime/src/test/fixtures/test_setup.rs +++ b/tee-worker/identity/enclave-runtime/src/test/fixtures/test_setup.rs @@ -24,11 +24,7 @@ use ita_sgx_runtime::Runtime; use ita_stf::{Getter, State, Stf, TrustedCallSigned}; use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; use itp_ocall_api::EnclaveAttestationOCallApi; -use itp_sgx_crypto::{ - ed25519_derivation::DeriveEd25519, - mocks::KeyRepositoryMock, - Aes, // TODO: use Aes256 when available -}; +use itp_sgx_crypto::{ed25519_derivation::DeriveEd25519, mocks::KeyRepositoryMock}; use itp_sgx_externalities::SgxExternalities; use itp_stf_executor::executor::StfExecutor; use itp_stf_primitives::types::{ShardIdentifier, TrustedOperation}; @@ -42,7 +38,7 @@ use itp_top_pool_author::{ author::Author, top_filter::{AllowAllTopsFilter, DirectCallsOnlyFilter}, }; -use itp_types::{parentchain::Header as ParentchainHeader, Block, MrEnclave}; +use itp_types::{Block, MrEnclave}; use sp_core::{crypto::Pair, ed25519 as spEd25519}; use std::sync::Arc; pub type TestRpcResponder = RpcResponderMock>>; @@ -65,8 +61,6 @@ pub type TestTopPoolAuthor = Author< >; pub type TestStf = Stf; -type TestOnChainEncryptionKeyRepository = KeyRepositoryMock; - pub type TestStfExecutor = StfExecutor< OcallApi, HandleStateMock, @@ -74,8 +68,6 @@ pub type TestStfExecutor = StfExecutor< TestStf, TrustedCallSigned, Getter, - ParentchainHeader, - TestOnChainEncryptionKeyRepository, >; /// Returns all the things that are commonly used in tests and runs @@ -88,7 +80,6 @@ pub fn test_setup() -> ( ShieldingCryptoMock, Arc, Arc, - Arc, ) { let shielding_key = ShieldingCryptoMock::default(); let shielding_key_repo = Arc::new(KeyRepositoryMock::new(shielding_key.clone())); @@ -100,13 +91,10 @@ pub fn test_setup() -> ( let mrenclave = OcallApi.get_mrenclave_of_self().unwrap().m; let node_metadata_repo = Arc::new(NodeMetadataRepository::new(NodeMetadataMock::new())); - let on_chain_encryption_key_repository = KeyRepositoryMock::new(Aes::default()); - let stf_executor = Arc::new(TestStfExecutor::new( Arc::new(OcallApi), state_handler.clone(), node_metadata_repo, - Arc::new(on_chain_encryption_key_repository), )); let (sender, _receiver) = std::sync::mpsc::sync_channel(1000); @@ -127,7 +115,6 @@ pub fn test_setup() -> ( shielding_key, state_handler, stf_executor, - Arc::new(OcallApi), ) } diff --git a/tee-worker/identity/enclave-runtime/src/test/mocks/types.rs b/tee-worker/identity/enclave-runtime/src/test/mocks/types.rs index ac39650570..ae939c53e4 100644 --- a/tee-worker/identity/enclave-runtime/src/test/mocks/types.rs +++ b/tee-worker/identity/enclave-runtime/src/test/mocks/types.rs @@ -39,10 +39,7 @@ use itp_top_pool_author::{ author::Author, top_filter::{AllowAllTopsFilter, DirectCallsOnlyFilter}, }; -use itp_types::{ - parentchain::Header as ParentchainHeader, Block as ParentchainBlock, - SignedBlock as SignedParentchainBlock, -}; +use itp_types::{Block as ParentchainBlock, SignedBlock as SignedParentchainBlock}; use its_primitives::types::SignedBlock as SignedSidechainBlock; use its_sidechain::{aura::block_importer::BlockImporter, block_composer::BlockComposer}; use primitive_types::H256; @@ -77,8 +74,6 @@ pub type TestStfExecutor = StfExecutor< TestStf, TrustedCallSigned, Getter, - ParentchainHeader, - TestStateKeyRepo, >; pub type TestRpcResponder = RpcResponderMock; diff --git a/tee-worker/identity/enclave-runtime/src/test/sidechain_aura_tests.rs b/tee-worker/identity/enclave-runtime/src/test/sidechain_aura_tests.rs index ac867fffa3..0e2c6639c9 100644 --- a/tee-worker/identity/enclave-runtime/src/test/sidechain_aura_tests.rs +++ b/tee-worker/identity/enclave-runtime/src/test/sidechain_aura_tests.rs @@ -103,7 +103,6 @@ pub fn produce_sidechain_block_and_import_it() { ocall_api.clone(), state_handler.clone(), node_metadata_repo, - state_key_repo.clone(), )); let top_pool = create_top_pool(); diff --git a/tee-worker/identity/enclave-runtime/src/test/sidechain_event_tests.rs b/tee-worker/identity/enclave-runtime/src/test/sidechain_event_tests.rs index a148d54b2e..458ea2053b 100644 --- a/tee-worker/identity/enclave-runtime/src/test/sidechain_event_tests.rs +++ b/tee-worker/identity/enclave-runtime/src/test/sidechain_event_tests.rs @@ -87,7 +87,6 @@ pub fn ensure_events_get_reset_upon_block_proposal() { ocall_api.clone(), state_handler.clone(), node_metadata_repo, - state_key_repo.clone(), )); let top_pool = create_top_pool(); let (sender, _receiver) = std::sync::mpsc::sync_channel(1000); diff --git a/tee-worker/identity/enclave-runtime/src/test/tests_main.rs b/tee-worker/identity/enclave-runtime/src/test/tests_main.rs index c94e12ee18..0a61660650 100644 --- a/tee-worker/identity/enclave-runtime/src/test/tests_main.rs +++ b/tee-worker/identity/enclave-runtime/src/test/tests_main.rs @@ -37,7 +37,7 @@ use ita_stf::{ AccountInfo, Getter, State, TrustedCall, TrustedCallSigned, TrustedGetter, }; use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; -use itp_sgx_crypto::{mocks::KeyRepositoryMock, Aes, StateCrypto}; +use itp_sgx_crypto::{Aes, StateCrypto}; use itp_sgx_externalities::{SgxExternalitiesDiffType, SgxExternalitiesTrait, StateHash}; use itp_stf_executor::{ executor_tests as stf_executor_tests, traits::StateUpdateProposer, BatchExecutionResult, @@ -183,7 +183,7 @@ fn run_evm_tests() {} fn test_compose_block() { // given - let (_, _, shard, _, _, state_handler, _, ..) = test_setup(); + let (_, _, shard, _, _, state_handler, _) = test_setup(); let block_composer = BlockComposer::::new( test_account(), Arc::new(TestStateKeyRepo::new(state_key())), @@ -325,7 +325,7 @@ fn test_differentiate_getter_and_call_works() { fn test_create_block_and_confirmation_works() { // given - let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor, ..) = test_setup(); + let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor) = test_setup(); let block_composer = BlockComposer::::new( test_account(), @@ -375,7 +375,7 @@ fn test_create_block_and_confirmation_works() { fn test_create_state_diff() { // given - let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor, ..) = test_setup(); + let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor) = test_setup(); let block_composer = BlockComposer::::new( test_account(), @@ -441,7 +441,7 @@ fn test_create_state_diff() { fn test_executing_call_updates_account_nonce() { // given - let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor, ..) = test_setup(); + let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor) = test_setup(); let sender = funded_pair(); let receiver = unfunded_public(); @@ -475,7 +475,7 @@ fn test_executing_call_updates_account_nonce() { } fn test_call_set_update_parentchain_block() { - let (_, _, shard, _, _, state_handler, _, ..) = test_setup(); + let (_, _, shard, _, _, state_handler, _) = test_setup(); let (mut state, _) = state_handler.load_cloned(&shard).unwrap(); let block_number = 3; @@ -498,7 +498,7 @@ fn test_call_set_update_parentchain_block() { fn test_signature_must_match_public_sender_in_call() { // given - let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor, ..) = test_setup(); + let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor) = test_setup(); // create accounts let sender = funded_pair(); @@ -529,7 +529,7 @@ fn test_signature_must_match_public_sender_in_call() { fn test_invalid_nonce_call_is_not_executed() { // given - let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor, ..) = test_setup(); + let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor) = test_setup(); // create accounts let sender = funded_pair(); @@ -560,8 +560,7 @@ fn test_invalid_nonce_call_is_not_executed() { pub fn test_retrieve_events() { // given - let (_, mut state, shard, mrenclave, _shielding_key, _state_handler, _stf_executor, ocall_api) = - test_setup(); + let (_, mut state, shard, mrenclave, ..) = test_setup(); let mut opaque_vec = Vec::new(); let sender = funded_pair(); let receiver = unendowed_account(); @@ -578,8 +577,6 @@ pub fn test_retrieve_events() { .sign(&sender.into(), 0, &mrenclave, &shard); let repo = Arc::new(NodeMetadataRepository::::default()); let shard = ShardIdentifier::default(); - let on_chain_encryption_key_repository = - Arc::new(KeyRepositoryMock::::new(Aes::default())); TestStf::execute_call( &mut state, &shard, @@ -587,9 +584,6 @@ pub fn test_retrieve_events() { Default::default(), &mut opaque_vec, repo, - ocall_api, - &latest_parentchain_header(), - on_chain_encryption_key_repository, ) .unwrap(); @@ -597,8 +591,7 @@ pub fn test_retrieve_events() { } pub fn test_retrieve_event_count() { - let (_, mut state, shard, mrenclave, _shielding_key, _state_handler, _stf_executor, ocall_api) = - test_setup(); + let (_, mut state, shard, mrenclave, ..) = test_setup(); let mut opaque_vec = Vec::new(); let sender = funded_pair(); let receiver = unendowed_account(); @@ -617,8 +610,6 @@ pub fn test_retrieve_event_count() { // when let repo = Arc::new(NodeMetadataRepository::::default()); let shard = ShardIdentifier::default(); - let on_chain_encryption_key_repository = - Arc::new(KeyRepositoryMock::::new(Aes::default())); TestStf::execute_call( &mut state, &shard, @@ -626,9 +617,6 @@ pub fn test_retrieve_event_count() { Default::default(), &mut opaque_vec, repo, - ocall_api, - &latest_parentchain_header(), - on_chain_encryption_key_repository, ) .unwrap(); @@ -637,8 +625,7 @@ pub fn test_retrieve_event_count() { } pub fn test_reset_events() { - let (_, mut state, shard, mrenclave, _shielding_key, _state_handler, _stf_executor, ocall_api) = - test_setup(); + let (_, mut state, shard, mrenclave, ..) = test_setup(); let mut opaque_vec = Vec::new(); let sender = funded_pair(); let receiver = unendowed_account(); @@ -654,9 +641,6 @@ pub fn test_reset_events() { .sign(&sender.into(), 0, &mrenclave, &shard); let repo = Arc::new(NodeMetadataRepository::::default()); let shard = ShardIdentifier::default(); - let on_chain_encryption_key_repository = - Arc::new(KeyRepositoryMock::::new(Aes::default())); - TestStf::execute_call( &mut state, &shard, @@ -664,9 +648,6 @@ pub fn test_reset_events() { Default::default(), &mut opaque_vec, repo, - ocall_api, - &latest_parentchain_header(), - on_chain_encryption_key_repository, ) .unwrap(); let receiver_acc_info = TestStf::get_account_data(&mut state, &receiver.public().into()); diff --git a/tee-worker/identity/enclave-runtime/src/top_pool_execution.rs b/tee-worker/identity/enclave-runtime/src/top_pool_execution.rs index f264ed819d..439a3f2463 100644 --- a/tee-worker/identity/enclave-runtime/src/top_pool_execution.rs +++ b/tee-worker/identity/enclave-runtime/src/top_pool_execution.rs @@ -203,7 +203,7 @@ fn execute_top_pool_trusted_calls_internal() -> Result<()> { } log_remaining_slot_duration(&slot, "Before AURA"); - let env = ProposerFactory::::new( + let env = ProposerFactory::::new( top_pool_author, stf_executor, block_composer, diff --git a/tee-worker/identity/sidechain/consensus/aura/src/proposer_factory.rs b/tee-worker/identity/sidechain/consensus/aura/src/proposer_factory.rs index 8c0f626dd9..61fa21557f 100644 --- a/tee-worker/identity/sidechain/consensus/aura/src/proposer_factory.rs +++ b/tee-worker/identity/sidechain/consensus/aura/src/proposer_factory.rs @@ -32,7 +32,7 @@ use its_primitives::traits::{ }; use its_state::{SidechainState, SidechainSystemExt}; use sp_runtime::{ - traits::{Block, Header as ParentchainHeaderTrait, NumberFor}, + traits::{Block, NumberFor}, MultiSignature, }; use std::{marker::PhantomData, sync::Arc}; @@ -45,18 +45,16 @@ pub struct ProposerFactory< StfExecutor, BlockComposer, MetricsApi, - PH, > { top_pool_author: Arc, stf_executor: Arc, block_composer: Arc, metrics_api: Arc, _phantom: PhantomData, - _phantom_header: PhantomData, } -impl - ProposerFactory +impl + ProposerFactory { pub fn new( top_pool_executor: Arc, @@ -70,21 +68,19 @@ impl, + ParentchainBlock: Block, SignedSidechainBlock, TopPoolAuthor, StfExecutor, BlockComposer, MetricsApi, - PH, > Environment - for ProposerFactory + for ProposerFactory where NumberFor: BlockNumberOps, SignedSidechainBlock: SignedSidechainBlockTrait @@ -94,19 +90,18 @@ where HeaderTrait, TopPoolAuthor: AuthorApi + Send + Sync + 'static, - StfExecutor: StateUpdateProposer + Send + Sync + 'static, - ExternalitiesFor: + StfExecutor: StateUpdateProposer + Send + Sync + 'static, + ExternalitiesFor: SgxExternalitiesTrait + SidechainState + SidechainSystemExt + StateHash, - as SgxExternalitiesTrait>::SgxExternalitiesType: Encode, + as SgxExternalitiesTrait>::SgxExternalitiesType: Encode, BlockComposer: ComposeBlock< - ExternalitiesFor, + ExternalitiesFor, ParentchainBlock, SignedSidechainBlock = SignedSidechainBlock, > + Send + Sync + 'static, MetricsApi: EnclaveMetricsOCallApi, - PH: ParentchainHeaderTrait, { type Proposer = SlotProposer< ParentchainBlock, @@ -115,7 +110,6 @@ where StfExecutor, BlockComposer, MetricsApi, - PH, >; type Error = ConsensusError; @@ -132,7 +126,6 @@ where shard, metrics_api: self.metrics_api.clone(), _phantom: PhantomData, - _phantom_header: PhantomData, }) } } diff --git a/tee-worker/identity/sidechain/consensus/aura/src/slot_proposer.rs b/tee-worker/identity/sidechain/consensus/aura/src/slot_proposer.rs index eaf005d3a2..2424df56f6 100644 --- a/tee-worker/identity/sidechain/consensus/aura/src/slot_proposer.rs +++ b/tee-worker/identity/sidechain/consensus/aura/src/slot_proposer.rs @@ -35,31 +35,28 @@ use its_primitives::traits::{ use its_state::{SidechainState, SidechainSystemExt}; use log::*; use sp_runtime::{ - traits::{Block, Header as ParentchainHeaderTrait, NumberFor}, + traits::{Block, NumberFor}, MultiSignature, }; use std::{marker::PhantomData, string::ToString, sync::Arc, time::Duration, vec::Vec}; -pub type ExternalitiesFor = - >::Externalities; +pub type ExternalitiesFor = >::Externalities; ///! `SlotProposer` instance that has access to everything needed to propose a sidechain block. pub struct SlotProposer< - ParentchainBlock: Block
, + ParentchainBlock: Block, SignedSidechainBlock: SignedSidechainBlockTrait, TopPoolAuthor, StfExecutor, BlockComposer, MetricsApi, - ParentchainHeader, > { pub(crate) top_pool_author: Arc, pub(crate) stf_executor: Arc, pub(crate) block_composer: Arc, - pub(crate) parentchain_header: ParentchainHeader, + pub(crate) parentchain_header: ParentchainBlock::Header, pub(crate) shard: ShardIdentifierFor, pub(crate) metrics_api: Arc, pub(crate) _phantom: PhantomData, - pub(crate) _phantom_header: PhantomData, } impl< @@ -69,7 +66,6 @@ impl< BlockComposer, StfExecutor, MetricsApi, - PH, > Proposer for SlotProposer< ParentchainBlock, @@ -78,30 +74,28 @@ impl< StfExecutor, BlockComposer, MetricsApi, - PH, > where - ParentchainBlock: Block, + ParentchainBlock: Block, NumberFor: BlockNumberOps, SignedSidechainBlock: SignedSidechainBlockTrait + 'static, SignedSidechainBlock::Block: SidechainBlockTrait, <::Block as SidechainBlockTrait>::HeaderType: HeaderTrait, - StfExecutor: StateUpdateProposer, - ExternalitiesFor: + StfExecutor: StateUpdateProposer, + ExternalitiesFor: SgxExternalitiesTrait + SidechainState + SidechainSystemExt + StateHash, - as SgxExternalitiesTrait>::SgxExternalitiesType: Encode, + as SgxExternalitiesTrait>::SgxExternalitiesType: Encode, TopPoolAuthor: AuthorApi + Send + Sync + 'static, BlockComposer: ComposeBlock< - ExternalitiesFor, + ExternalitiesFor, ParentchainBlock, SignedSidechainBlock = SignedSidechainBlock, > + Send + Sync + 'static, MetricsApi: EnclaveMetricsOCallApi, - PH: ParentchainHeaderTrait, { /// Proposes a new sidechain block. /// From 205a71bab2a227c2c9d3a85959c11c38854c613c Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 10 Oct 2024 15:25:15 +0000 Subject: [PATCH 30/39] Revert "fixing tests" This reverts commit 32ffc5e0318fb7f482c71db41978354e280765e6. --- .../bitacross/core/offchain-worker-executor/src/executor.rs | 5 +---- .../identity/core/offchain-worker-executor/src/executor.rs | 5 +---- 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/tee-worker/bitacross/core/offchain-worker-executor/src/executor.rs b/tee-worker/bitacross/core/offchain-worker-executor/src/executor.rs index a9fcee8f66..5cf3e778b8 100644 --- a/tee-worker/bitacross/core/offchain-worker-executor/src/executor.rs +++ b/tee-worker/bitacross/core/offchain-worker-executor/src/executor.rs @@ -261,9 +261,7 @@ mod tests { stf_mock::{GetterMock, TrustedCallSignedMock}, }; use itp_top_pool_author::mocks::AuthorApiMock; - use itp_types::{ - parentchain::Header as ParentchainHeader, Block as ParentchainBlock, RsaRequest, - }; + use itp_types::{Block as ParentchainBlock, RsaRequest}; use itp_test::mock::stf_mock::mock_top_indirect_trusted_call_signed; use std::boxed::Box; @@ -285,7 +283,6 @@ mod tests { TestStfInterface, TrustedCallSignedMock, GetterMock, - ParentchainHeader, >; const EVENT_COUNT_KEY: &[u8] = b"event_count"; diff --git a/tee-worker/identity/core/offchain-worker-executor/src/executor.rs b/tee-worker/identity/core/offchain-worker-executor/src/executor.rs index a9fcee8f66..5cf3e778b8 100644 --- a/tee-worker/identity/core/offchain-worker-executor/src/executor.rs +++ b/tee-worker/identity/core/offchain-worker-executor/src/executor.rs @@ -261,9 +261,7 @@ mod tests { stf_mock::{GetterMock, TrustedCallSignedMock}, }; use itp_top_pool_author::mocks::AuthorApiMock; - use itp_types::{ - parentchain::Header as ParentchainHeader, Block as ParentchainBlock, RsaRequest, - }; + use itp_types::{Block as ParentchainBlock, RsaRequest}; use itp_test::mock::stf_mock::mock_top_indirect_trusted_call_signed; use std::boxed::Box; @@ -285,7 +283,6 @@ mod tests { TestStfInterface, TrustedCallSignedMock, GetterMock, - ParentchainHeader, >; const EVENT_COUNT_KEY: &[u8] = b"event_count"; From 8e2f0c55091f6961df46e79b13bcb5487b0aca6c Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 10 Oct 2024 15:36:03 +0000 Subject: [PATCH 31/39] cleaning up dependencies --- tee-worker/Cargo.lock | 2 -- tee-worker/bitacross/app-libs/stf/Cargo.toml | 2 -- .../bitacross/app-libs/stf/src/stf_sgx_tests.rs | 2 -- tee-worker/bitacross/enclave-runtime/Cargo.lock | 13 ++++++------- 4 files changed, 6 insertions(+), 13 deletions(-) diff --git a/tee-worker/Cargo.lock b/tee-worker/Cargo.lock index 5ff2ee7d1a..35b97ff77e 100644 --- a/tee-worker/Cargo.lock +++ b/tee-worker/Cargo.lock @@ -445,8 +445,6 @@ dependencies = [ "hex-literal", "itp-hashing", "itp-node-api", - "itp-ocall-api", - "itp-sgx-crypto", "itp-sgx-externalities", "itp-stf-interface", "itp-stf-primitives", diff --git a/tee-worker/bitacross/app-libs/stf/Cargo.toml b/tee-worker/bitacross/app-libs/stf/Cargo.toml index d43d9a633a..d3016c539c 100644 --- a/tee-worker/bitacross/app-libs/stf/Cargo.toml +++ b/tee-worker/bitacross/app-libs/stf/Cargo.toml @@ -14,8 +14,6 @@ sgx_tstd = { workspace = true, features = ["untrusted_fs", "net", "backtrace"], itp-hashing = { workspace = true } itp-node-api = { workspace = true } -itp-ocall-api = { workspace = true } -itp-sgx-crypto = { workspace = true } itp-sgx-externalities = { workspace = true } itp-stf-interface = { workspace = true } itp-stf-primitives = { workspace = true } diff --git a/tee-worker/bitacross/app-libs/stf/src/stf_sgx_tests.rs b/tee-worker/bitacross/app-libs/stf/src/stf_sgx_tests.rs index 8a5eb0c111..479f3b9bb0 100644 --- a/tee-worker/bitacross/app-libs/stf/src/stf_sgx_tests.rs +++ b/tee-worker/bitacross/app-libs/stf/src/stf_sgx_tests.rs @@ -18,8 +18,6 @@ use crate::{Getter, State, Stf, TrustedCall, TrustedCallSigned}; use ita_sgx_runtime::Runtime; use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; -use itp_ocall_api::mock::OnchainMock; -use itp_sgx_crypto::{mocks::KeyRepositoryMock, Aes}; use itp_stf_interface::{ sudo_pallet::SudoPalletInterface, system_pallet::SystemPalletAccountInterface, InitState, StateCallInterface, diff --git a/tee-worker/bitacross/enclave-runtime/Cargo.lock b/tee-worker/bitacross/enclave-runtime/Cargo.lock index 949176f1aa..a4bdff99eb 100644 --- a/tee-worker/bitacross/enclave-runtime/Cargo.lock +++ b/tee-worker/bitacross/enclave-runtime/Cargo.lock @@ -324,8 +324,6 @@ dependencies = [ "hex-literal", "itp-hashing", "itp-node-api", - "itp-ocall-api", - "itp-sgx-crypto", "itp-sgx-externalities", "itp-stf-interface", "itp-stf-primitives", @@ -971,7 +969,7 @@ checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" [[package]] name = "core-primitives" version = "0.1.0" -source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#ea133d42f915d6e3cbbc51304f534d0b9f42e5d3" +source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#84afa8035ad15a50b57ec9f7d3845d03bc9a426b" dependencies = [ "base58", "frame-support", @@ -982,6 +980,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", + "sp-core-hashing", "sp-io", "sp-runtime", "sp-std", @@ -2767,7 +2766,7 @@ dependencies = [ [[package]] name = "litentry-hex-utils" version = "0.1.0" -source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#ea133d42f915d6e3cbbc51304f534d0b9f42e5d3" +source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#84afa8035ad15a50b57ec9f7d3845d03bc9a426b" dependencies = [ "hex", ] @@ -2779,7 +2778,7 @@ version = "0.1.0" [[package]] name = "litentry-macros" version = "0.1.0" -source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#ea133d42f915d6e3cbbc51304f534d0b9f42e5d3" +source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#84afa8035ad15a50b57ec9f7d3845d03bc9a426b" [[package]] name = "litentry-primitives" @@ -2818,7 +2817,7 @@ dependencies = [ [[package]] name = "litentry-proc-macros" version = "0.1.0" -source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#ea133d42f915d6e3cbbc51304f534d0b9f42e5d3" +source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#84afa8035ad15a50b57ec9f7d3845d03bc9a426b" dependencies = [ "cargo_toml", "proc-macro2", @@ -3193,7 +3192,7 @@ dependencies = [ [[package]] name = "pallet-teebag" version = "0.1.0" -source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#ea133d42f915d6e3cbbc51304f534d0b9f42e5d3" +source = "git+https://github.com/litentry/litentry-parachain?branch=release-v0.9.19#84afa8035ad15a50b57ec9f7d3845d03bc9a426b" dependencies = [ "base64 0.13.1", "chrono 0.4.31", From 78ced91ea14ea42a13b5e3a8347cd85a4fbed994 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 10 Oct 2024 15:46:57 +0000 Subject: [PATCH 32/39] cleaning up dependencies --- tee-worker/Cargo.lock | 2 -- tee-worker/identity/app-libs/stf/Cargo.toml | 2 -- tee-worker/identity/enclave-runtime/Cargo.lock | 2 -- 3 files changed, 6 deletions(-) diff --git a/tee-worker/Cargo.lock b/tee-worker/Cargo.lock index 35b97ff77e..c26141ecca 100644 --- a/tee-worker/Cargo.lock +++ b/tee-worker/Cargo.lock @@ -3395,8 +3395,6 @@ dependencies = [ "itp-node-api", "itp-node-api-metadata", "itp-node-api-metadata-provider", - "itp-ocall-api", - "itp-sgx-crypto", "itp-sgx-externalities", "itp-stf-interface", "itp-stf-primitives", diff --git a/tee-worker/identity/app-libs/stf/Cargo.toml b/tee-worker/identity/app-libs/stf/Cargo.toml index a19b15ca1f..02b7067a1b 100644 --- a/tee-worker/identity/app-libs/stf/Cargo.toml +++ b/tee-worker/identity/app-libs/stf/Cargo.toml @@ -17,8 +17,6 @@ sgx_tstd = { workspace = true, features = ["untrusted_fs", "net", "backtrace"], itp-hashing = { workspace = true } itp-node-api = { workspace = true } itp-node-api-metadata = { workspace = true } -itp-ocall-api = { workspace = true } -itp-sgx-crypto = { workspace = true } itp-sgx-externalities = { workspace = true } itp-stf-interface = { workspace = true } itp-stf-primitives = { workspace = true } diff --git a/tee-worker/identity/enclave-runtime/Cargo.lock b/tee-worker/identity/enclave-runtime/Cargo.lock index af0fdff788..6e02d80e6a 100644 --- a/tee-worker/identity/enclave-runtime/Cargo.lock +++ b/tee-worker/identity/enclave-runtime/Cargo.lock @@ -1925,8 +1925,6 @@ dependencies = [ "itp-node-api", "itp-node-api-metadata", "itp-node-api-metadata-provider", - "itp-ocall-api", - "itp-sgx-crypto", "itp-sgx-externalities", "itp-stf-interface", "itp-stf-primitives", From 34288c004c69a3304a5c8e5636df2c525b631995 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Thu, 10 Oct 2024 15:50:55 +0000 Subject: [PATCH 33/39] removing dead code --- .../core-primitives/ocall-api/src/mock.rs | 104 ------------------ 1 file changed, 104 deletions(-) delete mode 100644 tee-worker/common/core-primitives/ocall-api/src/mock.rs diff --git a/tee-worker/common/core-primitives/ocall-api/src/mock.rs b/tee-worker/common/core-primitives/ocall-api/src/mock.rs deleted file mode 100644 index fd6da98d47..0000000000 --- a/tee-worker/common/core-primitives/ocall-api/src/mock.rs +++ /dev/null @@ -1,104 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - 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::{EnclaveOnChainOCallApi, Error as OCallApiError}; -use alloc::{collections::BTreeMap, string::String, vec::Vec}; -use codec::{Decode, Encode}; -use core::fmt::Debug; -use itp_storage::Error::StorageValueUnavailable; -use itp_types::{ - parentchain::ParentchainId, storage::StorageEntryVerified, AccountId, BlockHash, - ShardIdentifier, WorkerRequest, WorkerResponse, WorkerType, -}; -use sgx_types::*; -use sp_core::H256; -use sp_runtime::{traits::Header as HeaderTrait, OpaqueExtrinsic}; -use sp_std::prelude::*; - -#[derive(Default, Clone, Debug)] -pub struct OnchainMock { - inner: BTreeMap, Vec>, -} - -impl OnchainMock { - pub fn get_at_header>( - &self, - header: &Header, - key: &[u8], - ) -> Option<&Vec> { - let key_with_header = (header, key).encode(); - self.inner.get(&key_with_header) - } -} - -impl EnclaveOnChainOCallApi for OnchainMock { - fn send_to_parentchain( - &self, - _extrinsics: Vec, - _: &ParentchainId, - _: bool, - ) -> SgxResult<()> { - Ok(()) - } - - fn worker_request( - &self, - _req: Vec, - _: &ParentchainId, - ) -> SgxResult>> { - Ok(Vec::new()) - } - - fn get_storage_verified, V: Decode>( - &self, - storage_hash: Vec, - header: &Header, - parentchain_id: &ParentchainId, - ) -> Result, OCallApiError> { - self.get_multiple_storages_verified(vec![storage_hash], header, parentchain_id)? - .into_iter() - .next() - .ok_or_else(|| OCallApiError::Storage(StorageValueUnavailable)) - } - - fn get_multiple_storages_verified, V: Decode>( - &self, - storage_hashes: Vec>, - header: &Header, - _: &ParentchainId, - ) -> Result>, OCallApiError> { - let mut entries = Vec::with_capacity(storage_hashes.len()); - for hash in storage_hashes.into_iter() { - let value = self - .get_at_header(header, &hash) - .map(|val| Decode::decode(&mut val.as_slice())) - .transpose() - .map_err(OCallApiError::Codec)?; - - entries.push(StorageEntryVerified::new(hash, value)) - } - Ok(entries) - } - - fn get_storage_keys>( - &self, - _key_prefix: Vec, - _header: Option<&H>, - ) -> Result>, OCallApiError> { - Ok(Default::default()) - } -} From f00ad0bd8ebf10b3294f8928044b1e3312eb07ee Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Sat, 12 Oct 2024 10:36:48 +0000 Subject: [PATCH 34/39] cleaning up dependencies --- common/primitives/core/Cargo.toml | 15 +++++++------- .../core/src/teebag/sgx_verify/mod.rs | 2 -- parachain/Cargo.lock | 2 -- parachain/pallets/omni-account/Cargo.toml | 1 - tee-worker/Cargo.lock | 20 +++---------------- .../identity/enclave-runtime/Cargo.lock | 20 +++---------------- 6 files changed, 13 insertions(+), 47 deletions(-) diff --git a/common/primitives/core/Cargo.toml b/common/primitives/core/Cargo.toml index 58e52c8f8e..c07ca703d3 100644 --- a/common/primitives/core/Cargo.toml +++ b/common/primitives/core/Cargo.toml @@ -7,24 +7,23 @@ version = '0.1.0' [dependencies] base58 = { version = "0.2", default-features = false } base64 = { version = "0.13", default-features = false, features = ["alloc"] } -parity-scale-codec = { version = "3.6", default-features = false, features = ["derive", "max-encoded-len"] } -strum = { version = "0.26", default-features = false } -strum_macros = { version = "0.26", default-features = false } -serde = { version = "1.0", default-features = false, features = ["derive", "alloc"] } -serde_json = { version = "=1.0.120", default-features = false } +chrono = { version = "0.4", default-features = false, features = ["serde"] } der = { version = "0.6.0", default-features = false } hex = { version = "0.4", default-features = false } hex-literal = { version = "0.4.1", default-features = false } -chrono = { version = "0.4", default-features = false, features = ["serde"] } +parity-scale-codec = { version = "3.6", default-features = false, features = ["derive", "max-encoded-len"] } ring = { version = "0.16.20", default-features = false, features = ["alloc"] } -x509-cert = { version = "0.1.0", default-features = false, features = ["alloc"] } +serde = { version = "1.0", default-features = false, features = ["derive", "alloc"] } +serde_json = { version = "=1.0.120", default-features = false } +strum = { version = "0.26", default-features = false } +strum_macros = { version = "0.26", default-features = false } webpki = { version = "=0.102.0-alpha.3", git = "https://github.com/rustls/webpki", rev = "da923ed", package = "rustls-webpki", default-features = false, features = ["alloc", "ring"] } +x509-cert = { version = "0.1.0", default-features = false, features = ["alloc"] } frame-support = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } pallet-evm = { git = "https://github.com/paritytech/frontier", branch = "polkadot-v1.1.0", default-features = false } scale-info = { version = "2.11", default-features = false, features = ["derive"] } sp-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } -sp-core-hashing = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } sp-io = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } sp-std = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } diff --git a/common/primitives/core/src/teebag/sgx_verify/mod.rs b/common/primitives/core/src/teebag/sgx_verify/mod.rs index d07583dc14..2a8ee2d251 100644 --- a/common/primitives/core/src/teebag/sgx_verify/mod.rs +++ b/common/primitives/core/src/teebag/sgx_verify/mod.rs @@ -28,8 +28,6 @@ //! //! * https://download.01.org/intel-sgx/linux-1.5/docs/Intel_SGX_Developer_Guide.pdf -pub extern crate alloc; - use self::{ collateral::{EnclaveIdentity, TcbInfo}, netscape_comment::NetscapeComment, diff --git a/parachain/Cargo.lock b/parachain/Cargo.lock index f01d29bf2a..6a4230119a 100644 --- a/parachain/Cargo.lock +++ b/parachain/Cargo.lock @@ -1457,7 +1457,6 @@ dependencies = [ "serde", "serde_json", "sp-core", - "sp-core-hashing", "sp-io", "sp-runtime", "sp-std", @@ -7832,7 +7831,6 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", - "sp-core-hashing", "sp-io", "sp-keyring", "sp-runtime", diff --git a/parachain/pallets/omni-account/Cargo.toml b/parachain/pallets/omni-account/Cargo.toml index 1a86c5ba09..fb5c35df7e 100644 --- a/parachain/pallets/omni-account/Cargo.toml +++ b/parachain/pallets/omni-account/Cargo.toml @@ -26,7 +26,6 @@ pallet-timestamp = { workspace = true, features = ["std"] } pallet-teebag = { workspace = true, features = ["std", "test-util"] } pallet-utility = { workspace = true, features = ["std"] } sp-keyring = { workspace = true } -sp-core-hashing = { workspace = true } [features] default = ["std"] diff --git a/tee-worker/Cargo.lock b/tee-worker/Cargo.lock index 466c6cb82d..2f1dd4c7b1 100644 --- a/tee-worker/Cargo.lock +++ b/tee-worker/Cargo.lock @@ -63,7 +63,7 @@ dependencies = [ "serde_json 1.0.120", "sp-application-crypto", "sp-core", - "sp-core-hashing 5.0.0", + "sp-core-hashing", "sp-runtime", "sp-runtime-interface", "sp-staking", @@ -1473,7 +1473,6 @@ dependencies = [ "serde 1.0.210", "serde_json 1.0.120", "sp-core", - "sp-core-hashing 9.0.0", "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std", @@ -8633,7 +8632,7 @@ dependencies = [ "secp256k1 0.24.3", "secrecy", "serde 1.0.210", - "sp-core-hashing 5.0.0", + "sp-core-hashing", "sp-debug-derive", "sp-externalities", "sp-runtime-interface", @@ -8660,19 +8659,6 @@ dependencies = [ "twox-hash", ] -[[package]] -name = "sp-core-hashing" -version = "9.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.1.0#65a434a0ed474c14f692dcf9f69f8da66a99d401" -dependencies = [ - "blake2b_simd", - "byteorder 1.4.3", - "digest 0.10.7", - "sha2 0.10.8", - "sha3", - "twox-hash", -] - [[package]] name = "sp-core-hashing-proc-macro" version = "5.0.0" @@ -8680,7 +8666,7 @@ source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff dependencies = [ "proc-macro2", "quote", - "sp-core-hashing 5.0.0", + "sp-core-hashing", "syn 2.0.79", ] diff --git a/tee-worker/identity/enclave-runtime/Cargo.lock b/tee-worker/identity/enclave-runtime/Cargo.lock index 2ad3b60425..7a29efe6e8 100644 --- a/tee-worker/identity/enclave-runtime/Cargo.lock +++ b/tee-worker/identity/enclave-runtime/Cargo.lock @@ -60,7 +60,7 @@ dependencies = [ "serde_json 1.0.120", "sp-application-crypto", "sp-core", - "sp-core-hashing 5.0.0", + "sp-core-hashing", "sp-runtime", "sp-runtime-interface", "sp-staking", @@ -631,7 +631,6 @@ dependencies = [ "serde 1.0.204", "serde_json 1.0.120", "sp-core", - "sp-core-hashing 9.0.0", "sp-io", "sp-runtime", "sp-std", @@ -4980,7 +4979,7 @@ dependencies = [ "schnorrkel", "secp256k1 0.24.3", "secrecy", - "sp-core-hashing 5.0.0", + "sp-core-hashing", "sp-debug-derive", "sp-runtime-interface", "sp-std", @@ -5003,19 +5002,6 @@ dependencies = [ "twox-hash", ] -[[package]] -name = "sp-core-hashing" -version = "9.0.0" -source = "git+https://github.com/paritytech/polkadot-sdk?branch=release-polkadot-v1.1.0#65a434a0ed474c14f692dcf9f69f8da66a99d401" -dependencies = [ - "blake2b_simd 1.0.2", - "byteorder 1.4.3", - "digest 0.10.7", - "sha2 0.10.7", - "sha3 0.10.8", - "twox-hash", -] - [[package]] name = "sp-core-hashing-proc-macro" version = "5.0.0" @@ -5023,7 +5009,7 @@ source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff dependencies = [ "proc-macro2", "quote 1.0.36", - "sp-core-hashing 5.0.0", + "sp-core-hashing", "syn 2.0.72", ] From 92cf32846813b8342648f53fc7dfcd9b5a71dc44 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Sat, 12 Oct 2024 10:40:21 +0000 Subject: [PATCH 35/39] fixing fmt --- common/primitives/core/src/omni_account.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/common/primitives/core/src/omni_account.rs b/common/primitives/core/src/omni_account.rs index 3a8d93c803..62385f802f 100644 --- a/common/primitives/core/src/omni_account.rs +++ b/common/primitives/core/src/omni_account.rs @@ -76,4 +76,3 @@ impl GetAccountStoreHash for Vec { hashes.using_encoded(blake2_256).into() } } - From 6ef64ace851495831f565ebc554b951cdca22ab7 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Tue, 15 Oct 2024 12:56:00 +0000 Subject: [PATCH 36/39] making types simpler as hash can be computed in all members --- .../core/omni-account/src/in_memory_store.rs | 18 +++++++----------- .../litentry/core/omni-account/src/lib.rs | 8 +------- .../core/omni-account/src/repository.rs | 16 ++++++---------- 3 files changed, 14 insertions(+), 28 deletions(-) diff --git a/tee-worker/identity/litentry/core/omni-account/src/in_memory_store.rs b/tee-worker/identity/litentry/core/omni-account/src/in_memory_store.rs index 12572f5dba..7631047f94 100644 --- a/tee-worker/identity/litentry/core/omni-account/src/in_memory_store.rs +++ b/tee-worker/identity/litentry/core/omni-account/src/in_memory_store.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Litentry. If not, see . -use crate::{AccountId, BTreeMap, Error, OmniAccountMembers, OmniAccounts}; +use crate::{AccountId, BTreeMap, Error, OmniAccountMembers, OmniAccounts, Vec}; use lazy_static::lazy_static; #[cfg(feature = "std")] @@ -42,39 +42,35 @@ impl InMemoryStore { omni_account_members.ok_or(Error::NotFound) } - pub fn insert( - &self, - owner: AccountId, - omni_account_members: OmniAccountMembers, - ) -> Result<(), Error> { + pub fn insert(&self, account_id: AccountId, members: Vec) -> Result<(), Error> { STORE .write() .map_err(|_| { log::error!("[InMemoryStore] Lock poisoning"); Error::LockPoisoning })? - .insert(owner, omni_account_members); + .insert(account_id, members); Ok(()) } - pub fn remove(&self, owner: AccountId) -> Result<(), Error> { + pub fn remove(&self, account_id: AccountId) -> Result<(), Error> { STORE .write() .map_err(|_| { log::error!("[InMemoryStore] Lock poisoning"); Error::LockPoisoning })? - .remove(&owner); + .remove(&account_id); Ok(()) } - pub fn load(&self, omni_accounts: OmniAccounts) -> Result<(), Error> { + pub fn load(&self, accounts: OmniAccounts) -> Result<(), Error> { *STORE.write().map_err(|_| { log::error!("[InMemoryStore] Lock poisoning"); Error::LockPoisoning - })? = omni_accounts; + })? = accounts; Ok(()) } diff --git a/tee-worker/identity/litentry/core/omni-account/src/lib.rs b/tee-worker/identity/litentry/core/omni-account/src/lib.rs index ba7b84afe8..fa8ef711b2 100644 --- a/tee-worker/identity/litentry/core/omni-account/src/lib.rs +++ b/tee-worker/identity/litentry/core/omni-account/src/lib.rs @@ -34,13 +34,7 @@ use alloc::{collections::btree_map::BTreeMap, vec::Vec}; use itp_types::parentchain::{AccountId, Hash, Header, ParentchainId}; use litentry_primitives::MemberAccount; -pub type OmniAccounts = BTreeMap; - -#[derive(Debug, Clone)] -pub struct OmniAccountMembers { - pub member_accounts: Vec, - pub hash: Hash, -} +pub type OmniAccounts = BTreeMap>; #[derive(Debug)] pub enum Error { diff --git a/tee-worker/identity/litentry/core/omni-account/src/repository.rs b/tee-worker/identity/litentry/core/omni-account/src/repository.rs index 9360a35a03..0c6e75ec3b 100644 --- a/tee-worker/identity/litentry/core/omni-account/src/repository.rs +++ b/tee-worker/identity/litentry/core/omni-account/src/repository.rs @@ -24,8 +24,8 @@ use itp_storage::{ use litentry_primitives::{GetAccountStoreHash, MemberAccount}; pub trait GetAccountStoresRepository { - fn get_by_owner(&self, owner: AccountId) -> Result; - fn get(&self) -> Result; + fn get_by_account_id(&self, account_id: AccountId) -> Result, Error>; + fn get_all(&self) -> Result; } pub struct OmniAccountRepository { @@ -46,7 +46,7 @@ impl OmniAccountRepository { impl GetAccountStoresRepository for OmniAccountRepository { - fn get_by_owner(&self, owner: AccountId) -> Result { + fn get_by_account_id(&self, owner: AccountId) -> Result, Error> { let storage_key = storage_map_key( "OmniAccount", "AccountStore", @@ -59,12 +59,11 @@ impl GetAccountStoresRepository .map_err(|_| Error::OCallApiError("Failed to get storage"))?; let member_accounts: Vec = storage_entry.value().to_owned().ok_or(Error::NotFound)?; - let account_store_hash = member_accounts.hash(); - Ok(OmniAccountMembers { member_accounts, hash: account_store_hash }) + Ok(member_accounts) } - fn get(&self) -> Result { + fn get_all(&self) -> Result { let account_store_key_prefix = storage_prefix(b"OmniAccount", b"AccountStore"); let account_store_storage_keys_response = self .ocall_api @@ -88,10 +87,7 @@ impl GetAccountStoresRepository let storage_key = decode_storage_key(entry.key)?; let account_id: AccountId = extract_blake2_128concat_key(&storage_key)?; let member_accounts: Vec = entry.value?; - let account_store_hash = member_accounts.hash(); - let omni_account_members = - OmniAccountMembers { member_accounts, hash: account_store_hash }; - Some((account_id, omni_account_members)) + Some((account_id, member_accounts)) }) .collect(); From e2b3758cdab1260922adaf7b1f9dd631a0248620 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Tue, 15 Oct 2024 12:59:11 +0000 Subject: [PATCH 37/39] removing unused imports --- .../litentry/core/omni-account/src/in_memory_store.rs | 4 ++-- tee-worker/identity/litentry/core/omni-account/src/lib.rs | 2 +- .../identity/litentry/core/omni-account/src/repository.rs | 3 +-- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/tee-worker/identity/litentry/core/omni-account/src/in_memory_store.rs b/tee-worker/identity/litentry/core/omni-account/src/in_memory_store.rs index 7631047f94..3b4f5e4a8d 100644 --- a/tee-worker/identity/litentry/core/omni-account/src/in_memory_store.rs +++ b/tee-worker/identity/litentry/core/omni-account/src/in_memory_store.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Litentry. If not, see . -use crate::{AccountId, BTreeMap, Error, OmniAccountMembers, OmniAccounts, Vec}; +use crate::{AccountId, BTreeMap, Error, MemberAccount, OmniAccounts, Vec}; use lazy_static::lazy_static; #[cfg(feature = "std")] @@ -29,7 +29,7 @@ lazy_static! { pub struct InMemoryStore; impl InMemoryStore { - pub fn get(&self, owner: AccountId) -> Result { + pub fn get(&self, owner: AccountId) -> Result, Error> { let omni_account_members = STORE .read() .map_err(|_| { diff --git a/tee-worker/identity/litentry/core/omni-account/src/lib.rs b/tee-worker/identity/litentry/core/omni-account/src/lib.rs index fa8ef711b2..1d059389f2 100644 --- a/tee-worker/identity/litentry/core/omni-account/src/lib.rs +++ b/tee-worker/identity/litentry/core/omni-account/src/lib.rs @@ -31,7 +31,7 @@ mod in_memory_store; pub use in_memory_store::InMemoryStore; use alloc::{collections::btree_map::BTreeMap, vec::Vec}; -use itp_types::parentchain::{AccountId, Hash, Header, ParentchainId}; +use itp_types::parentchain::{AccountId, Header, ParentchainId}; use litentry_primitives::MemberAccount; pub type OmniAccounts = BTreeMap>; diff --git a/tee-worker/identity/litentry/core/omni-account/src/repository.rs b/tee-worker/identity/litentry/core/omni-account/src/repository.rs index 0c6e75ec3b..3e3f5eba22 100644 --- a/tee-worker/identity/litentry/core/omni-account/src/repository.rs +++ b/tee-worker/identity/litentry/core/omni-account/src/repository.rs @@ -14,14 +14,13 @@ // You should have received a copy of the GNU General Public License // along with Litentry. If not, see . -use crate::{AccountId, Error, Header, OmniAccountMembers, OmniAccounts, ParentchainId}; +use crate::{AccountId, Error, Header, MemberAccount, OmniAccounts, ParentchainId}; use alloc::vec::Vec; use frame_support::storage::storage_prefix; use itp_ocall_api::EnclaveOnChainOCallApi; use itp_storage::{ decode_storage_key, extract_blake2_128concat_key, storage_map_key, StorageHasher, }; -use litentry_primitives::{GetAccountStoreHash, MemberAccount}; pub trait GetAccountStoresRepository { fn get_by_account_id(&self, account_id: AccountId) -> Result, Error>; From 698621712e35e2c75c602deaaeae78413800e511 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 16 Oct 2024 09:09:51 +0000 Subject: [PATCH 38/39] feat: update get methods to return Option type --- .../litentry/core/omni-account/src/in_memory_store.rs | 4 ++-- tee-worker/identity/litentry/core/omni-account/src/lib.rs | 1 - .../identity/litentry/core/omni-account/src/repository.rs | 5 ++--- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/tee-worker/identity/litentry/core/omni-account/src/in_memory_store.rs b/tee-worker/identity/litentry/core/omni-account/src/in_memory_store.rs index 3b4f5e4a8d..30da7a4234 100644 --- a/tee-worker/identity/litentry/core/omni-account/src/in_memory_store.rs +++ b/tee-worker/identity/litentry/core/omni-account/src/in_memory_store.rs @@ -29,7 +29,7 @@ lazy_static! { pub struct InMemoryStore; impl InMemoryStore { - pub fn get(&self, owner: AccountId) -> Result, Error> { + pub fn get(&self, owner: AccountId) -> Result>, Error> { let omni_account_members = STORE .read() .map_err(|_| { @@ -39,7 +39,7 @@ impl InMemoryStore { .get(&owner) .cloned(); - omni_account_members.ok_or(Error::NotFound) + Ok(omni_account_members) } pub fn insert(&self, account_id: AccountId, members: Vec) -> Result<(), Error> { diff --git a/tee-worker/identity/litentry/core/omni-account/src/lib.rs b/tee-worker/identity/litentry/core/omni-account/src/lib.rs index 1d059389f2..506ff11c41 100644 --- a/tee-worker/identity/litentry/core/omni-account/src/lib.rs +++ b/tee-worker/identity/litentry/core/omni-account/src/lib.rs @@ -39,6 +39,5 @@ pub type OmniAccounts = BTreeMap>; #[derive(Debug)] pub enum Error { LockPoisoning, - NotFound, OCallApiError(&'static str), } diff --git a/tee-worker/identity/litentry/core/omni-account/src/repository.rs b/tee-worker/identity/litentry/core/omni-account/src/repository.rs index 3e3f5eba22..e21271b323 100644 --- a/tee-worker/identity/litentry/core/omni-account/src/repository.rs +++ b/tee-worker/identity/litentry/core/omni-account/src/repository.rs @@ -45,7 +45,7 @@ impl OmniAccountRepository { impl GetAccountStoresRepository for OmniAccountRepository { - fn get_by_account_id(&self, owner: AccountId) -> Result, Error> { + fn get_by_account_id(&self, owner: AccountId) -> Result>, Error> { let storage_key = storage_map_key( "OmniAccount", "AccountStore", @@ -56,8 +56,7 @@ impl GetAccountStoresRepository .ocall_api .get_storage_verified(storage_key, &self.header, &ParentchainId::Litentry) .map_err(|_| Error::OCallApiError("Failed to get storage"))?; - let member_accounts: Vec = - storage_entry.value().to_owned().ok_or(Error::NotFound)?; + let member_accounts = storage_entry.value().to_owned(); Ok(member_accounts) } From 05959756d5f455854fee45fd7c407b0a9701f81d Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 16 Oct 2024 09:25:57 +0000 Subject: [PATCH 39/39] updating trait --- .../identity/litentry/core/omni-account/src/repository.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tee-worker/identity/litentry/core/omni-account/src/repository.rs b/tee-worker/identity/litentry/core/omni-account/src/repository.rs index e21271b323..c12993d1eb 100644 --- a/tee-worker/identity/litentry/core/omni-account/src/repository.rs +++ b/tee-worker/identity/litentry/core/omni-account/src/repository.rs @@ -23,7 +23,8 @@ use itp_storage::{ }; pub trait GetAccountStoresRepository { - fn get_by_account_id(&self, account_id: AccountId) -> Result, Error>; + fn get_by_account_id(&self, account_id: AccountId) + -> Result>, Error>; fn get_all(&self) -> Result; }