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

move sidechain_importBlock rpc method to trusted rpc #1605

Merged
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
1 change: 1 addition & 0 deletions Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3837,6 +3837,7 @@ dependencies = [
name = "its-rpc-handler"
version = "0.9.0"
dependencies = [
"itp-import-queue",
"itp-rpc",
"itp-stf-primitives",
"itp-top-pool-author",
Expand Down
9 changes: 0 additions & 9 deletions core-primitives/enclave-api/ffi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,15 +224,6 @@ extern "C" {

pub fn test_main_entrance(eid: sgx_enclave_id_t, retval: *mut sgx_status_t) -> sgx_status_t;

pub fn call_rpc_methods(
eid: sgx_enclave_id_t,
retval: *mut sgx_status_t,
request: *const u8,
request_len: u32,
response: *mut u8,
response_len: u32,
) -> sgx_status_t;

pub fn update_market_data_xt(
eid: sgx_enclave_id_t,
retval: *mut sgx_status_t,
Expand Down
58 changes: 0 additions & 58 deletions core-primitives/enclave-api/src/direct_request.rs

This file was deleted.

1 change: 0 additions & 1 deletion core-primitives/enclave-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@

use crate::error::Error;

pub mod direct_request;
pub mod enclave_base;
pub mod enclave_test;
pub mod error;
Expand Down
10 changes: 10 additions & 0 deletions core/rpc-client/src/direct_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ pub trait DirectApi {
fn get_mu_ra_url(&self) -> Result<String>;
fn get_untrusted_worker_url(&self) -> Result<String>;
fn get_state_metadata(&self) -> Result<Metadata>;
fn import_sidechain_blocks(&self, blocks_encoded: String) -> Result<()>;

fn send(&self, request: &str) -> Result<()>;
/// Close any open websocket connection.
Expand Down Expand Up @@ -155,6 +156,15 @@ impl DirectApi for DirectClient {
Metadata::try_from(metadata).map_err(|e| e.into())
}

fn import_sidechain_blocks(&self, sidechain_blocks_encoded: String) -> Result<()> {
let jsonrpc_call: String = RpcRequest::compose_jsonrpc_call(
"sidechain_importBlock".to_owned(),
vec![sidechain_blocks_encoded],
)?;
self.get(&jsonrpc_call)?;
Ok(())
}

fn send(&self, request: &str) -> Result<()> {
self.web_socket_control.send(request)
}
Expand Down
4 changes: 4 additions & 0 deletions core/rpc-client/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,10 @@ impl DirectApi for DirectClientMock {
Metadata::try_from(metadata).map_err(|e| e.into())
}

fn import_sidechain_blocks(&self, _blocks_encoded: String) -> Result<()> {
Ok(())
}

fn send(&self, _request: &str) -> Result<()> {
unimplemented!()
}
Expand Down
39 changes: 3 additions & 36 deletions core/rpc-server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,10 @@

*/

use itp_enclave_api::direct_request::DirectRequest;
use itp_rpc::RpcRequest;
use itp_utils::ToHexPrefixed;
use its_peer_fetch::block_fetch_server::BlockFetchServerModuleBuilder;
use its_primitives::types::block::SignedBlock;
use its_rpc_handler::constants::RPC_METHOD_NAME_IMPORT_BLOCKS;
use its_storage::interface::FetchBlocks;
use jsonrpsee::{
types::error::CallError,
ws_server::{RpcModule, WsServerBuilder},
};
use log::debug;
use jsonrpsee::{types::error::CallError, ws_server::WsServerBuilder};
use std::{net::SocketAddr, sync::Arc};
use tokio::net::ToSocketAddrs;

Expand All @@ -35,37 +27,15 @@ mod mock;
#[cfg(test)]
mod tests;

pub async fn run_server<Enclave, FetchSidechainBlocks>(
pub async fn run_server<FetchSidechainBlocks>(
addr: impl ToSocketAddrs,
enclave: Arc<Enclave>,
sidechain_block_fetcher: Arc<FetchSidechainBlocks>,
) -> anyhow::Result<SocketAddr>
where
Enclave: DirectRequest,
FetchSidechainBlocks: FetchBlocks<SignedBlock> + Send + Sync + 'static,
{
let mut server = WsServerBuilder::default().build(addr).await?;

// FIXME: import block should be moved to trusted side.
let mut import_sidechain_block_module = RpcModule::new(enclave);
import_sidechain_block_module.register_method(
RPC_METHOD_NAME_IMPORT_BLOCKS,
|params, enclave| {
debug!("{} params: {:?}", RPC_METHOD_NAME_IMPORT_BLOCKS, params);

let enclave_req = RpcRequest::compose_jsonrpc_call(
RPC_METHOD_NAME_IMPORT_BLOCKS.into(),
vec![params.one::<Vec<SignedBlock>>()?.to_hex()],
)
.unwrap();

enclave
.rpc(enclave_req.as_bytes().to_vec())
.map_err(|e| CallError::Failed(e.into()))
},
)?;
server.register_module(import_sidechain_block_module).unwrap();

let fetch_sidechain_blocks_module = BlockFetchServerModuleBuilder::new(sidechain_block_fetcher)
.build()
.map_err(|e| CallError::Failed(e.to_string().into()))?; // `to_string` necessary due to no all errors implementing Send + Sync.
Comment on lines 39 to 41
Copy link
Contributor

Choose a reason for hiding this comment

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

hmmm, I guess the sidechain block fetcher should also be on the trusted side eventually.

Expand All @@ -74,10 +44,7 @@ where
let socket_addr = server.local_addr()?;
tokio::spawn(async move { server.start().await });

println!(
"[+] Untrusted RPC server is spawned on: {} listening to peer sidechain block broadcasts",
socket_addr
);
println!("[+] Untrusted RPC server is spawned on: {} listening ", socket_addr);

Ok(socket_addr)
}
15 changes: 0 additions & 15 deletions core/rpc-server/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,29 +15,14 @@

*/

use itp_enclave_api::{direct_request::DirectRequest, EnclaveResult};
use itp_rpc::{Id, RpcResponse};
use itp_utils::ToHexPrefixed;
use its_primitives::{
traits::ShardIdentifierFor,
types::{BlockHash, SignedBlock, SignedBlock as SignedSidechainBlock},
};
use its_storage::interface::FetchBlocks;
use parity_scale_codec::Encode;

pub struct TestEnclave;

impl DirectRequest for TestEnclave {
fn rpc(&self, _request: Vec<u8>) -> EnclaveResult<Vec<u8>> {
Ok(RpcResponse {
jsonrpc: "mock_response".into(),
result: "null".to_hex(),
id: Id::Number(1),
}
.encode())
}
}

pub struct MockSidechainBlockFetcher;

impl FetchBlocks<SignedSidechainBlock> for MockSidechainBlockFetcher {
Expand Down
20 changes: 9 additions & 11 deletions core/rpc-server/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
use super::*;
use crate::mock::MockSidechainBlockFetcher;
use itp_rpc::RpcResponse;
use its_rpc_handler::constants::RPC_METHOD_NAME_IMPORT_BLOCKS;
use its_primitives::types::{header::ShardIdentifier, BlockHash};
use its_rpc_handler::constants::RPC_METHOD_NAME_FETCH_BLOCKS_FROM_PEER;
use its_test::sidechain_block_builder::{SidechainBlockBuilder, SidechainBlockBuilderTrait};
use jsonrpsee::{
types::{to_json_value, traits::Client},
Expand All @@ -35,22 +36,19 @@ fn init() {
#[tokio::test]
async fn test_client_calls() {
init();
let addr =
run_server("127.0.0.1:0", Arc::new(TestEnclave), Arc::new(MockSidechainBlockFetcher))
.await
.unwrap();
let addr = run_server("127.0.0.1:0", Arc::new(MockSidechainBlockFetcher)).await.unwrap();
info!("ServerAddress: {:?}", addr);

let url = format!("ws://{}", addr);
let client = WsClientBuilder::default().build(&url).await.unwrap();
let param_json =
to_json_value((BlockHash::default(), Option::<()>::None, ShardIdentifier::default()))
.unwrap();
let response: Vec<u8> = client
.request(
RPC_METHOD_NAME_IMPORT_BLOCKS,
vec![to_json_value(vec![SidechainBlockBuilder::default().build_signed()]).unwrap()]
.into(),
)
.request(RPC_METHOD_NAME_FETCH_BLOCKS_FROM_PEER, vec![param_json].into())
.await
.unwrap();

assert!(RpcResponse::decode(&mut response.as_slice()).is_ok());
//received no blocks from server
assert!(response.is_empty());
}
2 changes: 2 additions & 0 deletions enclave-runtime/Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -822,6 +822,7 @@ dependencies = [
"itp-utils",
"its-block-verification",
"its-primitives",
"its-rpc-handler",
"its-sidechain",
"jsonrpc-core",
"lazy_static",
Expand Down Expand Up @@ -2512,6 +2513,7 @@ dependencies = [
name = "its-rpc-handler"
version = "0.9.0"
dependencies = [
"itp-import-queue",
"itp-rpc",
"itp-stf-primitives",
"itp-top-pool-author",
Expand Down
1 change: 1 addition & 0 deletions enclave-runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ itp-types = { path = "../core-primitives/types", default-features = false }
itp-utils = { path = "../core-primitives/utils", default-features = false }
its-block-verification = { path = "../sidechain/block-verification", default-features = false }
its-primitives = { path = "../sidechain/primitives", default-features = false }
its-rpc-handler = { path = "../sidechain/rpc-handler", default-features = false, features = ["sgx"] }
its-sidechain = { path = "../sidechain/sidechain-crate", default-features = false, features = ["sgx"] }

# substrate deps
Expand Down
5 changes: 0 additions & 5 deletions enclave-runtime/Enclave.edl
Original file line number Diff line number Diff line change
Expand Up @@ -184,11 +184,6 @@ enclave {
int skip_ra
);

public sgx_status_t call_rpc_methods(
[in, size=request_len] uint8_t* request, uint32_t request_len,
[out, size=response_len] uint8_t* response, uint32_t response_len
);

public size_t test_main_entrance();
};

Expand Down
46 changes: 28 additions & 18 deletions enclave-runtime/src/initialization/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,23 +22,23 @@ use crate::{
initialization::global_components::{
EnclaveBlockImportConfirmationHandler, EnclaveGetterExecutor, EnclaveLightClientSeal,
EnclaveOCallApi, EnclaveRpcConnectionRegistry, EnclaveRpcResponder,
EnclaveShieldingKeyRepository, EnclaveSidechainApi, EnclaveSidechainBlockImportQueue,
EnclaveSidechainBlockImportQueueWorker, EnclaveSidechainBlockImporter,
EnclaveSidechainBlockSyncer, EnclaveStateFileIo, EnclaveStateHandler,
EnclaveStateInitializer, EnclaveStateObserver, EnclaveStateSnapshotRepository,
EnclaveStfEnclaveSigner, EnclaveTopPool, EnclaveTopPoolAuthor,
GLOBAL_ATTESTATION_HANDLER_COMPONENT, GLOBAL_INTEGRITEE_PARENTCHAIN_LIGHT_CLIENT_SEAL,
GLOBAL_OCALL_API_COMPONENT, GLOBAL_RPC_WS_HANDLER_COMPONENT,
GLOBAL_SHIELDING_KEY_REPOSITORY_COMPONENT, GLOBAL_SIDECHAIN_BLOCK_COMPOSER_COMPONENT,
GLOBAL_SIDECHAIN_BLOCK_SYNCER_COMPONENT, GLOBAL_SIDECHAIN_IMPORT_QUEUE_COMPONENT,
GLOBAL_SIDECHAIN_IMPORT_QUEUE_WORKER_COMPONENT, GLOBAL_SIGNING_KEY_REPOSITORY_COMPONENT,
GLOBAL_STATE_HANDLER_COMPONENT, GLOBAL_STATE_KEY_REPOSITORY_COMPONENT,
GLOBAL_STATE_OBSERVER_COMPONENT, GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL,
EnclaveShieldingKeyRepository, EnclaveSidechainApi, EnclaveSidechainBlockImportQueueWorker,
EnclaveSidechainBlockImporter, EnclaveSidechainBlockSyncer, EnclaveStateFileIo,
EnclaveStateHandler, EnclaveStateInitializer, EnclaveStateObserver,
EnclaveStateSnapshotRepository, EnclaveStfEnclaveSigner, EnclaveTopPool,
EnclaveTopPoolAuthor, GLOBAL_ATTESTATION_HANDLER_COMPONENT,
GLOBAL_INTEGRITEE_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_OCALL_API_COMPONENT,
GLOBAL_RPC_WS_HANDLER_COMPONENT, GLOBAL_SHIELDING_KEY_REPOSITORY_COMPONENT,
GLOBAL_SIDECHAIN_BLOCK_COMPOSER_COMPONENT, GLOBAL_SIDECHAIN_BLOCK_SYNCER_COMPONENT,
GLOBAL_SIDECHAIN_IMPORT_QUEUE_COMPONENT, GLOBAL_SIDECHAIN_IMPORT_QUEUE_WORKER_COMPONENT,
GLOBAL_SIGNING_KEY_REPOSITORY_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT,
GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, GLOBAL_STATE_OBSERVER_COMPONENT,
GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL,
GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TOP_POOL_AUTHOR_COMPONENT,
GLOBAL_WEB_SOCKET_SERVER_COMPONENT,
},
ocall::OcallApi,
rpc::{rpc_response_channel::RpcResponseChannel, worker_api_direct::public_api_rpc_handler},
rpc::{common_api::add_common_api, rpc_response_channel::RpcResponseChannel},
utils::{
get_extrinsic_factory_from_integritee_solo_or_parachain,
get_node_metadata_repository_from_integritee_solo_or_parachain,
Expand Down Expand Up @@ -77,6 +77,7 @@ use itp_top_pool::pool::Options as PoolOptions;
use itp_top_pool_author::author::AuthorTopFilter;
use itp_types::{parentchain::ParentchainId, ShardIdentifier};
use its_sidechain::block_composer::BlockComposer;
use jsonrpc_core::IoHandler;
use log::*;
use sp_core::crypto::Pair;
use std::{collections::HashMap, path::PathBuf, string::String, sync::Arc};
Expand Down Expand Up @@ -175,14 +176,23 @@ pub(crate) fn init_enclave(
GLOBAL_TOP_POOL_AUTHOR_COMPONENT.initialize(top_pool_author.clone());

let getter_executor = Arc::new(EnclaveGetterExecutor::new(state_observer));
let io_handler =
public_api_rpc_handler(top_pool_author, getter_executor, shielding_key_repository);

let mut io_handler = IoHandler::new();
add_common_api(&mut io_handler, top_pool_author, getter_executor, shielding_key_repository);

#[cfg(feature = "sidechain")]
{
use crate::initialization::global_components::EnclaveSidechainBlockImportQueue;
use its_rpc_handler::add_sidechain_api;
let sidechain_block_import_queue = Arc::new(EnclaveSidechainBlockImportQueue::default());
GLOBAL_SIDECHAIN_IMPORT_QUEUE_COMPONENT.initialize(sidechain_block_import_queue);
let sidechain_import_queue = GLOBAL_SIDECHAIN_IMPORT_QUEUE_COMPONENT.get()?;
add_sidechain_api(&mut io_handler, sidechain_import_queue);
}

let rpc_handler = Arc::new(RpcWsHandler::new(io_handler, watch_extractor, connection_registry));
GLOBAL_RPC_WS_HANDLER_COMPONENT.initialize(rpc_handler);

let sidechain_block_import_queue = Arc::new(EnclaveSidechainBlockImportQueue::default());
GLOBAL_SIDECHAIN_IMPORT_QUEUE_COMPONENT.initialize(sidechain_block_import_queue);

let attestation_handler =
Arc::new(IntelAttestationHandler::new(ocall_api, signing_key_repository));
GLOBAL_ATTESTATION_HANDLER_COMPONENT.initialize(attestation_handler);
Expand Down
Loading
Loading