Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add base path to light-client initialization #1330

Merged
merged 6 commits into from
May 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions core-primitives/utils/src/buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u8>) -> Result<()> {
pub fn write_slice_and_whitespace_pad(
writable: &mut [u8],
data: Vec<u8>,
) -> 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);
Expand All @@ -34,6 +39,12 @@ pub fn write_slice_and_whitespace_pad(writable: &mut [u8], data: Vec<u8>) -> 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::*;
Expand Down
3 changes: 0 additions & 3 deletions core-primitives/utils/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,8 @@ use std::boxed::Box;

pub type Result<T> = core::result::Result<T, Error>;

/// extrinsics factory error
#[derive(Debug, thiserror::Error)]
pub enum Error {
Copy link
Contributor Author

@clangenb clangenb May 30, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This aggregated error does not make sense IMO because the enum variants do actually not really share anything. Regardless, I only extracted the error that we support now as an explicit variant in the enclave-runtime to not change too many unrelated things.

#[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}")]
Expand Down
6 changes: 3 additions & 3 deletions core/parentchain/light-client/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ pub struct LightClientStateSeal<B, LightClientState> {
}

impl<B, L> LightClientStateSeal<B, L> {
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() }
}
}

Expand Down Expand Up @@ -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::<TestBlock, OnchainMock, _>(
parachain_params.clone(),
Expand Down
1 change: 1 addition & 0 deletions enclave-runtime/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<dyn std::error::Error>),
}

Expand Down
7 changes: 4 additions & 3 deletions enclave-runtime/src/initialization/parentchain/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<WorkerModeProvider: ProvideWorkerMode>(
base_path: PathBuf,
encoded_params: Vec<u8>,
) -> Result<Vec<u8>> {
match ParentchainInitParams::decode(&mut encoded_params.as_slice())? {
ParentchainInitParams::Parachain { params } =>
FullParachainHandler::init::<WorkerModeProvider>(params),
FullParachainHandler::init::<WorkerModeProvider>(base_path, params),
ParentchainInitParams::Solochain { params } =>
FullSolochainHandler::init::<WorkerModeProvider>(params),
FullSolochainHandler::init::<WorkerModeProvider>(base_path, params),
}
}
9 changes: 6 additions & 3 deletions enclave-runtime/src/initialization/parentchain/parachain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand All @@ -53,14 +53,17 @@ pub struct FullParachainHandler {
}

impl FullParachainHandler {
pub fn init<WorkerModeProvider: ProvideWorkerMode>(params: ParachainParams) -> Result<Vec<u8>> {
pub fn init<WorkerModeProvider: ProvideWorkerMode>(
base_path: PathBuf,
params: ParachainParams,
) -> Result<Vec<u8>> {
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,
Expand Down
9 changes: 6 additions & 3 deletions enclave-runtime/src/initialization/parentchain/solochain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand All @@ -52,14 +52,17 @@ pub struct FullSolochainHandler {
}

impl FullSolochainHandler {
pub fn init<WorkerModeProvider: ProvideWorkerMode>(params: SolochainParams) -> Result<Vec<u8>> {
pub fn init<WorkerModeProvider: ProvideWorkerMode>(
base_path: PathBuf,
params: SolochainParams,
) -> Result<Vec<u8>> {
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,
Expand Down
43 changes: 30 additions & 13 deletions enclave-runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ use crate::{
get_triggered_dispatcher_from_solo_or_parachain, utf8_str_from_raw, DecodeRaw,
},
};
use codec::{alloc::string::String, Decode};
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

moved to the rest in the std imports

use codec::Decode;
use itc_parentchain::block_import_dispatcher::{
triggered_dispatcher::TriggerParentchainBlockImport, DispatchBlockImport,
};
Expand All @@ -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;
Expand All @@ -85,6 +91,14 @@ pub type AuthorityPair = sp_core::ed25519::Pair;

static BASE_PATH: OnceCell<PathBuf> = OnceCell::new();

fn get_base_path() -> Result<PathBuf> {
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(
Expand Down Expand Up @@ -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<u8>, latest_header: &mut [u8]) -> Result<()> {
use initialization::parentchain::init_parentchain_components;

sgx_status_t::SGX_SUCCESS
let encoded_latest_header =
init_parentchain_components::<WorkerModeProvider>(get_base_path()?, params)?;

write_slice_and_whitespace_pad(latest_header, encoded_latest_header)?;

Ok(())
}

#[no_mangle]
Expand Down