diff --git a/core-primitives/utils/src/buffer.rs b/core-primitives/utils/src/buffer.rs index 0a69094577..304c0ce947 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,12 @@ pub fn write_slice_and_whitespace_pad(writable: &mut [u8], data: Vec) -> Res Ok(()) } +#[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..02042b8781 100644 --- a/core-primitives/utils/src/error.rs +++ b/core-primitives/utils/src/error.rs @@ -22,11 +22,8 @@ use std::boxed::Box; 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/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/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), } 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..809383c5ac 100644 --- a/enclave-runtime/src/lib.rs +++ b/enclave-runtime/src/lib.rs @@ -42,7 +42,7 @@ use crate::{ get_triggered_dispatcher_from_solo_or_parachain, utf8_str_from_raw, DecodeRaw, }, }; -use codec::{alloc::string::String, Decode}; +use codec::Decode; use itc_parentchain::block_import_dispatcher::{ triggered_dispatcher::TriggerParentchainBlockImport, DispatchBlockImport, }; @@ -59,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; @@ -85,6 +91,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("BASE_PATH not initialized. Broken enclave init flow!".to_string().into()) + })?; + + Ok(base_path.clone()) +} + /// Initialize the enclave. #[no_mangle] pub unsafe extern "C" fn init( @@ -335,19 +349,22 @@ pub unsafe extern "C" fn init_parentchain_components( 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::< - WorkerModeProvider, - >(encoded_params.to_vec()) - { - Ok(h) => h, - Err(e) => return e.into(), - }; + match init_parentchain_params_internal(encoded_params.to_vec(), latest_header_slice) { + Ok(()) => sgx_status_t::SGX_SUCCESS, + Err(e) => e.into(), + } +} - if let Err(e) = write_slice_and_whitespace_pad(latest_header_slice, encoded_latest_header) { - return Error::Other(Box::new(e)).into() - }; +/// 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; - sgx_status_t::SGX_SUCCESS + let encoded_latest_header = + init_parentchain_components::(get_base_path()?, params)?; + + write_slice_and_whitespace_pad(latest_header, encoded_latest_header)?; + + Ok(()) } #[no_mangle]