Skip to content

Commit

Permalink
injecting OnChainEncryptionKeyRepository and parentchain header to the
Browse files Browse the repository at this point in the history
stf executor
  • Loading branch information
silva-fj committed Oct 7, 2024
1 parent 7159024 commit 9fba6d1
Show file tree
Hide file tree
Showing 35 changed files with 659 additions and 137 deletions.
6 changes: 6 additions & 0 deletions tee-worker/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions tee-worker/common/core-primitives/ocall-api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,4 @@ std = [
"itp-storage/std",
"itp-types/std",
]
mocks = []
3 changes: 3 additions & 0 deletions tee-worker/common/core-primitives/ocall-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down
100 changes: 100 additions & 0 deletions tee-worker/common/core-primitives/ocall-api/src/mock.rs
Original file line number Diff line number Diff line change
@@ -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<u8>, Vec<u8>>,
}

impl OnchainMock {
pub fn get_at_header<Header: HeaderTrait<Hash = H256>>(
&self,
header: &Header,
key: &[u8],
) -> Option<&Vec<u8>> {
let key_with_header = (header, key).encode();
self.inner.get(&key_with_header)
}
}

impl EnclaveOnChainOCallApi for OnchainMock {
fn send_to_parentchain(
&self,
_extrinsics: Vec<OpaqueExtrinsic>,
_: &ParentchainId,
_: bool,
) -> SgxResult<()> {
Ok(())
}

fn worker_request<V: Encode + Decode>(
&self,
_req: Vec<WorkerRequest>,
_: &ParentchainId,
) -> SgxResult<Vec<WorkerResponse<V>>> {
Ok(Vec::new())
}

fn get_storage_verified<Header: HeaderTrait<Hash = H256>, V: Decode>(
&self,
storage_hash: Vec<u8>,
header: &Header,
parentchain_id: &ParentchainId,
) -> Result<StorageEntryVerified<V>, 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<Header: HeaderTrait<Hash = H256>, V: Decode>(
&self,
storage_hashes: Vec<Vec<u8>>,
header: &Header,
_: &ParentchainId,
) -> Result<Vec<StorageEntryVerified<V>>, 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<u8>) -> Result<Vec<Vec<u8>>, OCallApiError> {
Ok(Default::default())
}
}
14 changes: 12 additions & 2 deletions tee-worker/common/core-primitives/stf-interface/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand All @@ -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 = []
29 changes: 26 additions & 3 deletions tee-worker/common/core-primitives/stf-interface/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -62,11 +66,20 @@ pub trait UpdateState<State, StateDiff> {
}

/// Interface to execute state mutating calls on a state.
pub trait StateCallInterface<TCS, State, NodeMetadataRepository>
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<Hash = H256>,
OnChainEncryptionKeyRepository: AccessKey<KeyType = Aes>,
{
type Error: Encode;
type Result: StfExecutionResult;
Expand All @@ -77,13 +90,17 @@ 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,
call: TCS,
top_hash: H256,
calls: &mut Vec<ParentchainCall>,
node_metadata_repo: Arc<NodeMetadataRepository>,
ocall_api: Arc<OCallApi>,
parentchain_header: &PH,
on_chain_encryption_key_repo: Arc<OnChainEncryptionKeyRepository>,
) -> Result<Self::Result, Self::Error>;
}

Expand All @@ -94,10 +111,13 @@ pub trait StateGetterInterface<G, S> {
}

/// Trait used to abstract the call execution.
pub trait ExecuteCall<NodeMetadataRepository>
pub trait ExecuteCall<NodeMetadataRepository, OCallApi, PH, OnChainEncryptionKeyRepository>
where
NodeMetadataRepository: AccessNodeMetadata,
NodeMetadataRepository::MetadataType: NodeMetadataTrait,
OCallApi: EnclaveOnChainOCallApi,
PH: HeaderTrait<Hash = H256>,
OnChainEncryptionKeyRepository: AccessKey<KeyType = Aes>,
{
type Error: Encode;
type Result: StfExecutionResult;
Expand All @@ -112,6 +132,9 @@ where
top_hash: H256,
calls: &mut Vec<ParentchainCall>,
node_metadata_repo: Arc<NodeMetadataRepository>,
ocall_api: Arc<OCallApi>,
parentchain_header: &PH,
on_chain_encryption_key_repo: Arc<OnChainEncryptionKeyRepository>,
) -> Result<Self::Result, Self::Error>;

/// Get storages hashes that should be updated for a specific call.
Expand Down
33 changes: 30 additions & 3 deletions tee-worker/common/core-primitives/stf-interface/src/mocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<BlockNumber, BlakeTwo256>;

#[derive(Default)]
pub struct StateInterfaceMock<State, StateDiff> {
Expand All @@ -56,8 +63,15 @@ impl<State, StateDiff> UpdateState<State, StateDiff> for StateInterfaceMock<Stat
}
}

impl<TCS, State, StateDiff> StateCallInterface<TCS, State, NodeMetadataRepository<NodeMetadataMock>>
for StateInterfaceMock<State, StateDiff>
impl<TCS, State, StateDiff>
StateCallInterface<
TCS,
State,
NodeMetadataRepository<NodeMetadataMock>,
OnchainMock,
ParentchainHeader,
KeyRepositoryMock<Aes>,
> for StateInterfaceMock<State, StateDiff>
where
TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification,
{
Expand All @@ -71,6 +85,9 @@ where
_top_hash: H256,
_calls: &mut Vec<ParentchainCall>,
_node_metadata_repo: Arc<NodeMetadataRepository<NodeMetadataMock>>,
_ocall_api: Arc<OnchainMock>,
_parentchain_header: &ParentchainHeader,
_key_repository: Arc<KeyRepositoryMock<Aes>>,
) -> Result<Self::Result, Self::Error> {
unimplemented!()
}
Expand Down Expand Up @@ -100,7 +117,14 @@ impl<State, StateDiff> SystemPalletAccountInterface<State, AccountId>

pub struct CallExecutorMock;

impl ExecuteCall<NodeMetadataRepository<NodeMetadataMock>> for CallExecutorMock {
impl
ExecuteCall<
NodeMetadataRepository<NodeMetadataMock>,
OnchainMock,
ParentchainHeader,
KeyRepositoryMock<Aes>,
> for CallExecutorMock
{
type Error = String;
type Result = ();

Expand All @@ -110,6 +134,9 @@ impl ExecuteCall<NodeMetadataRepository<NodeMetadataMock>> for CallExecutorMock
_top_hash: H256,
_calls: &mut Vec<ParentchainCall>,
_node_metadata_repo: Arc<NodeMetadataRepository<NodeMetadataMock>>,
_ocall_api: Arc<OnchainMock>,
_parentchain_header: &ParentchainHeader,
_key_repository: Arc<KeyRepositoryMock<Aes>>,
) -> Result<(), Self::Error> {
unimplemented!()
}
Expand Down
2 changes: 1 addition & 1 deletion tee-worker/common/core-primitives/test/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
Loading

0 comments on commit 9fba6d1

Please sign in to comment.