diff --git a/core-primitives/node-api/api-client-extensions/src/chain.rs b/core-primitives/node-api/api-client-extensions/src/chain.rs index 10d1ad9d14..39b9b785e6 100644 --- a/core-primitives/node-api/api-client-extensions/src/chain.rs +++ b/core-primitives/node-api/api-client-extensions/src/chain.rs @@ -16,7 +16,7 @@ */ use crate::ApiResult; -use itp_types::SignedBlock; +use itp_types::{Header, SignedBlock}; use sp_core::{storage::StorageKey, Pair, H256}; use sp_finality_grandpa::{AuthorityList, VersionedAuthorityList, GRANDPA_AUTHORITIES_KEY}; use sp_runtime::MultiSignature; @@ -28,7 +28,8 @@ pub type StorageProof = Vec>; pub trait ChainApi { fn last_finalized_block(&self) -> ApiResult>; fn signed_block(&self, hash: Option) -> ApiResult>; - + fn get_genesis_hash(&self) -> ApiResult; + fn get_header(&self, header_hash: Option) -> ApiResult>; /// Fetch blocks from parentchain with blocknumber from until to, including both boundaries. /// Returns a vector with one element if from equals to. /// Returns an empty vector if from is greater than to. @@ -54,6 +55,14 @@ where self.get_signed_block(hash) } + fn get_genesis_hash(&self) -> ApiResult { + self.get_genesis_hash() + } + + fn get_header(&self, header_hash: Option) -> ApiResult> { + self.get_header(header_hash) + } + fn get_blocks(&self, from: u32, to: u32) -> ApiResult> { let mut blocks = Vec::::new(); diff --git a/service/src/error.rs b/service/src/error.rs index fb00517f9d..8dea96c1d1 100644 --- a/service/src/error.rs +++ b/service/src/error.rs @@ -44,6 +44,12 @@ pub enum Error { NoPeerWorkerFound, #[error("No worker for shard {0} found on parentchain")] NoWorkerForShardFound(ShardIdentifier), - #[error("Custom Error: {0}")] + #[error("Returned empty parentchain block vec after sync, even though there have been blocks given as input")] + EmptyChunk, + #[error("Could not find genesis header of the parentchain")] + MissingGenesisHeader, + #[error("Could not find last finalized block of the parentchain")] + MissingLastFinalizedBlock, + #[error("{0}")] Custom(Box), } diff --git a/service/src/main.rs b/service/src/main.rs index 4702e0d288..5757a930d5 100644 --- a/service/src/main.rs +++ b/service/src/main.rs @@ -30,7 +30,7 @@ use crate::{ ocall_bridge::{ bridge_api::Bridge as OCallBridge, component_factory::OCallBridgeComponentFactory, }, - parentchain_block_syncer::{ParentchainBlockSyncer, SyncParentchainBlocks}, + parentchain_handler::{HandleParentchain, ParentchainHandler}, prometheus_metrics::{start_metrics_server, EnclaveMetricsReceiver, MetricsHandler}, sidechain_setup::{sidechain_init_block_production, sidechain_start_untrusted_rpc_server}, sync_block_broadcaster::SyncBlockBroadcaster, @@ -46,7 +46,6 @@ use enclave::{ api::enclave_init, tls_ra::{enclave_request_state_provisioning, enclave_run_state_provisioning_server}, }; -use itc_parentchain_light_client::light_client_init_params::LightClientInitParams; use itp_enclave_api::{ direct_request::DirectRequest, enclave_base::EnclaveBase, @@ -56,7 +55,7 @@ use itp_enclave_api::{ Enclave, }; use itp_node_api::{ - api_client::{AccountApi, ChainApi, PalletTeerexApi, ParentchainApi}, + api_client::{AccountApi, PalletTeerexApi, ParentchainApi}, metadata::NodeMetadata, node_api_factory::{CreateNodeApi, NodeApiFactory}, }; @@ -73,7 +72,6 @@ use log::*; use my_node_runtime::{Event, Hash, Header}; use sgx_types::*; use sp_core::crypto::{AccountId32, Ss58Codec}; -use sp_finality_grandpa::VersionedAuthorityList; use sp_keyring::AccountKeyring; use std::{ path::PathBuf, @@ -95,20 +93,19 @@ mod error; mod globals; mod initialized_service; mod ocall_bridge; -mod parentchain_block_syncer; +mod parentchain_handler; mod prometheus_metrics; mod setup; mod sidechain_setup; mod sync_block_broadcaster; mod sync_state; +#[cfg(feature = "teeracle")] +mod teeracle; mod tests; mod utils; mod worker; mod worker_peers_updater; -#[cfg(feature = "teeracle")] -mod teeracle; - const VERSION: &str = env!("CARGO_PKG_VERSION"); pub type EnclaveWorker = @@ -286,7 +283,7 @@ fn start_worker( InitializationHandler: TrackInitialization + IsInitialized + Sync + Send + 'static, WorkerModeProvider: ProvideWorkerMode, { - println!("IntegriTEE Worker v{}", VERSION); + println!("Integritee Worker v{}", VERSION); info!("starting worker on shard {}", shard.encode().to_base58()); // ------------------------------------------------------------------------ // check for required files @@ -388,7 +385,8 @@ fn start_worker( // ------------------------------------------------------------------------ // Init parentchain specific stuff. Needed for parentchain communication. - let last_synced_header = init_parentchain_components(&node_api, enclave.clone()).unwrap(); + let parentchain_handler = Arc::new(ParentchainHandler::new(node_api.clone(), enclave.clone())); + let last_synced_header = parentchain_handler.init_parentchain_components().unwrap(); let nonce = node_api.get_nonce_of(&tee_accountid).unwrap(); info!("Enclave nonce = {:?}", nonce); enclave @@ -462,35 +460,31 @@ fn start_worker( println!("*** [+] Finished syncing light client, syncing parentchain..."); // Syncing all parentchain blocks, this might take a while.. - let parentchain_block_syncer = - Arc::new(ParentchainBlockSyncer::new(node_api.clone(), enclave.clone())); - let mut last_synced_header = parentchain_block_syncer.sync_parentchain(last_synced_header); + let mut last_synced_header = + parentchain_handler.sync_parentchain(last_synced_header).unwrap(); // ------------------------------------------------------------------------ // Initialize the sidechain if WorkerModeProvider::worker_mode() == WorkerMode::Sidechain { last_synced_header = sidechain_init_block_production( - enclave.clone(), + enclave, ®ister_enclave_xt_header, we_are_primary_validateer, - parentchain_block_syncer, + parentchain_handler.clone(), sidechain_storage, &last_synced_header, - ); + ) + .unwrap(); } // ------------------------------------------------------------------------ // start parentchain syncing loop (subscribe to header updates) - let api4 = node_api.clone(); - let enclave_parentchain_sync = enclave; thread::Builder::new() .name("parentchain_sync_loop".to_owned()) .spawn(move || { - if let Err(e) = subscribe_to_parentchain_new_headers( - enclave_parentchain_sync, - &api4, - last_synced_header, - ) { + if let Err(e) = + subscribe_to_parentchain_new_headers(parentchain_handler, last_synced_header) + { error!("Parentchain block syncing terminated with a failure: {:?}", e); } println!("[!] Parentchain block syncing has terminated"); @@ -687,46 +681,20 @@ fn print_events(events: Events, _sender: Sender) { } } -pub fn init_parentchain_components( - api: &ParentchainApi, - enclave_api: Arc, -) -> Result { - let genesis_hash = api.get_genesis_hash().unwrap(); - let genesis_header: Header = api.get_header(Some(genesis_hash)).unwrap().unwrap(); - info!("Got genesis Header: \n {:?} \n", genesis_header); - if api.is_grandpa_available()? { - let grandpas = api.grandpa_authorities(Some(genesis_hash)).unwrap(); - let grandpa_proof = api.grandpa_authorities_proof(Some(genesis_hash)).unwrap(); - - debug!("Grandpa Authority List: \n {:?} \n ", grandpas); - - let authority_list = VersionedAuthorityList::from(grandpas); - - let params = LightClientInitParams::Grandpa { - genesis_header, - authorities: authority_list.into(), - authority_proof: grandpa_proof, - }; - - Ok(enclave_api.init_parentchain_components(params).unwrap()) - } else { - let params = LightClientInitParams::Parachain { genesis_header }; - - Ok(enclave_api.init_parentchain_components(params).unwrap()) - } -} - /// Subscribe to the node API finalized heads stream and trigger a parent chain sync /// upon receiving a new header. fn subscribe_to_parentchain_new_headers( - enclave_api: Arc, - api: &ParentchainApi, + parentchain_handler: Arc>, mut last_synced_header: Header, ) -> Result<(), Error> { let (sender, receiver) = channel(); - api.subscribe_finalized_heads(sender).map_err(Error::ApiClient)?; + //TODO: this should be implemented by parentchain_handler directly, and not via + // exposed parentchain_api. Blocked by https://github.com/scs/substrate-api-client/issues/267. + parentchain_handler + .parentchain_api() + .subscribe_finalized_heads(sender) + .map_err(Error::ApiClient)?; - let parentchain_block_syncer = ParentchainBlockSyncer::new(api.clone(), enclave_api); loop { let new_header: Header = match receiver.recv() { Ok(header_str) => serde_json::from_str(&header_str).map_err(Error::Serialization), @@ -738,7 +706,7 @@ fn subscribe_to_parentchain_new_headers( new_header.number ); - last_synced_header = parentchain_block_syncer.sync_parentchain(last_synced_header); + last_synced_header = parentchain_handler.sync_parentchain(last_synced_header)?; } } diff --git a/service/src/parentchain_block_syncer.rs b/service/src/parentchain_block_syncer.rs deleted file mode 100644 index 30d8e548a5..0000000000 --- a/service/src/parentchain_block_syncer.rs +++ /dev/null @@ -1,114 +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::error::Error; -use itp_enclave_api::{enclave_base::EnclaveBase, sidechain::Sidechain}; -use itp_node_api::api_client::ChainApi; -use itp_types::SignedBlock; -use log::*; -use my_node_runtime::Header; -use sp_runtime::traits::Header as HeaderTrait; -use std::{cmp::min, sync::Arc}; - -const BLOCK_SYNC_BATCH_SIZE: u32 = 1000; - -pub trait SyncParentchainBlocks { - /// Fetches the parentchainblocks to sync from the parentchain and feeds them to the enclave. - /// Returns the latest synced block Header. - fn sync_parentchain(&self, last_synced_header: Header) -> Header; -} -/// Supplies functionality to sync parentchain blocks. -pub(crate) struct ParentchainBlockSyncer { - parentchain_api: ParentchainApi, - enclave_api: Arc, -} - -impl ParentchainBlockSyncer -where - ParentchainApi: ChainApi, - EnclaveApi: Sidechain, -{ - pub fn new(parentchain_api: ParentchainApi, enclave_api: Arc) -> Self { - ParentchainBlockSyncer { parentchain_api, enclave_api } - } -} - -impl SyncParentchainBlocks - for ParentchainBlockSyncer -where - ParentchainApi: ChainApi, - EnclaveApi: Sidechain, -{ - fn sync_parentchain(&self, last_synced_header: Header) -> Header { - trace!("Getting current head"); - let curr_block: SignedBlock = self.parentchain_api.last_finalized_block().unwrap().unwrap(); - let curr_block_number = curr_block.block.header.number; - - let mut until_synced_header = last_synced_header; - loop { - let block_chunk_to_sync = self - .parentchain_api - .get_blocks( - until_synced_header.number + 1, - min(until_synced_header.number + BLOCK_SYNC_BATCH_SIZE, curr_block_number), - ) - .unwrap(); - println!("[+] Found {} block(s) to sync", block_chunk_to_sync.len()); - if block_chunk_to_sync.is_empty() { - return until_synced_header - } - - if let Err(e) = self.enclave_api.sync_parentchain(block_chunk_to_sync.as_slice(), 0) { - error!("{:?}", e); - // enclave might not have synced - return until_synced_header - }; - until_synced_header = block_chunk_to_sync - .last() - .map(|b| b.block.header.clone()) - .expect("Chunk can't be empty; qed"); - println!( - "Synced {} out of {} finalized parentchain blocks", - until_synced_header.number, curr_block_number, - ) - } - } -} - -/// Ensure we're synced up until the parentchain block where we have registered ourselves. -pub(crate) fn import_parentchain_blocks_until_self_registry< - E: EnclaveBase + Sidechain, - ParentchainSyncer: SyncParentchainBlocks, ->( - enclave_api: Arc, - parentchain_block_syncer: Arc, - last_synced_header: &Header, - register_enclave_xt_header: &Header, -) -> Result { - info!( - "We're the first validateer to be registered, syncing parentchain blocks until the one we have registered ourselves on." - ); - let mut last_synced_header = last_synced_header.clone(); - - while last_synced_header.number() < register_enclave_xt_header.number() { - last_synced_header = parentchain_block_syncer.sync_parentchain(last_synced_header); - } - enclave_api.trigger_parentchain_block_import()?; - - Ok(last_synced_header) -} diff --git a/service/src/parentchain_handler.rs b/service/src/parentchain_handler.rs new file mode 100644 index 0000000000..3e61ee6396 --- /dev/null +++ b/service/src/parentchain_handler.rs @@ -0,0 +1,159 @@ +/* + 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::error::{Error, ServiceResult}; +use itc_parentchain_light_client::light_client_init_params::LightClientInitParams; +use itp_enclave_api::{enclave_base::EnclaveBase, sidechain::Sidechain}; +use itp_node_api::api_client::ChainApi; +use itp_types::SignedBlock; +use log::*; +use my_node_runtime::Header; +use sp_finality_grandpa::VersionedAuthorityList; +use sp_runtime::traits::Header as HeaderTrait; +use std::{cmp::min, sync::Arc}; + +const BLOCK_SYNC_BATCH_SIZE: u32 = 1000; + +pub trait HandleParentchain { + /// Initializes all parentchain specific components on the enclave side. + /// Returns the latest synced block header. + fn init_parentchain_components(&self) -> ServiceResult
; + + /// Fetches the parentchain blocks to sync from the parentchain and feeds them to the enclave. + /// Returns the latest synced block header. + fn sync_parentchain(&self, last_synced_header: Header) -> ServiceResult
; + + /// Triggers the import of the synced parentchain blocks inside the enclave. + fn trigger_parentchain_block_import(&self) -> ServiceResult<()>; + + /// Syncs and directly imports parentchain blocks from the latest synced header + /// until the specified until_header. + fn sync_and_import_parentchain_until( + &self, + last_synced_header: &Header, + until_header: &Header, + ) -> ServiceResult
; +} + +/// Handles the interaction between parentchain and enclave. +pub(crate) struct ParentchainHandler { + parentchain_api: ParentchainApi, + enclave_api: Arc, +} + +impl ParentchainHandler +where + ParentchainApi: ChainApi, + EnclaveApi: Sidechain + EnclaveBase, +{ + pub fn new(parentchain_api: ParentchainApi, enclave_api: Arc) -> Self { + Self { parentchain_api, enclave_api } + } + + pub fn parentchain_api(&self) -> &ParentchainApi { + &self.parentchain_api + } +} + +impl HandleParentchain + for ParentchainHandler +where + ParentchainApi: ChainApi, + EnclaveApi: Sidechain + EnclaveBase, +{ + fn init_parentchain_components(&self) -> ServiceResult
{ + let genesis_hash = self.parentchain_api.get_genesis_hash()?; + let genesis_header: Header = self + .parentchain_api + .get_header(Some(genesis_hash))? + .ok_or(Error::MissingGenesisHeader)?; + info!("Got genesis Header: \n {:?} \n", genesis_header); + if self.parentchain_api.is_grandpa_available()? { + let grandpas = self.parentchain_api.grandpa_authorities(Some(genesis_hash))?; + let grandpa_proof = + self.parentchain_api.grandpa_authorities_proof(Some(genesis_hash))?; + + debug!("Grandpa Authority List: \n {:?} \n ", grandpas); + + let authority_list = VersionedAuthorityList::from(grandpas); + + let params = LightClientInitParams::Grandpa { + genesis_header, + authorities: authority_list.into(), + authority_proof: grandpa_proof, + }; + + Ok(self.enclave_api.init_parentchain_components(params)?) + } else { + let params = LightClientInitParams::Parachain { genesis_header }; + + Ok(self.enclave_api.init_parentchain_components(params)?) + } + } + + fn sync_parentchain(&self, last_synced_header: Header) -> ServiceResult
{ + trace!("Getting current head"); + let curr_block: SignedBlock = self + .parentchain_api + .last_finalized_block()? + .ok_or(Error::MissingLastFinalizedBlock)?; + let curr_block_number = curr_block.block.header.number; + + let mut until_synced_header = last_synced_header; + loop { + let block_chunk_to_sync = self.parentchain_api.get_blocks( + until_synced_header.number + 1, + min(until_synced_header.number + BLOCK_SYNC_BATCH_SIZE, curr_block_number), + )?; + println!("[+] Found {} block(s) to sync", block_chunk_to_sync.len()); + if block_chunk_to_sync.is_empty() { + return Ok(until_synced_header) + } + + self.enclave_api.sync_parentchain(block_chunk_to_sync.as_slice(), 0)?; + + until_synced_header = block_chunk_to_sync + .last() + .map(|b| b.block.header.clone()) + .ok_or(Error::EmptyChunk)?; + println!( + "Synced {} out of {} finalized parentchain blocks", + until_synced_header.number, curr_block_number, + ) + } + } + + fn trigger_parentchain_block_import(&self) -> ServiceResult<()> { + Ok(self.enclave_api.trigger_parentchain_block_import()?) + } + + fn sync_and_import_parentchain_until( + &self, + last_synced_header: &Header, + until_header: &Header, + ) -> ServiceResult
{ + let mut last_synced_header = last_synced_header.clone(); + + while last_synced_header.number() < until_header.number() { + last_synced_header = self.sync_parentchain(last_synced_header)?; + } + self.trigger_parentchain_block_import()?; + + Ok(last_synced_header) + } +} diff --git a/service/src/sidechain_setup.rs b/service/src/sidechain_setup.rs index 28b2c61dd1..9827cd53a2 100644 --- a/service/src/sidechain_setup.rs +++ b/service/src/sidechain_setup.rs @@ -16,14 +16,14 @@ */ use crate::{ - parentchain_block_syncer::import_parentchain_blocks_until_self_registry, Config, - ParentchainBlockSyncer, + error::{Error, ServiceResult}, + parentchain_handler::HandleParentchain, + Config, }; use futures::executor::block_on; use itp_enclave_api::{ direct_request::DirectRequest, enclave_base::EnclaveBase, sidechain::Sidechain, }; -use itp_node_api::api_client::ParentchainApi; use itp_settings::{ files::{SIDECHAIN_PURGE_INTERVAL, SIDECHAIN_PURGE_LIMIT}, sidechain::SLOT_DURATION, @@ -54,31 +54,31 @@ pub(crate) fn sidechain_start_untrusted_rpc_server( }); } -pub(crate) fn sidechain_init_block_production( +pub(crate) fn sidechain_init_block_production( enclave: Arc, register_enclave_xt_header: &Header, we_are_primary_validateer: bool, - parentchain_block_syncer: Arc>, + parentchain_handler: Arc, sidechain_storage: Arc, last_synced_header: &Header, -) -> Header +) -> ServiceResult
where Enclave: EnclaveBase + Sidechain, SidechainStorage: BlockPruner + FetchBlocks + Sync + Send + 'static, + ParentchainHandler: HandleParentchain, { // If we're the first validateer to register, also trigger parentchain block import. let mut updated_header: Option
= None; if we_are_primary_validateer { - updated_header = Some( - import_parentchain_blocks_until_self_registry( - enclave.clone(), - parentchain_block_syncer, + info!( + "We're the first validateer to be registered, syncing parentchain blocks until the one we have registered ourselves on." + ); + updated_header = + Some(parentchain_handler.sync_and_import_parentchain_until( last_synced_header, register_enclave_xt_header, - ) - .unwrap(), - ); + )?); } // ------------------------------------------------------------------------ @@ -99,7 +99,7 @@ where block_on(future); println!("[!] Sidechain block production loop has terminated"); }) - .unwrap(); + .map_err(|e| Error::Custom(Box::new(e)))?; // ------------------------------------------------------------------------ // start sidechain pruning loop @@ -112,9 +112,9 @@ where SIDECHAIN_PURGE_LIMIT, ); }) - .unwrap(); + .map_err(|e| Error::Custom(Box::new(e)))?; - updated_header.unwrap_or_else(|| last_synced_header.clone()) + Ok(updated_header.unwrap_or_else(|| last_synced_header.clone())) } /// Execute trusted operations in the enclave. diff --git a/service/src/tests/mocks/enclave_api_mock.rs b/service/src/tests/mocks/enclave_api_mock.rs index 3cbf4055a9..800f083174 100644 --- a/service/src/tests/mocks/enclave_api_mock.rs +++ b/service/src/tests/mocks/enclave_api_mock.rs @@ -15,20 +15,21 @@ */ +use frame_support::sp_runtime::traits::Block as ParentchainBlockTrait; use itc_parentchain_light_client::light_client_init_params::{ LightClientInitParams, LightClientInitParams::{Grandpa, Parachain}, }; -use itp_enclave_api::{enclave_base::EnclaveBase, EnclaveResult}; +use itp_enclave_api::{enclave_base::EnclaveBase, sidechain::Sidechain, EnclaveResult}; use itp_settings::worker::MR_ENCLAVE_SIZE; use sgx_crypto_helper::rsa3072::Rsa3072PubKey; use sp_core::ed25519; use sp_runtime::traits::Header; /// mock for EnclaveBase - use in tests -pub struct EnclaveBaseMock; +pub struct EnclaveMock; -impl EnclaveBase for EnclaveBaseMock { +impl EnclaveBase for EnclaveMock { fn init(&self, _mu_ra_url: &str, _untrusted_url: &str) -> EnclaveResult<()> { Ok(()) } @@ -79,3 +80,17 @@ impl EnclaveBase for EnclaveBaseMock { Ok([1u8; MR_ENCLAVE_SIZE]) } } + +impl Sidechain for EnclaveMock { + fn sync_parentchain( + &self, + _blocks: &[sp_runtime::generic::SignedBlock], + _nonce: u32, + ) -> EnclaveResult<()> { + Ok(()) + } + + fn execute_trusted_calls(&self) -> EnclaveResult<()> { + todo!() + } +} diff --git a/service/src/tests/mocks/mod.rs b/service/src/tests/mocks/mod.rs index 93ee3b8cf5..cfe0d6fc76 100644 --- a/service/src/tests/mocks/mod.rs +++ b/service/src/tests/mocks/mod.rs @@ -20,5 +20,4 @@ pub mod direct_request_mock; pub mod enclave_api_mock; pub mod initialization_handler_mock; pub mod parentchain_api_mock; -pub mod sidechain_api_mock; pub mod update_worker_peers_mock; diff --git a/service/src/tests/mocks/parentchain_api_mock.rs b/service/src/tests/mocks/parentchain_api_mock.rs index 9397fbf2e1..5f02df4f04 100644 --- a/service/src/tests/mocks/parentchain_api_mock.rs +++ b/service/src/tests/mocks/parentchain_api_mock.rs @@ -20,7 +20,7 @@ use itc_parentchain_test::{ parentchain_header_builder::ParentchainHeaderBuilder, }; use itp_node_api::api_client::{ApiResult, ChainApi, StorageProof}; -use itp_types::{SignedBlock, H256}; +use itp_types::{Header, SignedBlock, H256}; use sp_finality_grandpa::AuthorityList; pub struct ParentchainApiMock { @@ -53,6 +53,14 @@ impl ChainApi for ParentchainApiMock { todo!() } + fn get_genesis_hash(&self) -> ApiResult { + todo!() + } + + fn get_header(&self, _header_hash: Option) -> ApiResult> { + todo!() + } + fn get_blocks(&self, from: u32, to: u32) -> ApiResult> { let num_elements = to.checked_sub(from).map(|n| n + 1).unwrap_or(0); let blocks = self diff --git a/service/src/tests/mocks/sidechain_api_mock.rs b/service/src/tests/mocks/sidechain_api_mock.rs deleted file mode 100644 index 0697abc957..0000000000 --- a/service/src/tests/mocks/sidechain_api_mock.rs +++ /dev/null @@ -1,36 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - 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 frame_support::sp_runtime::traits::Block as ParentchainBlockTrait; -use itp_enclave_api::{sidechain::Sidechain, EnclaveResult}; - -/// Mock for Parentchain Api -pub struct SidechainApiMock; - -impl Sidechain for SidechainApiMock { - fn sync_parentchain( - &self, - _blocks: &[sp_runtime::generic::SignedBlock], - _nonce: u32, - ) -> EnclaveResult<()> { - Ok(()) - } - - fn execute_trusted_calls(&self) -> EnclaveResult<()> { - todo!() - } -} diff --git a/service/src/tests/mod.rs b/service/src/tests/mod.rs index e8f9aa6fdb..72cc066bb6 100644 --- a/service/src/tests/mod.rs +++ b/service/src/tests/mod.rs @@ -26,7 +26,7 @@ pub mod mock; pub mod mocks; #[cfg(test)] -pub mod parentchain_block_syncer_test; +pub mod parentchain_handler_test; pub fn run_enclave_tests(matches: &ArgMatches) { println!("*** Starting Test enclave"); diff --git a/service/src/tests/parentchain_block_syncer_test.rs b/service/src/tests/parentchain_handler_test.rs similarity index 70% rename from service/src/tests/parentchain_block_syncer_test.rs rename to service/src/tests/parentchain_handler_test.rs index 07fba28335..bd15943b47 100644 --- a/service/src/tests/parentchain_block_syncer_test.rs +++ b/service/src/tests/parentchain_handler_test.rs @@ -16,10 +16,8 @@ */ use crate::{ - parentchain_block_syncer::{ParentchainBlockSyncer, SyncParentchainBlocks}, - tests::mocks::{ - parentchain_api_mock::ParentchainApiMock, sidechain_api_mock::SidechainApiMock, - }, + parentchain_handler::{HandleParentchain, ParentchainHandler}, + tests::mocks::{enclave_api_mock::EnclaveMock, parentchain_api_mock::ParentchainApiMock}, }; use itp_node_api::api_client::ChainApi; use std::sync::Arc; @@ -32,11 +30,11 @@ fn test_number_of_synced_blocks() { let last_synced_block = parentchain_api_mock.get_blocks(2, 2).unwrap().first().cloned().unwrap(); - let enclave_api_mock = SidechainApiMock; + let enclave_api_mock = EnclaveMock; - let parentchain_block_syncer = - ParentchainBlockSyncer::new(parentchain_api_mock, Arc::new(enclave_api_mock)); + let parentchain_handler = + ParentchainHandler::new(parentchain_api_mock, Arc::new(enclave_api_mock)); - let header = parentchain_block_syncer.sync_parentchain(last_synced_block.block.header); + let header = parentchain_handler.sync_parentchain(last_synced_block.block.header).unwrap(); assert_eq!(header.number, number_of_blocks); }