From f249daffefa8713d8368e7d52a6d17bcff0ba84d Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Tue, 30 May 2023 15:25:34 +0200 Subject: [PATCH 1/6] [itp-utils] create standalone buffer error --- core-primitives/utils/src/buffer.rs | 18 +++++++++++++++--- core-primitives/utils/src/error.rs | 2 -- enclave-runtime/src/error.rs | 1 + 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/core-primitives/utils/src/buffer.rs b/core-primitives/utils/src/buffer.rs index 0a69094577..7541eff369 100644 --- a/core-primitives/utils/src/buffer.rs +++ b/core-primitives/utils/src/buffer.rs @@ -17,15 +17,20 @@ //! Buffer utility functions. -use crate::error::{Error, Result}; use frame_support::ensure; use std::vec::Vec; +#[cfg(all(not(feature = "std"), feature = "sgx"))] +use crate::sgx_reexport_prelude::thiserror; + /// Fills a given buffer with data and the left over buffer space with white spaces. -pub fn write_slice_and_whitespace_pad(writable: &mut [u8], data: Vec) -> Result<()> { +pub fn write_slice_and_whitespace_pad( + writable: &mut [u8], + data: Vec, +) -> Result<(), BufferError> { ensure!( data.len() <= writable.len(), - Error::InsufficientBufferSize(writable.len(), data.len()) + BufferError::InsufficientBufferSize(writable.len(), data.len()) ); let (left, right) = writable.split_at_mut(data.len()); left.clone_from_slice(&data); @@ -34,6 +39,13 @@ pub fn write_slice_and_whitespace_pad(writable: &mut [u8], data: Vec) -> Res Ok(()) } +/// extrinsics factory error +#[derive(Debug, thiserror::Error)] +pub enum BufferError { + #[error("Insufficient buffer size. Actual: {0}, required: {1}")] + InsufficientBufferSize(usize, usize), +} + #[cfg(test)] mod tests { use super::*; diff --git a/core-primitives/utils/src/error.rs b/core-primitives/utils/src/error.rs index 662fb189a7..ab1d8e151a 100644 --- a/core-primitives/utils/src/error.rs +++ b/core-primitives/utils/src/error.rs @@ -25,8 +25,6 @@ pub type Result = core::result::Result; /// extrinsics factory error #[derive(Debug, thiserror::Error)] pub enum Error { - #[error("Insufficient buffer size. Actual: {0}, required: {1}")] - InsufficientBufferSize(usize, usize), #[error("Could not decode from hex data: {0}")] Hex(hex::FromHexError), #[error("Parity Scale Codec: {0}")] diff --git a/enclave-runtime/src/error.rs b/enclave-runtime/src/error.rs index 4c7ac4de6f..239e1450e3 100644 --- a/enclave-runtime/src/error.rs +++ b/enclave-runtime/src/error.rs @@ -47,6 +47,7 @@ pub enum Error { MutexAccess, Attestation(itp_attestation_handler::error::Error), Metadata(itp_node_api_metadata::error::Error), + BufferError(itp_utils::buffer::BufferError), Other(Box), } From 895beceea830cb0269a1c24f9508097a847c5e10 Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Tue, 30 May 2023 15:26:41 +0200 Subject: [PATCH 2/6] add base-path to light-client initialization --- core/parentchain/light-client/src/io.rs | 6 ++-- .../src/initialization/parentchain/mod.rs | 7 ++-- .../initialization/parentchain/parachain.rs | 9 +++-- .../initialization/parentchain/solochain.rs | 9 +++-- enclave-runtime/src/lib.rs | 36 +++++++++++++------ 5 files changed, 45 insertions(+), 22 deletions(-) diff --git a/core/parentchain/light-client/src/io.rs b/core/parentchain/light-client/src/io.rs index c455b283d5..b5fabfa796 100644 --- a/core/parentchain/light-client/src/io.rs +++ b/core/parentchain/light-client/src/io.rs @@ -44,8 +44,8 @@ pub struct LightClientStateSeal { } impl LightClientStateSeal { - pub fn new(path: &str) -> Self { - Self { path_buf: PathBuf::from(path), _phantom: Default::default() } + pub fn new(path: PathBuf) -> Self { + Self { path_buf: path, _phantom: Default::default() } } } @@ -219,7 +219,7 @@ pub mod sgx_tests { pub fn init_parachain_light_client_works() { let parachain_params = default_simple_params(); let temp_dir = TempDir::with_prefix("init_parachain_light_client_works").unwrap(); - let seal = TestSeal::new(temp_dir.path().to_str().unwrap()); + let seal = TestSeal::new(temp_dir.path().to_path_buf()); let validator = read_or_init_parachain_validator::( parachain_params.clone(), diff --git a/enclave-runtime/src/initialization/parentchain/mod.rs b/enclave-runtime/src/initialization/parentchain/mod.rs index 4e2e40e749..2206289d5c 100644 --- a/enclave-runtime/src/initialization/parentchain/mod.rs +++ b/enclave-runtime/src/initialization/parentchain/mod.rs @@ -21,19 +21,20 @@ use itc_parentchain::primitives::ParentchainInitParams; use itp_settings::worker_mode::ProvideWorkerMode; use parachain::FullParachainHandler; use solochain::FullSolochainHandler; -use std::vec::Vec; +use std::{path::PathBuf, vec::Vec}; mod common; pub mod parachain; pub mod solochain; pub(crate) fn init_parentchain_components( + base_path: PathBuf, encoded_params: Vec, ) -> Result> { match ParentchainInitParams::decode(&mut encoded_params.as_slice())? { ParentchainInitParams::Parachain { params } => - FullParachainHandler::init::(params), + FullParachainHandler::init::(base_path, params), ParentchainInitParams::Solochain { params } => - FullSolochainHandler::init::(params), + FullSolochainHandler::init::(base_path, params), } } diff --git a/enclave-runtime/src/initialization/parentchain/parachain.rs b/enclave-runtime/src/initialization/parentchain/parachain.rs index 24da81921c..dc2791e0d1 100644 --- a/enclave-runtime/src/initialization/parentchain/parachain.rs +++ b/enclave-runtime/src/initialization/parentchain/parachain.rs @@ -37,7 +37,7 @@ use itp_settings::{ files::LIGHT_CLIENT_DB, worker_mode::{ProvideWorkerMode, WorkerMode}, }; -use std::{sync::Arc, vec::Vec}; +use std::{path::PathBuf, sync::Arc, vec::Vec}; pub use itc_parentchain::primitives::{ParachainBlock, ParachainHeader, ParachainParams}; @@ -53,14 +53,17 @@ pub struct FullParachainHandler { } impl FullParachainHandler { - pub fn init(params: ParachainParams) -> Result> { + pub fn init( + base_path: PathBuf, + params: ParachainParams, + ) -> Result> { let ocall_api = GLOBAL_OCALL_API_COMPONENT.get()?; let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; let node_metadata_repository = Arc::new(EnclaveNodeMetadataRepository::default()); let genesis_header = params.genesis_header.clone(); - let light_client_seal = EnclaveLightClientSeal::new(LIGHT_CLIENT_DB); + let light_client_seal = EnclaveLightClientSeal::new(base_path.join(LIGHT_CLIENT_DB)); let validator = itc_parentchain::light_client::io::read_or_init_parachain_validator::< ParachainBlock, EnclaveOCallApi, diff --git a/enclave-runtime/src/initialization/parentchain/solochain.rs b/enclave-runtime/src/initialization/parentchain/solochain.rs index b251142c91..0b1a4b1301 100644 --- a/enclave-runtime/src/initialization/parentchain/solochain.rs +++ b/enclave-runtime/src/initialization/parentchain/solochain.rs @@ -37,7 +37,7 @@ use itp_settings::{ files::LIGHT_CLIENT_DB, worker_mode::{ProvideWorkerMode, WorkerMode}, }; -use std::{sync::Arc, vec::Vec}; +use std::{path::PathBuf, sync::Arc, vec::Vec}; pub use itc_parentchain::primitives::{SolochainBlock, SolochainHeader, SolochainParams}; @@ -52,14 +52,17 @@ pub struct FullSolochainHandler { } impl FullSolochainHandler { - pub fn init(params: SolochainParams) -> Result> { + pub fn init( + base_path: PathBuf, + params: SolochainParams, + ) -> Result> { let ocall_api = GLOBAL_OCALL_API_COMPONENT.get()?; let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; let node_metadata_repository = Arc::new(EnclaveNodeMetadataRepository::default()); let genesis_header = params.genesis_header.clone(); - let light_client_seal = EnclaveLightClientSeal::new(LIGHT_CLIENT_DB); + let light_client_seal = EnclaveLightClientSeal::new(base_path.join(LIGHT_CLIENT_DB)); let validator = itc_parentchain::light_client::io::read_or_init_grandpa_validator::< SolochainBlock, EnclaveOCallApi, diff --git a/enclave-runtime/src/lib.rs b/enclave-runtime/src/lib.rs index bdd3ecee96..1c2386bdb1 100644 --- a/enclave-runtime/src/lib.rs +++ b/enclave-runtime/src/lib.rs @@ -85,6 +85,14 @@ pub type AuthorityPair = sp_core::ed25519::Pair; static BASE_PATH: OnceCell = OnceCell::new(); +fn get_base_path() -> Result { + let base_path = BASE_PATH.get().ok_or_else(|| { + Error::Other(format!("BASE_PATH not initialized. Broken enclave init flow!").into()) + })?; + + Ok(base_path.clone()) +} + /// Initialize the enclave. #[no_mangle] pub unsafe extern "C" fn init( @@ -332,22 +340,30 @@ pub unsafe extern "C" fn init_parentchain_components( ) -> sgx_status_t { info!("Initializing light client!"); + match init_parentchain_params_internal(params, params_size, latest_header, latest_header_size) { + Ok(()) => sgx_status_t::SGX_SUCCESS, + Err(e) => e.into(), + } +} + +unsafe fn init_parentchain_params_internal( + params: *const u8, + params_size: usize, + latest_header: *mut u8, + latest_header_size: usize, +) -> Result<()> { + let base_path = get_base_path()?; + let encoded_params = slice::from_raw_parts(params, params_size); let latest_header_slice = slice::from_raw_parts_mut(latest_header, latest_header_size); - let encoded_latest_header = match initialization::parentchain::init_parentchain_components::< + let encoded_latest_header = initialization::parentchain::init_parentchain_components::< WorkerModeProvider, - >(encoded_params.to_vec()) - { - Ok(h) => h, - Err(e) => return e.into(), - }; + >(base_path, encoded_params.to_vec())?; - if let Err(e) = write_slice_and_whitespace_pad(latest_header_slice, encoded_latest_header) { - return Error::Other(Box::new(e)).into() - }; + write_slice_and_whitespace_pad(latest_header_slice, encoded_latest_header)?; - sgx_status_t::SGX_SUCCESS + Ok(()) } #[no_mangle] From 3f71e3ddb21ac7256cb7043b89ecb35b32acfdc9 Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Tue, 30 May 2023 15:35:51 +0200 Subject: [PATCH 3/6] fix clippy --- enclave-runtime/src/lib.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/enclave-runtime/src/lib.rs b/enclave-runtime/src/lib.rs index 1c2386bdb1..89d5dde272 100644 --- a/enclave-runtime/src/lib.rs +++ b/enclave-runtime/src/lib.rs @@ -28,6 +28,7 @@ #[cfg(not(target_env = "sgx"))] #[macro_use] extern crate sgx_tstd as std; +extern crate alloc; use crate::{ error::{Error, Result}, @@ -42,6 +43,7 @@ use crate::{ get_triggered_dispatcher_from_solo_or_parachain, utf8_str_from_raw, DecodeRaw, }, }; +use alloc::string::ToString; use codec::{alloc::string::String, Decode}; use itc_parentchain::block_import_dispatcher::{ triggered_dispatcher::TriggerParentchainBlockImport, DispatchBlockImport, @@ -87,7 +89,7 @@ static BASE_PATH: OnceCell = OnceCell::new(); fn get_base_path() -> Result { let base_path = BASE_PATH.get().ok_or_else(|| { - Error::Other(format!("BASE_PATH not initialized. Broken enclave init flow!").into()) + Error::Other("BASE_PATH not initialized. Broken enclave init flow!".to_string().into()) })?; Ok(base_path.clone()) From b70863ea5e56af80bb8d09065cfe21c952f48dec Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Tue, 30 May 2023 15:48:15 +0200 Subject: [PATCH 4/6] remove outdated documentation --- core-primitives/utils/src/buffer.rs | 1 - core-primitives/utils/src/error.rs | 1 - 2 files changed, 2 deletions(-) diff --git a/core-primitives/utils/src/buffer.rs b/core-primitives/utils/src/buffer.rs index 7541eff369..304c0ce947 100644 --- a/core-primitives/utils/src/buffer.rs +++ b/core-primitives/utils/src/buffer.rs @@ -39,7 +39,6 @@ pub fn write_slice_and_whitespace_pad( Ok(()) } -/// extrinsics factory error #[derive(Debug, thiserror::Error)] pub enum BufferError { #[error("Insufficient buffer size. Actual: {0}, required: {1}")] diff --git a/core-primitives/utils/src/error.rs b/core-primitives/utils/src/error.rs index ab1d8e151a..02042b8781 100644 --- a/core-primitives/utils/src/error.rs +++ b/core-primitives/utils/src/error.rs @@ -22,7 +22,6 @@ use std::boxed::Box; pub type Result = core::result::Result; -/// extrinsics factory error #[derive(Debug, thiserror::Error)] pub enum Error { #[error("Could not decode from hex data: {0}")] From ba7ccff06fabf6014789d4a44e863f65203e4ec6 Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Wed, 31 May 2023 10:27:19 +0200 Subject: [PATCH 5/6] [enclave-runtime] cleanup imports --- enclave-runtime/src/lib.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/enclave-runtime/src/lib.rs b/enclave-runtime/src/lib.rs index 89d5dde272..63670aae94 100644 --- a/enclave-runtime/src/lib.rs +++ b/enclave-runtime/src/lib.rs @@ -28,7 +28,6 @@ #[cfg(not(target_env = "sgx"))] #[macro_use] extern crate sgx_tstd as std; -extern crate alloc; use crate::{ error::{Error, Result}, @@ -43,8 +42,7 @@ use crate::{ get_triggered_dispatcher_from_solo_or_parachain, utf8_str_from_raw, DecodeRaw, }, }; -use alloc::string::ToString; -use codec::{alloc::string::String, Decode}; +use codec::Decode; use itc_parentchain::block_import_dispatcher::{ triggered_dispatcher::TriggerParentchainBlockImport, DispatchBlockImport, }; @@ -61,7 +59,13 @@ use log::*; use once_cell::sync::OnceCell; use sgx_types::sgx_status_t; use sp_runtime::traits::BlakeTwo256; -use std::{boxed::Box, path::PathBuf, slice, vec::Vec}; +use std::{ + boxed::Box, + path::PathBuf, + slice, + string::{String, ToString}, + vec::Vec, +}; mod attestation; mod empty_impls; From 9844f8f6918851e2210b38026eec50b837c958bb Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Wed, 31 May 2023 11:07:55 +0200 Subject: [PATCH 6/6] minor optimizations --- enclave-runtime/src/lib.rs | 25 ++++++++++--------------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/enclave-runtime/src/lib.rs b/enclave-runtime/src/lib.rs index 63670aae94..809383c5ac 100644 --- a/enclave-runtime/src/lib.rs +++ b/enclave-runtime/src/lib.rs @@ -346,28 +346,23 @@ pub unsafe extern "C" fn init_parentchain_components( ) -> sgx_status_t { info!("Initializing light client!"); - match init_parentchain_params_internal(params, params_size, latest_header, latest_header_size) { + let encoded_params = slice::from_raw_parts(params, params_size); + let latest_header_slice = slice::from_raw_parts_mut(latest_header, latest_header_size); + + match init_parentchain_params_internal(encoded_params.to_vec(), latest_header_slice) { Ok(()) => sgx_status_t::SGX_SUCCESS, Err(e) => e.into(), } } -unsafe fn init_parentchain_params_internal( - params: *const u8, - params_size: usize, - latest_header: *mut u8, - latest_header_size: usize, -) -> Result<()> { - let base_path = get_base_path()?; - - let encoded_params = slice::from_raw_parts(params, params_size); - let latest_header_slice = slice::from_raw_parts_mut(latest_header, latest_header_size); +/// Initializes the parentchain components and writes the latest header into the `latest_header` slice. +fn init_parentchain_params_internal(params: Vec, latest_header: &mut [u8]) -> Result<()> { + use initialization::parentchain::init_parentchain_components; - let encoded_latest_header = initialization::parentchain::init_parentchain_components::< - WorkerModeProvider, - >(base_path, encoded_params.to_vec())?; + let encoded_latest_header = + init_parentchain_components::(get_base_path()?, params)?; - write_slice_and_whitespace_pad(latest_header_slice, encoded_latest_header)?; + write_slice_and_whitespace_pad(latest_header, encoded_latest_header)?; Ok(()) }