From ff2d13b4d9314cd5ca45ec76e7e840f17fe86c8c Mon Sep 17 00:00:00 2001 From: Alain Brenzikofer Date: Thu, 14 Nov 2024 11:21:58 +0100 Subject: [PATCH 01/23] trying to use a supertrait to make ParentchainApi generic --- Cargo.lock | 1 + app-libs/parentchain-interface/Cargo.toml | 6 +- .../src/event_subscriber.rs | 10 +- .../src/integritee/api_client_types.rs | 95 +++++++++++++++ .../src/integritee/api_factory.rs | 45 +++++++ .../src/integritee/mod.rs | 3 + app-libs/parentchain-interface/src/lib.rs | 26 ++++ .../src/target_a/api_client_types.rs | 91 ++++++++++++++ .../src/target_a/api_factory.rs | 45 +++++++ .../parentchain-interface/src/target_a/mod.rs | 4 + .../src/target_b/api_client_types.rs | 91 ++++++++++++++ .../src/target_b/api_factory.rs | 45 +++++++ .../parentchain-interface/src/target_b/mod.rs | 20 +++- .../api-client-extensions/src/account.rs | 10 +- core-primitives/node-api/factory/src/lib.rs | 4 +- enclave-runtime/Cargo.lock | 2 + service/src/account_funding.rs | 104 ++++++++++------ service/src/main_impl.rs | 112 ++++++++++-------- service/src/ocall_bridge/component_factory.rs | 5 +- .../src/ocall_bridge/worker_on_chain_ocall.rs | 29 +++-- service/src/parentchain_handler.rs | 10 +- service/src/prometheus_metrics.rs | 14 ++- service/src/worker.rs | 28 +++-- .../peer-fetch/src/untrusted_peer_fetch.rs | 19 +-- 24 files changed, 676 insertions(+), 143 deletions(-) create mode 100644 app-libs/parentchain-interface/src/integritee/api_client_types.rs create mode 100644 app-libs/parentchain-interface/src/integritee/api_factory.rs create mode 100644 app-libs/parentchain-interface/src/target_a/api_client_types.rs create mode 100644 app-libs/parentchain-interface/src/target_a/api_factory.rs create mode 100644 app-libs/parentchain-interface/src/target_b/api_client_types.rs create mode 100644 app-libs/parentchain-interface/src/target_b/api_factory.rs diff --git a/Cargo.lock b/Cargo.lock index 01ec42e55c..3640de9f8d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2793,6 +2793,7 @@ dependencies = [ "sgx_tstd", "sp-core", "sp-runtime", + "sp-version", "substrate-api-client", ] diff --git a/app-libs/parentchain-interface/Cargo.toml b/app-libs/parentchain-interface/Cargo.toml index 547db7dbf8..2ac630a82a 100644 --- a/app-libs/parentchain-interface/Cargo.toml +++ b/app-libs/parentchain-interface/Cargo.toml @@ -25,11 +25,12 @@ codec = { package = "parity-scale-codec", version = "3.0.0", default-features = log = { version = "0.4", default-features = false } regex = { optional = true, version = "1.9.5" } -substrate-api-client = { optional = true, default-features = false, features = ["std", "sync-api"], git = "https://github.com/encointer/substrate-api-client.git", branch = "v0.9.42-tag-v0.14.0-retracted-check-metadata-hash" } +substrate-api-client = { default-features = false, git = "https://github.com/encointer/substrate-api-client.git", branch = "v0.9.42-tag-v0.14.0-retracted-check-metadata-hash" } # substrate dep sp-core = { default-features = false, features = ["full_crypto"], git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } +sp-version = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } [dev-dependencies] env_logger = "0.9.0" @@ -62,7 +63,8 @@ std = [ "regex", "sp-core/std", "sp-runtime/std", - "substrate-api-client", + "substrate-api-client/std", + "substrate-api-client/sync-api", ] sgx = [ "sgx_tstd", diff --git a/app-libs/parentchain-interface/src/event_subscriber.rs b/app-libs/parentchain-interface/src/event_subscriber.rs index de5765340f..9732c1996a 100644 --- a/app-libs/parentchain-interface/src/event_subscriber.rs +++ b/app-libs/parentchain-interface/src/event_subscriber.rs @@ -18,12 +18,18 @@ extern crate alloc; use alloc::sync::Arc; use core::sync::atomic::{AtomicBool, Ordering}; use itp_api_client_types::ParentchainApi; -use itp_types::parentchain::{AddedSgxEnclave, BalanceTransfer, ExtrinsicFailed, ParentchainId}; +use itp_node_api::api_client::AccountApi; +use itp_types::parentchain::{ + AddedSgxEnclave, BalanceTransfer, ExtrinsicFailed, Hash, ParentchainId, +}; use log::warn; +use sp_core::crypto::AccountId32; use sp_runtime::DispatchError; use substrate_api_client::SubscribeEvents; -pub fn subscribe_to_parentchain_events( +pub fn subscribe_to_parentchain_events< + ParentchainApi: AccountApi + SubscribeEvents, +>( api: &ParentchainApi, parentchain_id: ParentchainId, shutdown_flag: Arc, diff --git a/app-libs/parentchain-interface/src/integritee/api_client_types.rs b/app-libs/parentchain-interface/src/integritee/api_client_types.rs new file mode 100644 index 0000000000..2513d23d92 --- /dev/null +++ b/app-libs/parentchain-interface/src/integritee/api_client_types.rs @@ -0,0 +1,95 @@ +/* + 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. + +*/ + +//! Contains semi-generic type definitions to talk to the node without depending on an implementation of Runtime. +//! +//! You need to update this if you have a signed extension in your node that +//! is different from the integritee-node, e.g., if you use the `pallet_asset_tx_payment`. + +pub use itp_types::parentchain::{ + AccountData, AccountId, AccountInfo, Address, Balance, Hash, Index, Signature as PairSignature, +}; +use sp_runtime::generic; +use substrate_api_client::ac_primitives::{PlainTipExtrinsicParams, WithExtrinsicParams}; +pub use substrate_api_client::{ + ac_node_api::{ + metadata::{InvalidMetadataError, Metadata, MetadataError}, + EventDetails, Events, StaticEvent, + }, + ac_primitives::{ + config::{AssetRuntimeConfig, Config}, + extrinsics::{ + AssetTip, CallIndex, ExtrinsicParams, GenericAdditionalParams, GenericAdditionalSigned, + GenericExtrinsicParams, GenericSignedExtra, PlainTip, UncheckedExtrinsicV4, + }, + serde_impls::StorageKey, + signer::{SignExtrinsic, StaticExtrinsicSigner}, + }, + rpc::Request, + storage_key, Api, +}; + +// traits from the api-client +pub mod traits { + pub use substrate_api_client::{GetAccountInformation, GetChainInfo, GetStorage}; +} + +pub type IntegriteeTip = PlainTip; +pub type IntegriteeRuntimeConfig = + WithExtrinsicParams>; + +// Configuration for the ExtrinsicParams. +// +// Pay in asset fees. +// +// This needs to be used if the node uses the `pallet_asset_tx_payment`. +pub type IntegriteeExtrinsicParams = GenericExtrinsicParams; +pub type IntegriteeAdditionalParams = GenericAdditionalParams; + +pub type IntegriteeSignedExtra = GenericSignedExtra; +pub type IntegriteeSignature = Signature; + +pub type IntegriteeUncheckedExtrinsic = + UncheckedExtrinsicV4; + +/// Signature type of the [UncheckedExtrinsicV4]. +pub type Signature = Option<(Address, PairSignature, SignedExtra)>; + +pub type Block = generic::Block>; + +#[cfg(feature = "std")] +pub use api::*; +use itp_types::parentchain::Header; + +#[cfg(feature = "std")] +mod api { + use super::IntegriteeRuntimeConfig; + use crate::ParentchainApiTrait; + use itp_node_api::api_client::AccountApi; + use itp_types::parentchain::{AccountId, Balance, Hash, Index}; + pub use substrate_api_client::{ + api::Error as ApiClientError, + rpc::{tungstenite_client::TungsteniteRpcClient, Error as RpcClientError}, + }; + use substrate_api_client::{ + Api, GetBalance, GetChainInfo, GetStorage, GetTransactionPayment, SubscribeEvents, + }; + + pub type IntegriteeApi = Api; + + impl ParentchainApiTrait for IntegriteeApi {} +} diff --git a/app-libs/parentchain-interface/src/integritee/api_factory.rs b/app-libs/parentchain-interface/src/integritee/api_factory.rs new file mode 100644 index 0000000000..333868bce6 --- /dev/null +++ b/app-libs/parentchain-interface/src/integritee/api_factory.rs @@ -0,0 +1,45 @@ +/* + 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 super::api_client_types::IntegriteeApi; +use itp_api_client_types::TungsteniteRpcClient; +use itp_node_api::node_api_factory::{CreateNodeApi, NodeApiFactoryError, Result}; +use sp_core::sr25519; + +/// Node API factory implementation. +pub struct IntegriteeNodeApiFactory { + node_url: String, + signer: sr25519::Pair, +} + +impl IntegriteeNodeApiFactory { + pub fn new(url: String, signer: sr25519::Pair) -> Self { + Self { node_url: url, signer } + } +} + +impl CreateNodeApi for IntegriteeNodeApiFactory { + fn create_api(&self) -> Result { + let rpc_client = TungsteniteRpcClient::new(self.node_url.as_str(), 5) + .map_err(NodeApiFactoryError::FailedToCreateRpcClient)?; + let mut api = + IntegriteeApi::new(rpc_client).map_err(NodeApiFactoryError::FailedToCreateNodeApi)?; + api.set_signer(self.signer.clone().into()); + Ok(api) + } +} diff --git a/app-libs/parentchain-interface/src/integritee/mod.rs b/app-libs/parentchain-interface/src/integritee/mod.rs index 00c350cf20..3859a7808f 100644 --- a/app-libs/parentchain-interface/src/integritee/mod.rs +++ b/app-libs/parentchain-interface/src/integritee/mod.rs @@ -15,6 +15,9 @@ */ +pub mod api_client_types; +#[cfg(feature = "std")] +pub mod api_factory; mod event_filter; mod event_handler; diff --git a/app-libs/parentchain-interface/src/lib.rs b/app-libs/parentchain-interface/src/lib.rs index e2e0582bf7..cdea4b0079 100644 --- a/app-libs/parentchain-interface/src/lib.rs +++ b/app-libs/parentchain-interface/src/lib.rs @@ -22,6 +22,17 @@ extern crate sgx_tstd as std; use codec::{Decode, Encode}; +use itp_node_api::api_client::{AccountApi, ChainApi}; +use itp_types::parentchain::{AccountId, Balance, Hash, Header, Index}; +use sp_runtime::{ + generic::{Block, UncheckedExtrinsic}, + MultiAddress, +}; +use sp_version::GetRuntimeVersionAt; +use substrate_api_client::{ + ac_primitives::Properties, extrinsic::BalancesExtrinsics, GetAccountInformation, GetBalance, + GetStorage, GetTransactionPayment, SubmitAndWatch, SubscribeEvents, SystemApi, +}; #[cfg(feature = "std")] pub mod event_subscriber; @@ -54,3 +65,18 @@ pub fn decode_and_log_error(encoded: &mut &[u8]) -> Option { }, } } + +/// a trait to aggreagate all traits we need in the service +pub trait ParentchainApiTrait: + AccountApi + + GetBalance + + GetStorage + + SystemApi + + BalancesExtrinsics
, Balance = Balance> + + ChainApi + + GetAccountInformation + + SubscribeEvents + + GetTransactionPayment + + SubmitAndWatch //+ GetRuntimeVersionAt>> +{ +} diff --git a/app-libs/parentchain-interface/src/target_a/api_client_types.rs b/app-libs/parentchain-interface/src/target_a/api_client_types.rs new file mode 100644 index 0000000000..1d3ed7398e --- /dev/null +++ b/app-libs/parentchain-interface/src/target_a/api_client_types.rs @@ -0,0 +1,91 @@ +/* + 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. + +*/ + +//! Contains semi-generic type definitions to talk to the node without depending on an implementation of Runtime. +//! +//! You need to update this if you have a signed extension in your node that +//! is different from the integritee-node, e.g., if you use the `pallet_asset_tx_payment`. + +pub use itp_types::parentchain::{ + AccountData, AccountId, AccountInfo, Address, Balance, Hash, Index, Signature as PairSignature, +}; +use substrate_api_client::ac_primitives::{PlainTipExtrinsicParams, WithExtrinsicParams}; +pub use substrate_api_client::{ + ac_node_api::{ + metadata::{InvalidMetadataError, Metadata, MetadataError}, + EventDetails, Events, StaticEvent, + }, + ac_primitives::{ + config::{AssetRuntimeConfig, Config}, + extrinsics::{ + AssetTip, CallIndex, ExtrinsicParams, GenericAdditionalParams, GenericAdditionalSigned, + GenericExtrinsicParams, GenericSignedExtra, PlainTip, UncheckedExtrinsicV4, + }, + serde_impls::StorageKey, + signer::{SignExtrinsic, StaticExtrinsicSigner}, + }, + rpc::Request, + storage_key, Api, +}; + +// traits from the api-client +pub mod traits { + pub use substrate_api_client::{GetAccountInformation, GetChainInfo, GetStorage}; +} + +pub type TargetATip = PlainTip; +pub type TargetARuntimeConfig = + WithExtrinsicParams>; + +// Configuration for the ExtrinsicParams. +// +// Pay in asset fees. +// +// This needs to be used if the node uses the `pallet_asset_tx_payment`. +pub type TargetAExtrinsicParams = GenericExtrinsicParams; +pub type TargetAAdditionalParams = GenericAdditionalParams; + +pub type TargetASignedExtra = GenericSignedExtra; +pub type TargetASignature = Signature; + +pub type TargetAUncheckedExtrinsic = + UncheckedExtrinsicV4; + +/// Signature type of the [UncheckedExtrinsicV4]. +pub type Signature = Option<(Address, PairSignature, SignedExtra)>; + +#[cfg(feature = "std")] +pub use api::*; + +#[cfg(feature = "std")] +mod api { + use super::TargetARuntimeConfig; + use crate::ParentchainApiTrait; + use itp_node_api::api_client::AccountApi; + use itp_types::parentchain::{AccountId, Balance, Hash, Index}; + pub use substrate_api_client::{ + api::Error as ApiClientError, + rpc::{tungstenite_client::TungsteniteRpcClient, Error as RpcClientError}, + }; + use substrate_api_client::{ + Api, GetBalance, GetChainInfo, GetStorage, GetTransactionPayment, SubscribeEvents, + }; + + pub type TargetAApi = Api; + + //impl ParentchainApiTrait for TargetAApi {} +} diff --git a/app-libs/parentchain-interface/src/target_a/api_factory.rs b/app-libs/parentchain-interface/src/target_a/api_factory.rs new file mode 100644 index 0000000000..1955a26f01 --- /dev/null +++ b/app-libs/parentchain-interface/src/target_a/api_factory.rs @@ -0,0 +1,45 @@ +/* + 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 super::api_client_types::TargetAApi; +use itp_api_client_types::TungsteniteRpcClient; +use itp_node_api::node_api_factory::{CreateNodeApi, NodeApiFactoryError, Result}; +use sp_core::sr25519; + +/// Node API factory implementation. +pub struct TargetANodeApiFactory { + node_url: String, + signer: sr25519::Pair, +} + +impl TargetANodeApiFactory { + pub fn new(url: String, signer: sr25519::Pair) -> Self { + Self { node_url: url, signer } + } +} + +impl CreateNodeApi for TargetANodeApiFactory { + fn create_api(&self) -> Result { + let rpc_client = TungsteniteRpcClient::new(self.node_url.as_str(), 5) + .map_err(NodeApiFactoryError::FailedToCreateRpcClient)?; + let mut api = + TargetAApi::new(rpc_client).map_err(NodeApiFactoryError::FailedToCreateNodeApi)?; + api.set_signer(self.signer.clone().into()); + Ok(api) + } +} diff --git a/app-libs/parentchain-interface/src/target_a/mod.rs b/app-libs/parentchain-interface/src/target_a/mod.rs index d8d804d42f..433ec0a072 100644 --- a/app-libs/parentchain-interface/src/target_a/mod.rs +++ b/app-libs/parentchain-interface/src/target_a/mod.rs @@ -14,6 +14,10 @@ limitations under the License. */ + +pub mod api_client_types; +#[cfg(feature = "std")] +pub mod api_factory; mod event_filter; mod event_handler; diff --git a/app-libs/parentchain-interface/src/target_b/api_client_types.rs b/app-libs/parentchain-interface/src/target_b/api_client_types.rs new file mode 100644 index 0000000000..2580017de0 --- /dev/null +++ b/app-libs/parentchain-interface/src/target_b/api_client_types.rs @@ -0,0 +1,91 @@ +/* + 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. + +*/ + +//! Contains semi-generic type definitions to talk to the node without depending on an implementation of Runtime. +//! +//! You need to update this if you have a signed extension in your node that +//! is different from the integritee-node, e.g., if you use the `pallet_asset_tx_payment`. + +pub use itp_types::parentchain::{ + AccountData, AccountId, AccountInfo, Address, Balance, Hash, Index, Signature as PairSignature, +}; +use substrate_api_client::ac_primitives::{AssetTipExtrinsicParams, WithExtrinsicParams}; +pub use substrate_api_client::{ + ac_node_api::{ + metadata::{InvalidMetadataError, Metadata, MetadataError}, + EventDetails, Events, StaticEvent, + }, + ac_primitives::{ + config::{AssetRuntimeConfig, Config}, + extrinsics::{ + AssetTip, CallIndex, ExtrinsicParams, GenericAdditionalParams, GenericAdditionalSigned, + GenericExtrinsicParams, GenericSignedExtra, PlainTip, UncheckedExtrinsicV4, + }, + serde_impls::StorageKey, + signer::{SignExtrinsic, StaticExtrinsicSigner}, + }, + rpc::Request, + storage_key, Api, +}; + +// traits from the api-client +pub mod traits { + pub use substrate_api_client::{GetAccountInformation, GetChainInfo, GetStorage}; +} + +pub type TargetBTip = AssetTip; +pub type TargetBRuntimeConfig = + WithExtrinsicParams>; + +// Configuration for the ExtrinsicParams. +// +// Pay in asset fees. +// +// This needs to be used if the node uses the `pallet_asset_tx_payment`. +pub type TargetBExtrinsicParams = GenericExtrinsicParams; +pub type TargetBAdditionalParams = GenericAdditionalParams; + +pub type TargetBSignedExtra = GenericSignedExtra; +pub type TargetBSignature = Signature; + +pub type TargetBUncheckedExtrinsic = + UncheckedExtrinsicV4; + +/// Signature type of the [UncheckedExtrinsicV4]. +pub type Signature = Option<(Address, PairSignature, SignedExtra)>; + +#[cfg(feature = "std")] +pub use api::*; + +#[cfg(feature = "std")] +mod api { + use super::TargetBRuntimeConfig; + use crate::ParentchainApiTrait; + use itp_node_api::api_client::{AccountApi, ApiResult}; + use itp_types::parentchain::{AccountId, Balance, Hash, Index}; + pub use substrate_api_client::{ + api::Error as ApiClientError, + rpc::{tungstenite_client::TungsteniteRpcClient, Error as RpcClientError}, + }; + use substrate_api_client::{ + Api, GetBalance, GetChainInfo, GetStorage, GetTransactionPayment, SubscribeEvents, + }; + + pub type TargetBApi = Api; + + impl ParentchainApiTrait for TargetBApi {} +} diff --git a/app-libs/parentchain-interface/src/target_b/api_factory.rs b/app-libs/parentchain-interface/src/target_b/api_factory.rs new file mode 100644 index 0000000000..691e6de27d --- /dev/null +++ b/app-libs/parentchain-interface/src/target_b/api_factory.rs @@ -0,0 +1,45 @@ +/* + 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 super::api_client_types::TargetBApi; +use itp_api_client_types::TungsteniteRpcClient; +use itp_node_api::node_api_factory::{CreateNodeApi, NodeApiFactoryError, Result}; +use sp_core::sr25519; + +/// Node API factory implementation. +pub struct TargetBNodeApiFactory { + node_url: String, + signer: sr25519::Pair, +} + +impl TargetBNodeApiFactory { + pub fn new(url: String, signer: sr25519::Pair) -> Self { + Self { node_url: url, signer } + } +} + +impl CreateNodeApi for TargetBNodeApiFactory { + fn create_api(&self) -> Result { + let rpc_client = TungsteniteRpcClient::new(self.node_url.as_str(), 5) + .map_err(NodeApiFactoryError::FailedToCreateRpcClient)?; + let mut api = + TargetBApi::new(rpc_client).map_err(NodeApiFactoryError::FailedToCreateNodeApi)?; + api.set_signer(self.signer.clone().into()); + Ok(api) + } +} diff --git a/app-libs/parentchain-interface/src/target_b/mod.rs b/app-libs/parentchain-interface/src/target_b/mod.rs index c21bbe6654..a092a567bd 100644 --- a/app-libs/parentchain-interface/src/target_b/mod.rs +++ b/app-libs/parentchain-interface/src/target_b/mod.rs @@ -15,6 +15,9 @@ */ +pub mod api_client_types; +#[cfg(feature = "std")] +pub mod api_factory; mod event_filter; mod event_handler; @@ -33,11 +36,26 @@ use itc_parentchain_indirect_calls_executor::{ filter_metadata::FilterIntoDataFrom, IndirectDispatch, }; -use itp_api_client_types::ParentchainSignedExtra; +use itp_api_client_types::{ + AssetRuntimeConfig, AssetTip, GenericAdditionalParams, GenericExtrinsicParams, + GenericSignedExtra, PairSignature, ParentchainPlainTip, Signature, UncheckedExtrinsicV4, +}; use itp_node_api::metadata::pallet_timestamp::TimestampCallIndexes; use itp_stf_primitives::traits::IndirectExecutor; +use itp_types::parentchain::{Address, Balance, Hash, Index}; use log::*; +// We assume Asset Hub here (or any similar parachain) +// Pay in asset fees. +// This needs to be used if the node uses the `pallet_asset_tx_payment`. +pub type ParentchainExtrinsicParams = GenericExtrinsicParams>; +pub type ParentchainAdditionalParams = GenericAdditionalParams; + +pub type ParentchainUncheckedExtrinsic = + UncheckedExtrinsicV4; +pub type ParentchainSignedExtra = GenericSignedExtra; +pub type ParentchainSignature = Signature; + /// Parses the extrinsics corresponding to the parentchain. pub type ParentchainExtrinsicParser = ExtrinsicParser; diff --git a/core-primitives/node-api/api-client-extensions/src/account.rs b/core-primitives/node-api/api-client-extensions/src/account.rs index d2becda266..9b4e11216d 100644 --- a/core-primitives/node-api/api-client-extensions/src/account.rs +++ b/core-primitives/node-api/api-client-extensions/src/account.rs @@ -14,11 +14,9 @@ limitations under the License. */ - use crate::ApiResult; -use itp_api_client_types::{ - traits::GetAccountInformation, Api, Config, ParentchainRuntimeConfig, Request, -}; +use itp_api_client_types::{traits::GetAccountInformation, Api, Config, Request}; +use substrate_api_client::ac_primitives::AccountData; /// ApiClient extension that contains some convenience methods around accounts. // Todo: make generic over `Config` type instead? @@ -31,9 +29,11 @@ pub trait AccountApi { fn get_free_balance(&self, who: &Self::AccountId) -> ApiResult; } -impl AccountApi for Api +impl AccountApi for Api where Client: Request, + ParentchainRuntimeConfig: + Config::Balance>>, { type AccountId = ::AccountId; type Index = ::Index; diff --git a/core-primitives/node-api/factory/src/lib.rs b/core-primitives/node-api/factory/src/lib.rs index 2a98e07a1c..2882fe9482 100644 --- a/core-primitives/node-api/factory/src/lib.rs +++ b/core-primitives/node-api/factory/src/lib.rs @@ -20,7 +20,7 @@ use itp_api_client_types::{ParentchainApi, TungsteniteRpcClient}; use sp_core::sr25519; /// Trait to create a node API, based on a node URL and signer. -pub trait CreateNodeApi { +pub trait CreateNodeApi { fn create_api(&self) -> Result; } @@ -61,7 +61,7 @@ impl NodeApiFactory { } } -impl CreateNodeApi for NodeApiFactory { +impl CreateNodeApi for NodeApiFactory { fn create_api(&self) -> Result { let rpc_client = TungsteniteRpcClient::new(self.node_url.as_str(), 5) .map_err(NodeApiFactoryError::FailedToCreateRpcClient)?; diff --git a/enclave-runtime/Cargo.lock b/enclave-runtime/Cargo.lock index 312ab70de5..f84cc501cd 100644 --- a/enclave-runtime/Cargo.lock +++ b/enclave-runtime/Cargo.lock @@ -1682,6 +1682,8 @@ dependencies = [ "sgx_tstd", "sp-core", "sp-runtime", + "sp-version", + "substrate-api-client", ] [[package]] diff --git a/service/src/account_funding.rs b/service/src/account_funding.rs index affbaf815f..c761e039ca 100644 --- a/service/src/account_funding.rs +++ b/service/src/account_funding.rs @@ -17,10 +17,11 @@ use crate::error::{Error, ServiceResult}; use codec::Encode; +use ita_parentchain_interface::ParentchainApiTrait; use itp_node_api::api_client::{AccountApi, ParentchainApi, TEEREX}; use itp_settings::worker::REGISTERING_FEE_FACTOR_FOR_INIT_FUNDS; use itp_types::{ - parentchain::{AccountId, Balance, ParentchainId}, + parentchain::{AccountId, Balance, Index, ParentchainId}, Moment, }; use log::*; @@ -29,10 +30,12 @@ use sp_core::{ Pair, }; use sp_keyring::AccountKeyring; -use sp_runtime::{MultiAddress, Saturating}; +use sp_runtime::{traits::SignedExtension, MultiAddress, Saturating}; use std::{fmt::Display, thread, time::Duration}; use substrate_api_client::{ - ac_compose_macros::compose_extrinsic, ac_primitives::Bytes, extrinsic::BalancesExtrinsics, + ac_compose_macros::{compose_extrinsic, compose_extrinsic_with_nonce}, + ac_primitives::Bytes, + extrinsic::BalancesExtrinsics, GetBalance, GetStorage, GetTransactionPayment, SubmitAndWatch, SystemApi, XtStatus, }; use teerex_primitives::SgxAttestationMethod; @@ -76,13 +79,19 @@ pub trait ParentchainAccountInfo { fn decimals(&self) -> ServiceResult; } -pub struct ParentchainAccountInfoProvider { +pub struct ParentchainAccountInfoProvider +where + ParentchainApi: ParentchainApiTrait, +{ parentchain_id: ParentchainId, node_api: ParentchainApi, account_and_role: AccountAndRole, } -impl ParentchainAccountInfo for ParentchainAccountInfoProvider { +impl ParentchainAccountInfo for ParentchainAccountInfoProvider +where + ParentchainApi: ParentchainApiTrait, +{ fn free_balance(&self) -> ServiceResult { self.node_api .get_free_balance(&self.account_and_role.account_id()) @@ -107,7 +116,10 @@ impl ParentchainAccountInfo for ParentchainAccountInfoProvider { } } -impl ParentchainAccountInfoProvider { +impl ParentchainAccountInfoProvider +where + ParentchainApi: ParentchainApiTrait, +{ pub fn new( parentchain_id: ParentchainId, node_api: ParentchainApi, @@ -120,7 +132,7 @@ impl ParentchainAccountInfoProvider { /// evaluate if the enclave should have more funds and how much more /// in --dev mode: let Alice pay for missing funds /// in production mode: wait for manual transfer before continuing -pub fn setup_reasonable_account_funding( +pub fn setup_reasonable_account_funding( api: &ParentchainApi, accountid: &AccountId32, parentchain_id: ParentchainId, @@ -148,7 +160,7 @@ pub fn setup_reasonable_account_funding( } } -fn estimate_funds_needed_to_run_for_a_while( +fn estimate_funds_needed_to_run_for_a_while( api: &ParentchainApi, accountid: &AccountId32, parentchain_id: ParentchainId, @@ -163,32 +175,35 @@ fn estimate_funds_needed_to_run_for_a_while( info!("[{:?}] a single transfer costs {:?}", parentchain_id, transfer_fee); min_required_funds += 1000 * transfer_fee; - // Check if this is an integritee chain and Compose a register_sgx_enclave extrinsic - if let Ok(ra_renewal) = api.get_constant::("Teerex", "MaxAttestationRenewalPeriod") { - info!("[{:?}] this chain has the teerex pallet. estimating RA fees", parentchain_id); - let encoded_xt: Bytes = compose_extrinsic!( - api, - TEEREX, - "register_sgx_enclave", - vec![0u8; SGX_RA_PROOF_MAX_LEN], - Some(vec![0u8; MAX_URL_LEN]), - SgxAttestationMethod::Dcap { proxied: false } - ) - .encode() - .into(); - let tx_fee = - api.get_fee_details(&encoded_xt, None).unwrap().unwrap().inclusion_fee.unwrap(); - let ra_fee = tx_fee.base_fee + tx_fee.len_fee + tx_fee.adjusted_weight_fee; - info!( - "[{:?}] one enclave registration costs {:?} and needs to be renewed every {:?}h", - parentchain_id, - ra_fee, - ra_renewal / 1_000 / 3_600 - ); - min_required_funds += 5 * ra_fee; - } else { - info!("[{:?}] this chain has no teerex pallet, no need to add RA fees", parentchain_id); - } + // // Check if this is an integritee chain and Compose a register_sgx_enclave extrinsic + // if let Ok(ra_renewal) = api.get_constant::("Teerex", "MaxAttestationRenewalPeriod") { + // info!("[{:?}] this chain has the teerex pallet. estimating RA fees", parentchain_id); + // let nonce = api.get_nonce_of(accountid)?; + // + // let encoded_xt: Bytes = compose_extrinsic_with_nonce!( + // api, + // nonce, + // TEEREX, + // "register_sgx_enclave", + // vec![0u8; SGX_RA_PROOF_MAX_LEN], + // Some(vec![0u8; MAX_URL_LEN]), + // SgxAttestationMethod::Dcap { proxied: false } + // ) + // .encode() + // .into(); + // let tx_fee = + // api.get_fee_details(&encoded_xt, None).unwrap().unwrap().inclusion_fee.unwrap(); + // let ra_fee = tx_fee.base_fee + tx_fee.len_fee + tx_fee.adjusted_weight_fee; + // info!( + // "[{:?}] one enclave registration costs {:?} and needs to be renewed every {:?}h", + // parentchain_id, + // ra_fee, + // ra_renewal / 1_000 / 3_600 + // ); + // min_required_funds += 5 * ra_fee; + // } else { + // info!("[{:?}] this chain has no teerex pallet, no need to add RA fees", parentchain_id); + // } info!( "[{:?}] we estimate the funding requirement for the primary validateer (worst case) to be {:?}", @@ -198,7 +213,10 @@ fn estimate_funds_needed_to_run_for_a_while( Ok(min_required_funds) } -pub fn estimate_fee(api: &ParentchainApi, encoded_extrinsic: Vec) -> Result { +pub fn estimate_fee( + api: &ParentchainApi, + encoded_extrinsic: Vec, +) -> Result { let reg_fee_details = api.get_fee_details(&encoded_extrinsic.into(), None)?; match reg_fee_details { Some(details) => match details.inclusion_fee { @@ -213,7 +231,7 @@ pub fn estimate_fee(api: &ParentchainApi, encoded_extrinsic: Vec) -> Result< } /// Alice sends some funds to the account. only for dev chains testing -fn bootstrap_funds_from_alice( +fn bootstrap_funds_from_alice( api: &ParentchainApi, accountid: &AccountId32, funding_amount: u128, @@ -253,7 +271,9 @@ fn bootstrap_funds_from_alice( } /// precise estimation of necessary funds to register a hardcoded number of proxies -pub fn shard_vault_initial_funds(api: &ParentchainApi) -> Result { +pub fn shard_vault_initial_funds( + api: &ParentchainApi, +) -> Result { let proxy_deposit_base: Balance = api.get_constant("Proxy", "ProxyDepositBase")?; let proxy_deposit_factor: Balance = api.get_constant("Proxy", "ProxyDepositFactor")?; let transfer_fee = estimate_transfer_fee(api)?; @@ -263,12 +283,18 @@ pub fn shard_vault_initial_funds(api: &ParentchainApi) -> Result } /// precise estimation of a single transfer fee -pub fn estimate_transfer_fee(api: &ParentchainApi) -> Result { +pub fn estimate_transfer_fee( + api: &ParentchainApi, +) -> Result { let encoded_xt: Bytes = api .balance_transfer_allow_death(AccountId::from([0u8; 32]).into(), 1000000000000) .encode() .into(); - let tx_fee = api.get_fee_details(&encoded_xt, None).unwrap().unwrap().inclusion_fee.unwrap(); + let tx_fee = api + .get_fee_details(&encoded_xt, None)? + .expect("the node must understand our extrinsic encoding") + .inclusion_fee + .unwrap(); let transfer_fee = tx_fee.base_fee + tx_fee.len_fee + tx_fee.adjusted_weight_fee; Ok(transfer_fee) } diff --git a/service/src/main_impl.rs b/service/src/main_impl.rs index dcfe995493..98b0f984c6 100644 --- a/service/src/main_impl.rs +++ b/service/src/main_impl.rs @@ -55,7 +55,7 @@ use sgx_types::*; use sp_runtime::traits::{Header as HeaderT, IdentifyAccount}; use substrate_api_client::{ api::XtStatus, rpc::HandleSubscription, GetAccountInformation, GetBalance, GetChainInfo, - SubmitAndWatch, SubscribeChain, SubscribeEvents, + GetStorage, SubmitAndWatch, SubscribeChain, SubscribeEvents, }; use teerex_primitives::{AnySigner, MultiEnclave}; @@ -72,8 +72,13 @@ use crate::{ sidechain_setup::ParentchainIntegriteeSidechainInfoProvider, }; use enclave_bridge_primitives::ShardIdentifier; +use ita_parentchain_interface::{ + integritee::{api_client_types::IntegriteeApi, api_factory::IntegriteeNodeApiFactory}, + ParentchainApiTrait, +}; use itc_parentchain::primitives::ParentchainId; -use itp_types::parentchain::{AccountId, Balance}; +use itp_node_api::api_client::ChainApi; +use itp_types::parentchain::{AccountId, Balance, Index}; use sp_core::crypto::{AccountId32, Ss58Codec}; use sp_keyring::AccountKeyring; use sp_runtime::MultiSigner; @@ -95,8 +100,13 @@ use tokio::{runtime::Handle, task::JoinHandle, time::Instant}; const VERSION: &str = env!("CARGO_PKG_VERSION"); #[cfg(feature = "link-binary")] -pub type EnclaveWorker = - Worker>; +pub type EnclaveWorker = Worker< + Config, + IntegriteeNodeApiFactory, + IntegriteeApi, + Enclave, + InitializationHandler, +>; pub(crate) fn main() { // Setup logging @@ -502,9 +512,12 @@ fn start_worker( .expect("our enclave should be registered at this point"); trace!("verified that our enclave is registered: {:?}", my_enclave); - let (we_are_primary_validateer, re_init_parentchain_needed) = - match integritee_rpc_api.primary_worker_for_shard(shard, None).unwrap() { - Some(primary_enclave) => match primary_enclave.instance_signer() { + let (we_are_primary_validateer, re_init_parentchain_needed) = match integritee_rpc_api + .primary_worker_for_shard(shard, None) + .unwrap() + { + Some(primary_enclave) => + match primary_enclave.instance_signer() { AnySigner::Known(MultiSigner::Ed25519(primary)) => if primary.encode() == tee_accountid.encode() { println!("We are primary worker on this shard and we have been previously running."); @@ -539,24 +552,24 @@ fn start_worker( ); }, }, - None => { - println!("We are the primary worker on this shard and the shard is untouched. Will initialize it"); - enclave.init_shard(shard.encode()).unwrap(); - if WorkerModeProvider::worker_mode() != WorkerMode::Teeracle { - enclave - .init_shard_creation_parentchain_header( - shard, - &ParentchainId::Integritee, - ®ister_enclave_xt_header, - ) - .unwrap(); - debug!("shard config should be initialized on integritee network now"); - (true, true) - } else { - (true, false) - } - }, - }; + None => { + println!("We are the primary worker on this shard and the shard is untouched. Will initialize it"); + enclave.init_shard(shard.encode()).unwrap(); + if WorkerModeProvider::worker_mode() != WorkerMode::Teeracle { + enclave + .init_shard_creation_parentchain_header( + shard, + &ParentchainId::Integritee, + ®ister_enclave_xt_header, + ) + .unwrap(); + debug!("shard config should be initialized on integritee network now"); + (true, true) + } else { + (true, false) + } + }, + }; debug!("getting shard creation: {:?}", enclave.get_shard_creation_info(shard)); initialization_handler.registered_on_parentchain(); @@ -651,10 +664,14 @@ fn start_worker( } let maybe_target_a_rpc_api = if let Some(url) = config.target_a_parentchain_rpc_endpoint() { - let (api, mut handles) = init_target_parentchain( + println!("Initializing parentchain TargetA with url: {}", url); + let api = NodeApiFactory::new(url, AccountKeyring::Alice.pair()) + .create_api() + .unwrap_or_else(|_| panic!("[TargetA] Failed to create parentchain node API")); + let mut handles = init_target_parentchain( &enclave, &tee_accountid, - url, + &api, shard, ParentchainId::TargetA, is_development_mode, @@ -667,10 +684,17 @@ fn start_worker( }; let maybe_target_b_rpc_api = if let Some(url) = config.target_b_parentchain_rpc_endpoint() { - let (api, mut handles) = init_target_parentchain( + println!("Initializing parentchain TargetB with url: {}", url); + let api = ita_parentchain_interface::target_b::api_factory::TargetBNodeApiFactory::new( + url, + AccountKeyring::Alice.pair(), + ) + .create_api() + .unwrap_or_else(|_| panic!("[TargetB] Failed to create parentchain node API")); + let mut handles = init_target_parentchain( &enclave, &tee_accountid, - url, + &api, shard, ParentchainId::TargetB, is_development_mode, @@ -787,32 +811,22 @@ fn init_provided_shard_vault( } } -fn init_target_parentchain( +fn init_target_parentchain( enclave: &Arc, tee_account_id: &AccountId32, - url: String, + node_api: &ParentchainApi, shard: &ShardIdentifier, parentchain_id: ParentchainId, is_development_mode: bool, shutdown_flag: Arc, -) -> (ParentchainApi, Vec>) +) -> Vec> where E: EnclaveBase + Sidechain, { - println!("Initializing parentchain {:?} with url: {}", parentchain_id, url); - let node_api = NodeApiFactory::new(url, AccountKeyring::Alice.pair()) - .create_api() - .unwrap_or_else(|_| panic!("[{:?}] Failed to create parentchain node API", parentchain_id)); - - setup_reasonable_account_funding( - &node_api, - tee_account_id, - parentchain_id, - is_development_mode, - ) - .unwrap_or_else(|_| { - panic!("[{:?}] Could not fund parentchain enclave account", parentchain_id) - }); + setup_reasonable_account_funding(node_api, tee_account_id, parentchain_id, is_development_mode) + .unwrap_or_else(|_| { + panic!("[{:?}] Could not fund parentchain enclave account", parentchain_id) + }); // we attempt to set shard creation for this parentchain in case it hasn't been done before let api_head = node_api.get_header(None).unwrap().unwrap(); @@ -855,16 +869,16 @@ where .name(format!("{:?}_parentchain_event_subscription", parentchain_id)) .spawn(move || { ita_parentchain_interface::event_subscriber::subscribe_to_parentchain_events( - &node_api_clone, + node_api_clone, parentchain_id, shutdown_flag, ) }) .unwrap(); - (node_api, handles) + handles } -fn init_parentchain( +fn init_parentchain( enclave: &Arc, node_api: &ParentchainApi, tee_account_id: &AccountId32, diff --git a/service/src/ocall_bridge/component_factory.rs b/service/src/ocall_bridge/component_factory.rs index 3448bea31b..403f0a453f 100644 --- a/service/src/ocall_bridge/component_factory.rs +++ b/service/src/ocall_bridge/component_factory.rs @@ -135,8 +135,9 @@ impl< PeerBlockFetcher, TokioHandle, MetricsReceiver, - > where - NodeApi: CreateNodeApi + 'static, + > +where + NodeApi: CreateNodeApi + 'static, Broadcaster: BroadcastBlocks + 'static, EnclaveApi: RemoteAttestationCallBacks + 'static, Storage: BlockStorage + 'static, diff --git a/service/src/ocall_bridge/worker_on_chain_ocall.rs b/service/src/ocall_bridge/worker_on_chain_ocall.rs index b6ece561c2..ee3a618498 100644 --- a/service/src/ocall_bridge/worker_on_chain_ocall.rs +++ b/service/src/ocall_bridge/worker_on_chain_ocall.rs @@ -19,6 +19,12 @@ use crate::ocall_bridge::bridge_api::{OCallBridgeError, OCallBridgeResult, WorkerOnChainBridge}; use chrono::Local; use codec::{Decode, Encode}; +use ita_parentchain_interface::{ + integritee::{api_client_types::IntegriteeApi, api_factory::IntegriteeNodeApiFactory}, + target_a::{api_client_types::TargetAApi, api_factory::TargetANodeApiFactory}, + target_b::{api_client_types::TargetBApi, api_factory::TargetBNodeApiFactory}, + ParentchainApiTrait, +}; use itp_api_client_types::ParentchainApi; use itp_node_api::{api_client::AccountApi, node_api_factory::CreateNodeApi}; use itp_types::{ @@ -41,18 +47,18 @@ use substrate_api_client::{ GetAccountInformation, GetChainInfo, GetStorage, SubmitAndWatch, SubmitExtrinsic, XtStatus, }; -pub struct WorkerOnChainOCall { - integritee_api_factory: Arc, - target_a_parentchain_api_factory: Option>, - target_b_parentchain_api_factory: Option>, +pub struct WorkerOnChainOCall { + integritee_api_factory: Arc, + target_a_parentchain_api_factory: Option>, + target_b_parentchain_api_factory: Option>, log_dir: Arc, } -impl WorkerOnChainOCall { +impl WorkerOnChainOCall { pub fn new( - integritee_api_factory: Arc, - target_a_parentchain_api_factory: Option>, - target_b_parentchain_api_factory: Option>, + integritee_api_factory: Arc, + target_a_parentchain_api_factory: Option>, + target_b_parentchain_api_factory: Option>, log_dir: Arc, ) -> Self { WorkerOnChainOCall { @@ -64,7 +70,7 @@ impl WorkerOnChainOCall { } } -impl WorkerOnChainOCall { +impl WorkerOnChainOCall { pub fn create_api(&self, parentchain_id: ParentchainId) -> OCallBridgeResult { Ok(match parentchain_id { ParentchainId::Integritee => self.integritee_api_factory.create_api()?, @@ -82,10 +88,7 @@ impl WorkerOnChainOCall { } } -impl WorkerOnChainBridge for WorkerOnChainOCall -where - F: CreateNodeApi, -{ +impl WorkerOnChainBridge for WorkerOnChainOCall { fn worker_request( &self, request: Vec, diff --git a/service/src/parentchain_handler.rs b/service/src/parentchain_handler.rs index 2fd175af57..11164730e0 100644 --- a/service/src/parentchain_handler.rs +++ b/service/src/parentchain_handler.rs @@ -19,12 +19,11 @@ use crate::error::{Error, ServiceResult}; use codec::{Decode, Encode}; use humantime::format_duration; -use ita_parentchain_interface::integritee::Header; +use ita_parentchain_interface::{integritee::Header, ParentchainApiTrait}; use itc_parentchain::{ light_client::light_client_init_params::{GrandpaParams, SimpleParams}, primitives::{ParentchainId, ParentchainInitParams}, }; -use itp_api_client_types::ParentchainApi; use itp_enclave_api::{enclave_base::EnclaveBase, sidechain::Sidechain}; use itp_node_api::api_client::ChainApi; use itp_storage::StorageProof; @@ -74,9 +73,10 @@ pub(crate) struct ParentchainHandler { // #TODO: #1451: Reintroduce `ParentchainApi: ChainApi` once there is no trait bound conflict // any more with the api-clients own trait definitions. -impl ParentchainHandler +impl ParentchainHandler where EnclaveApi: EnclaveBase, + ParentchainApi: ParentchainApiTrait, { pub fn new( parentchain_api: ParentchainApi, @@ -142,9 +142,11 @@ where } } -impl HandleParentchain for ParentchainHandler +impl HandleParentchain + for ParentchainHandler where EnclaveApi: Sidechain + EnclaveBase, + ParentchainApi: ParentchainApiTrait, { fn init_parentchain_components(&self) -> ServiceResult
{ Ok(self diff --git a/service/src/prometheus_metrics.rs b/service/src/prometheus_metrics.rs index 80534a0353..58cd8de508 100644 --- a/service/src/prometheus_metrics.rs +++ b/service/src/prometheus_metrics.rs @@ -34,13 +34,17 @@ use codec::{Decode, Encode}; use core::time::Duration; use enclave_bridge_primitives::ShardIdentifier; use frame_support::scale_info::TypeInfo; +use ita_parentchain_interface::{ + integritee::api_client_types::IntegriteeApi, target_a::api_client_types::TargetAApi, + target_b::api_client_types::TargetBApi, +}; #[cfg(feature = "attesteer")] use itc_rest_client::{ http_client::{DefaultSend, HttpClient}, rest_client::{RestClient, Url as URL}, RestGet, RestPath, }; -use itp_api_client_types::ParentchainApi; + use itp_enclave_api::{enclave_base::EnclaveBase, sidechain::Sidechain}; use itp_enclave_metrics::EnclaveMetric; use itp_types::{parentchain::ParentchainId, EnclaveFingerprint}; @@ -354,16 +358,16 @@ pub fn start_prometheus_metrics_server( enclave: &Arc, tee_account_id: &AccountId32, shard: &ShardIdentifier, - integritee_rpc_api: ParentchainApi, - maybe_target_a_rpc_api: Option, - maybe_target_b_rpc_api: Option, + integritee_rpc_api: IntegriteeApi, + maybe_target_a_rpc_api: Option, + maybe_target_b_rpc_api: Option, shielding_target: Option, tokio_handle: &Handle, metrics_server_port: u16, ) where E: EnclaveBase + Sidechain, { - let mut account_info_providers: Vec> = vec![]; + let mut account_info_providers: Vec>> = vec![]; account_info_providers.push(Arc::new(ParentchainAccountInfoProvider::new( ParentchainId::Integritee, integritee_rpc_api.clone(), diff --git a/service/src/worker.rs b/service/src/worker.rs index 97bb56be83..adb6d76f5d 100644 --- a/service/src/worker.rs +++ b/service/src/worker.rs @@ -14,7 +14,6 @@ limitations under the License. */ - ///! Integritee worker. Inspiration for this design came from parity's substrate Client. /// /// This should serve as a proof of concept for a potential refactoring design. Ultimately, everything @@ -22,6 +21,7 @@ /// multiple traits. use crate::{config::Config, error::Error, initialized_service::TrackInitialization}; use async_trait::async_trait; +use ita_parentchain_interface::ParentchainApiTrait; use itc_rpc_client::direct_client::{DirectApi, DirectClient as DirectWorkerApi}; use itp_node_api::{api_client::PalletTeerexApi, node_api_factory::CreateNodeApi}; use itp_types::ShardIdentifier; @@ -33,23 +33,27 @@ use jsonrpsee::{ ws_client::WsClientBuilder, }; use log::*; -use std::sync::{Arc, RwLock}; +use std::{ + marker::PhantomData, + sync::{Arc, RwLock}, +}; use teerex_primitives::MultiEnclave; use url::Url as UrlType; pub type WorkerResult = Result; pub type Url = String; -pub struct Worker { +pub struct Worker { _config: Config, // unused yet, but will be used when more methods are migrated to the worker _enclave_api: Arc, node_api_factory: Arc, initialization_handler: Arc, peers: RwLock>, + _phantom: PhantomData, } -impl - Worker +impl + Worker { pub fn new( config: Config, @@ -75,10 +79,11 @@ pub trait AsyncBlockBroadcaster { } #[async_trait] -impl AsyncBlockBroadcaster - for Worker +impl AsyncBlockBroadcaster + for Worker where - NodeApiFactory: CreateNodeApi + Send + Sync, + NodeApiFactory: CreateNodeApi + Send + Sync, + NodeApi: ParentchainApiTrait, Enclave: Send + Sync, InitializationHandler: TrackInitialization + Send + Sync, { @@ -136,10 +141,11 @@ pub trait UpdatePeers { } } -impl UpdatePeers - for Worker +impl UpdatePeers + for Worker where - NodeApiFactory: CreateNodeApi + Send + Sync, + NodeApiFactory: CreateNodeApi + Send + Sync, + NodeApi: ParentchainApiTrait, { fn search_peers(&self, shard: ShardIdentifier) -> WorkerResult> { let node_api = self diff --git a/sidechain/peer-fetch/src/untrusted_peer_fetch.rs b/sidechain/peer-fetch/src/untrusted_peer_fetch.rs index cfdabbfbf4..592555cc40 100644 --- a/sidechain/peer-fetch/src/untrusted_peer_fetch.rs +++ b/sidechain/peer-fetch/src/untrusted_peer_fetch.rs @@ -14,12 +14,11 @@ limitations under the License. */ - use crate::error::{Error, Result}; use itc_rpc_client::direct_client::{DirectApi, DirectClient as DirectWorkerApi}; use itp_node_api::{api_client::PalletTeerexApi, node_api_factory::CreateNodeApi}; use its_primitives::types::ShardIdentifier; -use std::sync::Arc; +use std::{marker::PhantomData, sync::Arc}; /// Trait to fetch untrusted peer servers. pub trait FetchUntrustedPeers { @@ -29,22 +28,26 @@ pub trait FetchUntrustedPeers { /// Fetches the untrusted peer servers /// FIXME: Should probably be combined with the peer fetch in /// service/src/worker.rs -pub struct UntrustedPeerFetcher { +pub struct UntrustedPeerFetcher { node_api_factory: Arc, + _phantom: PhantomData, } -impl UntrustedPeerFetcher +impl UntrustedPeerFetcher where - NodeApiFactory: CreateNodeApi + Send + Sync, + NodeApiFactory: CreateNodeApi + Send + Sync, + ParentchainApi: Clone, { pub fn new(node_api: Arc) -> Self { - UntrustedPeerFetcher { node_api_factory: node_api } + UntrustedPeerFetcher { node_api_factory: node_api, _phantom: Default::default() } } } -impl FetchUntrustedPeers for UntrustedPeerFetcher +impl FetchUntrustedPeers + for UntrustedPeerFetcher where - NodeApiFactory: CreateNodeApi + Send + Sync, + NodeApiFactory: CreateNodeApi + Send + Sync, + ParentchainApi: Clone + PalletTeerexApi, { fn get_untrusted_peer_url_of_shard(&self, shard: &ShardIdentifier) -> Result { let node_api = self.node_api_factory.create_api()?; From f0139f33a399d87bcf2e5d8f8a8bc52f50a340e7 Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Thu, 21 Nov 2024 15:54:23 +0100 Subject: [PATCH 02/23] introduce ParentchainRuntimeConfig for simpler generic parentchain support --- .../src/integritee/api_client_types.rs | 2 +- app-libs/parentchain-interface/src/lib.rs | 44 ++++++++- .../src/target_b/api_client_types.rs | 2 +- .../api-client-extensions/src/account.rs | 21 +++- service/src/account_funding.rs | 97 +++++++++++++------ 5 files changed, 131 insertions(+), 35 deletions(-) diff --git a/app-libs/parentchain-interface/src/integritee/api_client_types.rs b/app-libs/parentchain-interface/src/integritee/api_client_types.rs index 2513d23d92..d5c1ff0a77 100644 --- a/app-libs/parentchain-interface/src/integritee/api_client_types.rs +++ b/app-libs/parentchain-interface/src/integritee/api_client_types.rs @@ -91,5 +91,5 @@ mod api { pub type IntegriteeApi = Api; - impl ParentchainApiTrait for IntegriteeApi {} + // impl ParentchainApiTrait for IntegriteeApi {} } diff --git a/app-libs/parentchain-interface/src/lib.rs b/app-libs/parentchain-interface/src/lib.rs index cdea4b0079..2f6ef64e2f 100644 --- a/app-libs/parentchain-interface/src/lib.rs +++ b/app-libs/parentchain-interface/src/lib.rs @@ -18,20 +18,30 @@ #![cfg_attr(all(not(target_env = "sgx"), not(feature = "std")), no_std)] #![cfg_attr(target_env = "sgx", feature(rustc_private))] +extern crate core; #[cfg(all(not(feature = "std"), feature = "sgx"))] extern crate sgx_tstd as std; +use crate::integritee::api_client_types::Config; use codec::{Decode, Encode}; +use core::marker::PhantomData; +use itp_api_client_types::{ExtrinsicParams, GenericExtrinsicParams}; use itp_node_api::api_client::{AccountApi, ChainApi}; use itp_types::parentchain::{AccountId, Balance, Hash, Header, Index}; +use sp_core::{crypto::AccountId32, sr25519}; use sp_runtime::{ generic::{Block, UncheckedExtrinsic}, - MultiAddress, + MultiAddress, MultiSignature, }; use sp_version::GetRuntimeVersionAt; use substrate_api_client::{ - ac_primitives::Properties, extrinsic::BalancesExtrinsics, GetAccountInformation, GetBalance, - GetStorage, GetTransactionPayment, SubmitAndWatch, SubscribeEvents, SystemApi, + ac_primitives::{ + AccountData, AssetTipExtrinsicParams, BlakeTwo256, ExtrinsicSigner, Properties, + SubstrateBlock, SubstrateHeader, SubstrateOpaqueExtrinsic, + }, + extrinsic::BalancesExtrinsics, + GetAccountInformation, GetBalance, GetStorage, GetTransactionPayment, SubmitAndWatch, + SubscribeEvents, SystemApi, }; #[cfg(feature = "std")] @@ -80,3 +90,31 @@ pub trait ParentchainApiTrait: + SubmitAndWatch //+ GetRuntimeVersionAt>> { } + +#[derive(Decode, Encode, Clone, Eq, PartialEq, Debug)] +pub struct ParentchainRuntimeConfig { + _phantom: PhantomData, +} + +impl Config for ParentchainRuntimeConfig +where + u128: From, + Tip: Copy + Default + Encode, +{ + type Index = u32; + type BlockNumber = u32; + type Hash = Hash; + type AccountId = AccountId32; + type Address = MultiAddress; + type Signature = MultiSignature; + type Hasher = BlakeTwo256; + type Header = SubstrateHeader; + type AccountData = itp_types::AccountData; + type ExtrinsicParams = GenericExtrinsicParams; + type CryptoKey = sr25519::Pair; + type ExtrinsicSigner = ExtrinsicSigner; + type Block = SubstrateBlock; + type Balance = itp_types::Balance; + type ContractCurrency = u128; + type StakingBalance = u128; +} diff --git a/app-libs/parentchain-interface/src/target_b/api_client_types.rs b/app-libs/parentchain-interface/src/target_b/api_client_types.rs index 2580017de0..9399010701 100644 --- a/app-libs/parentchain-interface/src/target_b/api_client_types.rs +++ b/app-libs/parentchain-interface/src/target_b/api_client_types.rs @@ -87,5 +87,5 @@ mod api { pub type TargetBApi = Api; - impl ParentchainApiTrait for TargetBApi {} + // impl ParentchainApiTrait for TargetBApi {} } diff --git a/core-primitives/node-api/api-client-extensions/src/account.rs b/core-primitives/node-api/api-client-extensions/src/account.rs index 9b4e11216d..46e6129615 100644 --- a/core-primitives/node-api/api-client-extensions/src/account.rs +++ b/core-primitives/node-api/api-client-extensions/src/account.rs @@ -29,11 +29,30 @@ pub trait AccountApi { fn get_free_balance(&self, who: &Self::AccountId) -> ApiResult; } +// impl AccountApi for Api +// where +// Client: Request, +// ParentchainRuntimeConfig: +// Config::Balance>>, +// { +// type AccountId = ::AccountId; +// type Index = ::Index; +// type Balance = ::Balance; +// +// fn get_nonce_of(&self, who: &Self::AccountId) -> ApiResult { +// Ok(self.get_account_info(who)?.map(|info| info.nonce).unwrap_or_default()) +// } +// +// fn get_free_balance(&self, who: &Self::AccountId) -> ApiResult { +// Ok(self.get_account_data(who)?.map(|data| data.free).unwrap_or_default()) +// } +// } + impl AccountApi for Api where Client: Request, ParentchainRuntimeConfig: - Config::Balance>>, + Config, { type AccountId = ::AccountId; type Index = ::Index; diff --git a/service/src/account_funding.rs b/service/src/account_funding.rs index c761e039ca..9a9df3c332 100644 --- a/service/src/account_funding.rs +++ b/service/src/account_funding.rs @@ -17,12 +17,14 @@ use crate::error::{Error, ServiceResult}; use codec::Encode; -use ita_parentchain_interface::ParentchainApiTrait; +use ita_parentchain_interface::{ + integritee::api_client_types::Config, ParentchainApiTrait, ParentchainRuntimeConfig, +}; use itp_node_api::api_client::{AccountApi, ParentchainApi, TEEREX}; use itp_settings::worker::REGISTERING_FEE_FACTOR_FOR_INIT_FUNDS; use itp_types::{ parentchain::{AccountId, Balance, Index, ParentchainId}, - Moment, + AccountData, Moment, Nonce, }; use log::*; use sp_core::{ @@ -34,9 +36,10 @@ use sp_runtime::{traits::SignedExtension, MultiAddress, Saturating}; use std::{fmt::Display, thread, time::Duration}; use substrate_api_client::{ ac_compose_macros::{compose_extrinsic, compose_extrinsic_with_nonce}, - ac_primitives::Bytes, + ac_primitives::{Bytes, Config as ParentchainNodeConfig}, extrinsic::BalancesExtrinsics, - GetBalance, GetStorage, GetTransactionPayment, SubmitAndWatch, SystemApi, XtStatus, + rpc::{Request, Subscribe}, + Api, GetBalance, GetStorage, GetTransactionPayment, SubmitAndWatch, SystemApi, XtStatus, }; use teerex_primitives::SgxAttestationMethod; @@ -79,18 +82,22 @@ pub trait ParentchainAccountInfo { fn decimals(&self) -> ServiceResult; } -pub struct ParentchainAccountInfoProvider +pub struct ParentchainAccountInfoProvider where - ParentchainApi: ParentchainApiTrait, + u128: From, + Tip: Copy + Default + Encode, + Client: Request, { parentchain_id: ParentchainId, - node_api: ParentchainApi, + node_api: Api, Client>, account_and_role: AccountAndRole, } -impl ParentchainAccountInfo for ParentchainAccountInfoProvider +impl ParentchainAccountInfo for ParentchainAccountInfoProvider where - ParentchainApi: ParentchainApiTrait, + u128: From, + Tip: Copy + Default + Encode, + Client: Request, { fn free_balance(&self) -> ServiceResult { self.node_api @@ -116,13 +123,15 @@ where } } -impl ParentchainAccountInfoProvider +impl ParentchainAccountInfoProvider where - ParentchainApi: ParentchainApiTrait, + u128: From, + Tip: Copy + Default + Encode, + Client: Request, { pub fn new( parentchain_id: ParentchainId, - node_api: ParentchainApi, + node_api: Api, Client>, account_and_role: AccountAndRole, ) -> Self { ParentchainAccountInfoProvider { parentchain_id, node_api, account_and_role } @@ -132,12 +141,17 @@ where /// evaluate if the enclave should have more funds and how much more /// in --dev mode: let Alice pay for missing funds /// in production mode: wait for manual transfer before continuing -pub fn setup_reasonable_account_funding( - api: &ParentchainApi, +pub fn setup_reasonable_account_funding( + api: &Api, Client>, accountid: &AccountId32, parentchain_id: ParentchainId, is_development_mode: bool, -) -> ServiceResult<()> { +) -> ServiceResult<()> +where + u128: From, + Tip: Copy + Default + Encode, + Client: Request + Subscribe, +{ loop { let needed = estimate_funds_needed_to_run_for_a_while(api, accountid, parentchain_id)?; let free = api.get_free_balance(accountid)?; @@ -160,11 +174,16 @@ pub fn setup_reasonable_account_funding( } } -fn estimate_funds_needed_to_run_for_a_while( - api: &ParentchainApi, +fn estimate_funds_needed_to_run_for_a_while( + api: &Api, Client>, accountid: &AccountId32, parentchain_id: ParentchainId, -) -> ServiceResult { +) -> ServiceResult +where + u128: From, + Tip: Copy + Default + Encode, + Client: Request, +{ let existential_deposit = api.get_existential_deposit()?; info!("[{:?}] Existential deposit is = {:?}", parentchain_id, existential_deposit); @@ -213,10 +232,15 @@ fn estimate_funds_needed_to_run_for_a_while Ok(min_required_funds) } -pub fn estimate_fee( +pub fn estimate_fee( api: &ParentchainApi, encoded_extrinsic: Vec, -) -> Result { +) -> Result +where + u128: From, + Tip: Copy + Default + Encode, + Client: Request, +{ let reg_fee_details = api.get_fee_details(&encoded_extrinsic.into(), None)?; match reg_fee_details { Some(details) => match details.inclusion_fee { @@ -231,11 +255,16 @@ pub fn estimate_fee( } /// Alice sends some funds to the account. only for dev chains testing -fn bootstrap_funds_from_alice( - api: &ParentchainApi, +fn bootstrap_funds_from_alice( + api: &Api, Client>, accountid: &AccountId32, funding_amount: u128, -) -> Result<(), Error> { +) -> Result<(), Error> +where + u128: From, + Tip: Copy + Default + Encode, + Client: Request + Subscribe, +{ let alice = AccountKeyring::Alice.pair(); let alice_acc = AccountId32::from(*alice.public().as_array_ref()); @@ -271,9 +300,14 @@ fn bootstrap_funds_from_alice( } /// precise estimation of necessary funds to register a hardcoded number of proxies -pub fn shard_vault_initial_funds( - api: &ParentchainApi, -) -> Result { +pub fn shard_vault_initial_funds( + api: &Api, Client>, +) -> Result +where + u128: From, + Tip: Copy + Default + Encode, + Client: Request, +{ let proxy_deposit_base: Balance = api.get_constant("Proxy", "ProxyDepositBase")?; let proxy_deposit_factor: Balance = api.get_constant("Proxy", "ProxyDepositFactor")?; let transfer_fee = estimate_transfer_fee(api)?; @@ -283,9 +317,14 @@ pub fn shard_vault_initial_funds( } /// precise estimation of a single transfer fee -pub fn estimate_transfer_fee( - api: &ParentchainApi, -) -> Result { +pub fn estimate_transfer_fee( + api: &Api, Client>, +) -> Result +where + u128: From, + Tip: Copy + Default + Encode, + Client: Request, +{ let encoded_xt: Bytes = api .balance_transfer_allow_death(AccountId::from([0u8; 32]).into(), 1000000000000) .encode() From e10f166559238291f337c6c05f8a69d31ed528ab Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Fri, 22 Nov 2024 08:41:28 +0100 Subject: [PATCH 03/23] [onchain_bridge] worker_request compiles --- .../src/integritee/api_factory.rs | 16 +- .../src/target_a/api_factory.rs | 16 +- .../src/target_b/api_factory.rs | 16 +- .../node-api/api-client-types/src/lib.rs | 5 +- core-primitives/node-api/factory/src/lib.rs | 26 +-- service/src/ocall_bridge/component_factory.rs | 55 ++++-- .../src/ocall_bridge/worker_on_chain_ocall.rs | 171 +++++++++++++----- service/src/worker.rs | 39 ++-- .../peer-fetch/src/untrusted_peer_fetch.rs | 22 ++- 9 files changed, 251 insertions(+), 115 deletions(-) diff --git a/app-libs/parentchain-interface/src/integritee/api_factory.rs b/app-libs/parentchain-interface/src/integritee/api_factory.rs index 333868bce6..325551da3e 100644 --- a/app-libs/parentchain-interface/src/integritee/api_factory.rs +++ b/app-libs/parentchain-interface/src/integritee/api_factory.rs @@ -16,8 +16,9 @@ */ -use super::api_client_types::IntegriteeApi; -use itp_api_client_types::TungsteniteRpcClient; +use super::api_client_types::IntegriteeTip; +use crate::ParentchainRuntimeConfig; +use itp_api_client_types::{Api, TungsteniteRpcClient}; use itp_node_api::node_api_factory::{CreateNodeApi, NodeApiFactoryError, Result}; use sp_core::sr25519; @@ -33,12 +34,15 @@ impl IntegriteeNodeApiFactory { } } -impl CreateNodeApi for IntegriteeNodeApiFactory { - fn create_api(&self) -> Result { +impl CreateNodeApi, TungsteniteRpcClient> + for IntegriteeNodeApiFactory +{ + fn create_api( + &self, + ) -> Result, TungsteniteRpcClient>> { let rpc_client = TungsteniteRpcClient::new(self.node_url.as_str(), 5) .map_err(NodeApiFactoryError::FailedToCreateRpcClient)?; - let mut api = - IntegriteeApi::new(rpc_client).map_err(NodeApiFactoryError::FailedToCreateNodeApi)?; + let mut api = Api::new(rpc_client).map_err(NodeApiFactoryError::FailedToCreateNodeApi)?; api.set_signer(self.signer.clone().into()); Ok(api) } diff --git a/app-libs/parentchain-interface/src/target_a/api_factory.rs b/app-libs/parentchain-interface/src/target_a/api_factory.rs index 1955a26f01..3871003124 100644 --- a/app-libs/parentchain-interface/src/target_a/api_factory.rs +++ b/app-libs/parentchain-interface/src/target_a/api_factory.rs @@ -16,8 +16,9 @@ */ -use super::api_client_types::TargetAApi; -use itp_api_client_types::TungsteniteRpcClient; +use super::api_client_types::TargetATip; +use crate::ParentchainRuntimeConfig; +use itp_api_client_types::{Api, TungsteniteRpcClient}; use itp_node_api::node_api_factory::{CreateNodeApi, NodeApiFactoryError, Result}; use sp_core::sr25519; @@ -33,12 +34,15 @@ impl TargetANodeApiFactory { } } -impl CreateNodeApi for TargetANodeApiFactory { - fn create_api(&self) -> Result { +impl CreateNodeApi, TungsteniteRpcClient> + for TargetANodeApiFactory +{ + fn create_api( + &self, + ) -> Result, TungsteniteRpcClient>> { let rpc_client = TungsteniteRpcClient::new(self.node_url.as_str(), 5) .map_err(NodeApiFactoryError::FailedToCreateRpcClient)?; - let mut api = - TargetAApi::new(rpc_client).map_err(NodeApiFactoryError::FailedToCreateNodeApi)?; + let mut api = Api::new(rpc_client).map_err(NodeApiFactoryError::FailedToCreateNodeApi)?; api.set_signer(self.signer.clone().into()); Ok(api) } diff --git a/app-libs/parentchain-interface/src/target_b/api_factory.rs b/app-libs/parentchain-interface/src/target_b/api_factory.rs index 691e6de27d..90e75bfdd2 100644 --- a/app-libs/parentchain-interface/src/target_b/api_factory.rs +++ b/app-libs/parentchain-interface/src/target_b/api_factory.rs @@ -16,8 +16,9 @@ */ -use super::api_client_types::TargetBApi; -use itp_api_client_types::TungsteniteRpcClient; +use super::api_client_types::TargetBTip; +use crate::ParentchainRuntimeConfig; +use itp_api_client_types::{Api, TungsteniteRpcClient}; use itp_node_api::node_api_factory::{CreateNodeApi, NodeApiFactoryError, Result}; use sp_core::sr25519; @@ -33,12 +34,15 @@ impl TargetBNodeApiFactory { } } -impl CreateNodeApi for TargetBNodeApiFactory { - fn create_api(&self) -> Result { +impl CreateNodeApi, TungsteniteRpcClient> + for TargetBNodeApiFactory +{ + fn create_api( + &self, + ) -> Result, TungsteniteRpcClient>> { let rpc_client = TungsteniteRpcClient::new(self.node_url.as_str(), 5) .map_err(NodeApiFactoryError::FailedToCreateRpcClient)?; - let mut api = - TargetBApi::new(rpc_client).map_err(NodeApiFactoryError::FailedToCreateNodeApi)?; + let mut api = Api::new(rpc_client).map_err(NodeApiFactoryError::FailedToCreateNodeApi)?; api.set_signer(self.signer.clone().into()); Ok(api) } diff --git a/core-primitives/node-api/api-client-types/src/lib.rs b/core-primitives/node-api/api-client-types/src/lib.rs index b82b0c376b..8107ab7f5f 100644 --- a/core-primitives/node-api/api-client-types/src/lib.rs +++ b/core-primitives/node-api/api-client-types/src/lib.rs @@ -45,7 +45,10 @@ pub use substrate_api_client::{ // traits from the api-client pub mod traits { - pub use substrate_api_client::{GetAccountInformation, GetChainInfo, GetStorage}; + pub use substrate_api_client::{ + rpc::{Request, Subscribe}, + GetAccountInformation, GetChainInfo, GetStorage, + }; } pub type ParentchainPlainTip = PlainTip; diff --git a/core-primitives/node-api/factory/src/lib.rs b/core-primitives/node-api/factory/src/lib.rs index 2882fe9482..89186855c0 100644 --- a/core-primitives/node-api/factory/src/lib.rs +++ b/core-primitives/node-api/factory/src/lib.rs @@ -15,13 +15,13 @@ limitations under the License. */ - -use itp_api_client_types::{ParentchainApi, TungsteniteRpcClient}; +use itp_api_client_types::{traits::Request, Api, Config, ParentchainApi, TungsteniteRpcClient}; use sp_core::sr25519; +use std::marker::PhantomData; /// Trait to create a node API, based on a node URL and signer. -pub trait CreateNodeApi { - fn create_api(&self) -> Result; +pub trait CreateNodeApi { + fn create_api(&self) -> Result>; } /// Node API factory error. @@ -50,23 +50,27 @@ impl From for NodeApiFactoryError { pub type Result = std::result::Result; /// Node API factory implementation. -pub struct NodeApiFactory { +pub struct NodeApiFactory { node_url: String, signer: sr25519::Pair, + _phantom: PhantomData<(NodeConfig, Client)>, } -impl NodeApiFactory { +impl NodeApiFactory { pub fn new(url: String, signer: sr25519::Pair) -> Self { - NodeApiFactory { node_url: url, signer } + NodeApiFactory { node_url: url, signer, _phantom: Default::default() } } } -impl CreateNodeApi for NodeApiFactory { - fn create_api(&self) -> Result { +impl CreateNodeApi + for NodeApiFactory +where + ::ExtrinsicSigner: From, +{ + fn create_api(&self) -> Result> { let rpc_client = TungsteniteRpcClient::new(self.node_url.as_str(), 5) .map_err(NodeApiFactoryError::FailedToCreateRpcClient)?; - let mut api = - ParentchainApi::new(rpc_client).map_err(NodeApiFactoryError::FailedToCreateNodeApi)?; + let mut api = Api::new(rpc_client).map_err(NodeApiFactoryError::FailedToCreateNodeApi)?; api.set_signer(self.signer.clone().into()); Ok(api) } diff --git a/service/src/ocall_bridge/component_factory.rs b/service/src/ocall_bridge/component_factory.rs index 403f0a453f..4b5053b086 100644 --- a/service/src/ocall_bridge/component_factory.rs +++ b/service/src/ocall_bridge/component_factory.rs @@ -32,18 +32,23 @@ use crate::{ sync_block_broadcaster::BroadcastBlocks, worker_peers_updater::UpdateWorkerPeers, }; +use itp_api_client_types::{Config, Request}; use itp_enclave_api::remote_attestation::RemoteAttestationCallBacks; -use itp_node_api::node_api_factory::CreateNodeApi; +use itp_node_api::node_api_factory::{CreateNodeApi, NodeApiFactory}; +use itp_types::{AccountId, BlockHash, Nonce}; use its_peer_fetch::FetchBlocksFromPeer; use its_primitives::types::block::SignedBlock as SignedSidechainBlock; use its_storage::BlockStorage; use std::{path::Path, sync::Arc}; +use substrate_api_client::rpc::TungsteniteRpcClient; /// Concrete implementation, should be moved out of the OCall Bridge, into the worker /// since the OCall bridge itself should not know any concrete types to ensure /// our dependency graph is worker -> ocall bridge pub struct OCallBridgeComponentFactory< - NodeApi, + IntegriteeRuntimeConfig: Config, + TargetARuntimeConfig: Config, + TargetBRuntimeConfig: Config, Broadcaster, EnclaveApi, Storage, @@ -52,9 +57,11 @@ pub struct OCallBridgeComponentFactory< TokioHandle, MetricsReceiver, > { - integritee_rpc_api_factory: Arc, - target_a_parentchain_rpc_api_factory: Option>, - target_b_parentchain_rpc_api_factory: Option>, + integritee_rpc_api_factory: Arc>, + target_a_parentchain_rpc_api_factory: + Option>>, + target_b_parentchain_rpc_api_factory: + Option>>, block_broadcaster: Arc, enclave_api: Arc, block_storage: Arc, @@ -66,7 +73,9 @@ pub struct OCallBridgeComponentFactory< } impl< - NodeApi, + IntegriteeRuntimeConfig: Config, + TargetARuntimeConfig: Config, + TargetBRuntimeConfig: Config, Broadcaster, EnclaveApi, Storage, @@ -76,7 +85,9 @@ impl< MetricsReceiver, > OCallBridgeComponentFactory< - NodeApi, + IntegriteeRuntimeConfig, + TargetARuntimeConfig, + TargetBRuntimeConfig, Broadcaster, EnclaveApi, Storage, @@ -88,9 +99,15 @@ impl< { #[allow(clippy::too_many_arguments)] pub fn new( - integritee_rpc_api_factory: Arc, - target_a_parentchain_rpc_api_factory: Option>, - target_b_parentchain_rpc_api_factory: Option>, + integritee_rpc_api_factory: Arc< + NodeApiFactory, + >, + target_a_parentchain_rpc_api_factory: Option< + Arc>, + >, + target_b_parentchain_rpc_api_factory: Option< + Arc>, + >, block_broadcaster: Arc, enclave_api: Arc, block_storage: Arc, @@ -117,7 +134,9 @@ impl< } impl< - NodeApi, + IntegriteeRuntimeConfig, + TargetARuntimeConfig, + TargetBRuntimeConfig, Broadcaster, EnclaveApi, Storage, @@ -127,7 +146,9 @@ impl< MetricsReceiver, > GetOCallBridgeComponents for OCallBridgeComponentFactory< - NodeApi, + IntegriteeRuntimeConfig, + TargetARuntimeConfig, + TargetBRuntimeConfig, Broadcaster, EnclaveApi, Storage, @@ -135,9 +156,13 @@ impl< PeerBlockFetcher, TokioHandle, MetricsReceiver, - > -where - NodeApi: CreateNodeApi + 'static, + > where + IntegriteeRuntimeConfig: Config, + TargetARuntimeConfig: Config, + TargetBRuntimeConfig: Config, + ::ExtrinsicSigner: From, + ::ExtrinsicSigner: From, + ::ExtrinsicSigner: From, Broadcaster: BroadcastBlocks + 'static, EnclaveApi: RemoteAttestationCallBacks + 'static, Storage: BlockStorage + 'static, diff --git a/service/src/ocall_bridge/worker_on_chain_ocall.rs b/service/src/ocall_bridge/worker_on_chain_ocall.rs index ee3a618498..68208929e7 100644 --- a/service/src/ocall_bridge/worker_on_chain_ocall.rs +++ b/service/src/ocall_bridge/worker_on_chain_ocall.rs @@ -23,13 +23,16 @@ use ita_parentchain_interface::{ integritee::{api_client_types::IntegriteeApi, api_factory::IntegriteeNodeApiFactory}, target_a::{api_client_types::TargetAApi, api_factory::TargetANodeApiFactory}, target_b::{api_client_types::TargetBApi, api_factory::TargetBNodeApiFactory}, - ParentchainApiTrait, + ParentchainApiTrait, ParentchainRuntimeConfig, +}; +use itp_api_client_types::{ParentchainApi, Request}; +use itp_node_api::{ + api_client::{AccountApi, Config}, + node_api_factory::{CreateNodeApi, NodeApiFactory}, }; -use itp_api_client_types::ParentchainApi; -use itp_node_api::{api_client::AccountApi, node_api_factory::CreateNodeApi}; use itp_types::{ - parentchain::{Header as ParentchainHeader, ParentchainId}, - DigestItem, WorkerRequest, WorkerResponse, + parentchain::{AccountId, Header as ParentchainHeader, ParentchainId}, + BlockHash, DigestItem, Nonce, WorkerRequest, WorkerResponse, }; use log::*; use sp_core::blake2_256; @@ -44,21 +47,38 @@ use std::{ use substrate_api_client::{ ac_primitives, ac_primitives::{serde_impls::StorageKey, SubstrateHeader}, - GetAccountInformation, GetChainInfo, GetStorage, SubmitAndWatch, SubmitExtrinsic, XtStatus, + rpc::TungsteniteRpcClient, + Api, GetAccountInformation, GetChainInfo, GetStorage, SubmitAndWatch, SubmitExtrinsic, + XtStatus, }; -pub struct WorkerOnChainOCall { - integritee_api_factory: Arc, - target_a_parentchain_api_factory: Option>, - target_b_parentchain_api_factory: Option>, +pub struct WorkerOnChainOCall< + IntegriteeConfig: Config, + TargetAConfig: Config, + TargetBConfig: Config, + Client: Request, +> { + integritee_api_factory: Arc>, + target_a_parentchain_api_factory: Option>>, + target_b_parentchain_api_factory: Option>>, log_dir: Arc, } -impl WorkerOnChainOCall { +impl + WorkerOnChainOCall +where + ::ExtrinsicSigner: From, + ::ExtrinsicSigner: From, + ::ExtrinsicSigner: From, +{ pub fn new( - integritee_api_factory: Arc, - target_a_parentchain_api_factory: Option>, - target_b_parentchain_api_factory: Option>, + integritee_api_factory: Arc>, + target_a_parentchain_api_factory: Option< + Arc>, + >, + target_b_parentchain_api_factory: Option< + Arc>, + >, log_dir: Arc, ) -> Self { WorkerOnChainOCall { @@ -70,41 +90,49 @@ impl WorkerOnChainOCall { } } -impl WorkerOnChainOCall { - pub fn create_api(&self, parentchain_id: ParentchainId) -> OCallBridgeResult { - Ok(match parentchain_id { - ParentchainId::Integritee => self.integritee_api_factory.create_api()?, - ParentchainId::TargetA => self - .target_a_parentchain_api_factory - .as_ref() - .ok_or(OCallBridgeError::TargetAParentchainNotInitialized) - .and_then(|f| f.create_api().map_err(Into::into))?, - ParentchainId::TargetB => self - .target_b_parentchain_api_factory - .as_ref() - .ok_or(OCallBridgeError::TargetBParentchainNotInitialized) - .and_then(|f| f.create_api().map_err(Into::into))?, - }) +impl< + IntegriteeConfig: Config, + TargetAConfig: Config, + TargetBConfig: Config, + > WorkerOnChainOCall +where + ::ExtrinsicSigner: From, + ::ExtrinsicSigner: From, + ::ExtrinsicSigner: From, +{ + pub fn create_integritee_api( + &self, + ) -> OCallBridgeResult> { + Ok(self.integritee_api_factory.create_api()?) } -} -impl WorkerOnChainBridge for WorkerOnChainOCall { - fn worker_request( + pub fn create_target_a_api( &self, - request: Vec, - parentchain_id: Vec, - ) -> OCallBridgeResult> { - debug!(" Entering ocall_worker_request"); - - let requests: Vec = Decode::decode(&mut request.as_slice())?; - if requests.is_empty() { - debug!("requests is empty, returning empty vector"); - return Ok(Vec::::new().encode()) - } + ) -> OCallBridgeResult> { + Ok(self + .target_a_parentchain_api_factory + .as_ref() + .ok_or(OCallBridgeError::TargetAParentchainNotInitialized) + .and_then(|f| f.create_api().map_err(Into::into))?) + } - let parentchain_id = ParentchainId::decode(&mut parentchain_id.as_slice())?; + pub fn create_target_b_api( + &self, + ) -> OCallBridgeResult> { + Ok(self + .target_b_parentchain_api_factory + .as_ref() + .ok_or(OCallBridgeError::TargetBParentchainNotInitialized) + .and_then(|f| f.create_api().map_err(Into::into))?) + } - let api = self.create_api(parentchain_id)?; + fn handle_requests< + Config: itp_api_client_types::Config, + >( + &self, + api: &Api, + requests: Vec, + ) -> OCallBridgeResult>>> { let last_finalized = api.get_finalized_head().map_err(|_| OCallBridgeError::NodeApiError)?; let header = if let Some(header) = @@ -113,7 +141,7 @@ impl WorkerOnChainBridge for WorkerOnChainOCall { header } else { warn!("failed to fetch parentchain header. can't answer WorkerRequest"); - return Ok(Vec::::new().encode()) + return Ok(vec![]) }; let resp: Vec>> = requests @@ -139,6 +167,59 @@ impl WorkerOnChainBridge for WorkerOnChainOCall { }) .collect(); + Ok(resp) + } +} + +impl< + IntegriteeConfig: Config, + TargetAConfig: Config, + TargetBConfig: Config, + > WorkerOnChainBridge + for WorkerOnChainOCall +where + ::ExtrinsicSigner: From, + ::ExtrinsicSigner: From, + ::ExtrinsicSigner: From, +{ + fn worker_request( + &self, + request: Vec, + parentchain_id: Vec, + ) -> OCallBridgeResult> { + debug!(" Entering ocall_worker_request"); + + let requests: Vec = Decode::decode(&mut request.as_slice())?; + if requests.is_empty() { + debug!("requests is empty, returning empty vector"); + return Ok(Vec::::new().encode()) + } + + let parentchain_id = ParentchainId::decode(&mut parentchain_id.as_slice())?; + + let resp = match parentchain_id { + ParentchainId::Integritee => { + let api = self.integritee_api_factory.create_api()?; + self.handle_requests(&api, requests)? + }, + ParentchainId::TargetA => { + let api = self + .target_a_parentchain_api_factory + .as_ref() + .ok_or(OCallBridgeError::TargetAParentchainNotInitialized)? + .create_api()?; + self.handle_requests(&api, requests)? + }, + ParentchainId::TargetB => { + let api = self + .target_b_parentchain_api_factory + .as_ref() + .ok_or(OCallBridgeError::TargetBParentchainNotInitialized)? + .create_api()?; + self.handle_requests(&api, requests)? + }, + }; + let encoded_response: Vec = resp.encode(); Ok(encoded_response) diff --git a/service/src/worker.rs b/service/src/worker.rs index adb6d76f5d..289863866c 100644 --- a/service/src/worker.rs +++ b/service/src/worker.rs @@ -23,7 +23,11 @@ use crate::{config::Config, error::Error, initialized_service::TrackInitializati use async_trait::async_trait; use ita_parentchain_interface::ParentchainApiTrait; use itc_rpc_client::direct_client::{DirectApi, DirectClient as DirectWorkerApi}; -use itp_node_api::{api_client::PalletTeerexApi, node_api_factory::CreateNodeApi}; +use itp_api_client_types::{Config as NodeRuntimeConfig, Request}; +use itp_node_api::{ + api_client::PalletTeerexApi, + node_api_factory::{CreateNodeApi, NodeApiFactory}, +}; use itp_types::ShardIdentifier; use itp_utils::ToHexPrefixed; use its_primitives::types::SignedBlock as SignedSidechainBlock; @@ -42,23 +46,28 @@ use url::Url as UrlType; pub type WorkerResult = Result; pub type Url = String; -pub struct Worker { +pub struct Worker< + Config, + NodeConfig: NodeRuntimeConfig, + Client: Request, + Enclave, + InitializationHandler, +> { _config: Config, // unused yet, but will be used when more methods are migrated to the worker _enclave_api: Arc, - node_api_factory: Arc, + node_api_factory: Arc>, initialization_handler: Arc, peers: RwLock>, - _phantom: PhantomData, } -impl - Worker +impl + Worker { pub fn new( config: Config, enclave_api: Arc, - node_api_factory: Arc, + node_api_factory: Arc>, initialization_handler: Arc, peers: Vec, ) -> Self { @@ -79,11 +88,11 @@ pub trait AsyncBlockBroadcaster { } #[async_trait] -impl AsyncBlockBroadcaster - for Worker +impl AsyncBlockBroadcaster + for Worker where - NodeApiFactory: CreateNodeApi + Send + Sync, - NodeApi: ParentchainApiTrait, + NodeConfig: NodeRuntimeConfig, + Client: Request, Enclave: Send + Sync, InitializationHandler: TrackInitialization + Send + Sync, { @@ -141,11 +150,11 @@ pub trait UpdatePeers { } } -impl UpdatePeers - for Worker +impl UpdatePeers + for Worker where - NodeApiFactory: CreateNodeApi + Send + Sync, - NodeApi: ParentchainApiTrait, + NodeConfig: NodeRuntimeConfig, + Client: Request, { fn search_peers(&self, shard: ShardIdentifier) -> WorkerResult> { let node_api = self diff --git a/sidechain/peer-fetch/src/untrusted_peer_fetch.rs b/sidechain/peer-fetch/src/untrusted_peer_fetch.rs index 592555cc40..c220adb0c7 100644 --- a/sidechain/peer-fetch/src/untrusted_peer_fetch.rs +++ b/sidechain/peer-fetch/src/untrusted_peer_fetch.rs @@ -16,7 +16,10 @@ */ use crate::error::{Error, Result}; use itc_rpc_client::direct_client::{DirectApi, DirectClient as DirectWorkerApi}; -use itp_node_api::{api_client::PalletTeerexApi, node_api_factory::CreateNodeApi}; +use itp_node_api::{ + api_client::{traits::Request, Config, PalletTeerexApi}, + node_api_factory::CreateNodeApi, +}; use its_primitives::types::ShardIdentifier; use std::{marker::PhantomData, sync::Arc}; @@ -28,26 +31,25 @@ pub trait FetchUntrustedPeers { /// Fetches the untrusted peer servers /// FIXME: Should probably be combined with the peer fetch in /// service/src/worker.rs -pub struct UntrustedPeerFetcher { +pub struct UntrustedPeerFetcher { node_api_factory: Arc, - _phantom: PhantomData, + _phantom: PhantomData<(NodeConfig, Client)>, } -impl UntrustedPeerFetcher +impl + UntrustedPeerFetcher where - NodeApiFactory: CreateNodeApi + Send + Sync, - ParentchainApi: Clone, + NodeApiFactory: CreateNodeApi + Send + Sync, { pub fn new(node_api: Arc) -> Self { UntrustedPeerFetcher { node_api_factory: node_api, _phantom: Default::default() } } } -impl FetchUntrustedPeers - for UntrustedPeerFetcher +impl FetchUntrustedPeers + for UntrustedPeerFetcher where - NodeApiFactory: CreateNodeApi + Send + Sync, - ParentchainApi: Clone + PalletTeerexApi, + NodeApiFactory: CreateNodeApi + Send + Sync, { fn get_untrusted_peer_url_of_shard(&self, shard: &ShardIdentifier) -> Result { let node_api = self.node_api_factory.create_api()?; From 005db8e1f6580b972760629eb3aae6b682356b3e Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Fri, 22 Nov 2024 08:53:22 +0100 Subject: [PATCH 04/23] [onchain_bridge] send_to_parentchain compiles --- .../src/ocall_bridge/worker_on_chain_ocall.rs | 142 ++++++++++++------ 1 file changed, 96 insertions(+), 46 deletions(-) diff --git a/service/src/ocall_bridge/worker_on_chain_ocall.rs b/service/src/ocall_bridge/worker_on_chain_ocall.rs index 68208929e7..8dacbbb69a 100644 --- a/service/src/ocall_bridge/worker_on_chain_ocall.rs +++ b/service/src/ocall_bridge/worker_on_chain_ocall.rs @@ -169,6 +169,54 @@ where Ok(resp) } + + fn submit_extrinsics_to_parentchain< + Config: itp_api_client_types::Config, + >( + &self, + api: &Api, + extrinsics: Vec, + parentchain_id: ParentchainId, + await_each_inclusion: bool, + ) -> OCallBridgeResult<()> { + debug!( + "Enclave wants to send {} extrinsics to parentchain: {:?}. await each inclusion: {:?}", + extrinsics.len(), + parentchain_id, + await_each_inclusion + ); + log_extrinsics_to_file(self.log_dir.clone(), parentchain_id, extrinsics.clone()) + .map_err(|e| { + error!("Error logging extrinsic to disk: {}", e); + e + }) + .unwrap_or_default(); + + for call in extrinsics.into_iter() { + if await_each_inclusion { + if let Err(e) = api.submit_and_watch_opaque_extrinsic_until( + &call.encode().into(), + XtStatus::InBlock, + ) { + error!( + "Could not send extrinsic to {:?}: {:?}, error: {:?}", + parentchain_id, + serde_json::to_string(&call), + e + ); + } + } else if let Err(e) = api.submit_opaque_extrinsic(&call.encode().into()) { + error!( + "Could not send extrinsic to {:?}: {:?}, error: {:?}", + parentchain_id, + serde_json::to_string(&call), + e + ); + } + } + + Ok(()) + } } impl< @@ -229,60 +277,62 @@ where &self, extrinsics_encoded: Vec, parentchain_id: Vec, - await_each_inlcusion: bool, + await_each_inclusion: bool, ) -> OCallBridgeResult<()> { - // TODO: improve error handling, using a mut status is not good design? - let mut status: OCallBridgeResult<()> = Ok(()); - let extrinsics: Vec = match Decode::decode(&mut extrinsics_encoded.as_slice()) { Ok(calls) => calls, - Err(_) => { - status = Err(OCallBridgeError::SendExtrinsicsToParentchain( + Err(_) => + return Err(OCallBridgeError::SendExtrinsicsToParentchain( "Could not decode extrinsics".to_string(), - )); - Default::default() - }, + )), }; - if !extrinsics.is_empty() { - let parentchain_id = ParentchainId::decode(&mut parentchain_id.as_slice())?; - debug!( - "Enclave wants to send {} extrinsics to parentchain: {:?}. await each inclusion: {:?}", - extrinsics.len(), - parentchain_id, await_each_inlcusion - ); - log_extrinsics_to_file(self.log_dir.clone(), parentchain_id, extrinsics.clone()) - .map_err(|e| { - error!("Error logging extrinsic to disk: {}", e); - e - }) - .unwrap_or_default(); - let api = self.create_api(parentchain_id)?; - for call in extrinsics.into_iter() { - if await_each_inlcusion { - if let Err(e) = api.submit_and_watch_opaque_extrinsic_until( - &call.encode().into(), - XtStatus::InBlock, - ) { - error!( - "Could not send extrinsic to {:?}: {:?}, error: {:?}", - parentchain_id, - serde_json::to_string(&call), - e - ); - } - } else if let Err(e) = api.submit_opaque_extrinsic(&call.encode().into()) { - error!( - "Could not send extrinsic to {:?}: {:?}, error: {:?}", - parentchain_id, - serde_json::to_string(&call), - e - ); - } - } + if extrinsics.is_empty() { + return Ok(()) } - status + + let parentchain_id = ParentchainId::decode(&mut parentchain_id.as_slice())?; + + match parentchain_id { + ParentchainId::Integritee => { + let api = self.integritee_api_factory.create_api()?; + self.submit_extrinsics_to_parentchain( + &api, + extrinsics, + parentchain_id, + await_each_inclusion, + )? + }, + ParentchainId::TargetA => { + let api = self + .target_a_parentchain_api_factory + .as_ref() + .ok_or(OCallBridgeError::TargetAParentchainNotInitialized)? + .create_api()?; + self.submit_extrinsics_to_parentchain( + &api, + extrinsics, + parentchain_id, + await_each_inclusion, + )? + }, + ParentchainId::TargetB => { + let api = self + .target_b_parentchain_api_factory + .as_ref() + .ok_or(OCallBridgeError::TargetBParentchainNotInitialized)? + .create_api()?; + self.submit_extrinsics_to_parentchain( + &api, + extrinsics, + parentchain_id, + await_each_inclusion, + )? + }, + }; + + Ok(()) } } From bddffe6cb135c10139a1fa8514f934edc91c7c59 Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Fri, 22 Nov 2024 09:25:18 +0100 Subject: [PATCH 05/23] [onchain_bridge] stuck at prometheus metrics --- .../src/integritee/api_client_types.rs | 8 +- .../src/target_a/api_client_types.rs | 8 +- .../src/target_b/api_client_types.rs | 10 +- service/src/main_impl.rs | 97 +++++++++++-------- 4 files changed, 71 insertions(+), 52 deletions(-) diff --git a/app-libs/parentchain-interface/src/integritee/api_client_types.rs b/app-libs/parentchain-interface/src/integritee/api_client_types.rs index d5c1ff0a77..1e873f77be 100644 --- a/app-libs/parentchain-interface/src/integritee/api_client_types.rs +++ b/app-libs/parentchain-interface/src/integritee/api_client_types.rs @@ -77,10 +77,10 @@ use itp_types::parentchain::Header; #[cfg(feature = "std")] mod api { - use super::IntegriteeRuntimeConfig; - use crate::ParentchainApiTrait; + use crate::ParentchainRuntimeConfig; + use itp_api_client_types::PlainTip; use itp_node_api::api_client::AccountApi; - use itp_types::parentchain::{AccountId, Balance, Hash, Index}; + use itp_types::parentchain::Balance; pub use substrate_api_client::{ api::Error as ApiClientError, rpc::{tungstenite_client::TungsteniteRpcClient, Error as RpcClientError}, @@ -89,7 +89,7 @@ mod api { Api, GetBalance, GetChainInfo, GetStorage, GetTransactionPayment, SubscribeEvents, }; - pub type IntegriteeApi = Api; + pub type IntegriteeApi = Api>, TungsteniteRpcClient>; // impl ParentchainApiTrait for IntegriteeApi {} } diff --git a/app-libs/parentchain-interface/src/target_a/api_client_types.rs b/app-libs/parentchain-interface/src/target_a/api_client_types.rs index 1d3ed7398e..92be945287 100644 --- a/app-libs/parentchain-interface/src/target_a/api_client_types.rs +++ b/app-libs/parentchain-interface/src/target_a/api_client_types.rs @@ -73,10 +73,10 @@ pub use api::*; #[cfg(feature = "std")] mod api { - use super::TargetARuntimeConfig; - use crate::ParentchainApiTrait; + use crate::ParentchainRuntimeConfig; + use itp_api_client_types::PlainTip; use itp_node_api::api_client::AccountApi; - use itp_types::parentchain::{AccountId, Balance, Hash, Index}; + use itp_types::parentchain::Balance; pub use substrate_api_client::{ api::Error as ApiClientError, rpc::{tungstenite_client::TungsteniteRpcClient, Error as RpcClientError}, @@ -85,7 +85,7 @@ mod api { Api, GetBalance, GetChainInfo, GetStorage, GetTransactionPayment, SubscribeEvents, }; - pub type TargetAApi = Api; + pub type TargetAApi = Api>, TungsteniteRpcClient>; //impl ParentchainApiTrait for TargetAApi {} } diff --git a/app-libs/parentchain-interface/src/target_b/api_client_types.rs b/app-libs/parentchain-interface/src/target_b/api_client_types.rs index 9399010701..26472604ef 100644 --- a/app-libs/parentchain-interface/src/target_b/api_client_types.rs +++ b/app-libs/parentchain-interface/src/target_b/api_client_types.rs @@ -73,10 +73,10 @@ pub use api::*; #[cfg(feature = "std")] mod api { - use super::TargetBRuntimeConfig; - use crate::ParentchainApiTrait; - use itp_node_api::api_client::{AccountApi, ApiResult}; - use itp_types::parentchain::{AccountId, Balance, Hash, Index}; + use crate::ParentchainRuntimeConfig; + use itp_api_client_types::PlainTip; + use itp_node_api::api_client::AccountApi; + use itp_types::parentchain::Balance; pub use substrate_api_client::{ api::Error as ApiClientError, rpc::{tungstenite_client::TungsteniteRpcClient, Error as RpcClientError}, @@ -85,7 +85,7 @@ mod api { Api, GetBalance, GetChainInfo, GetStorage, GetTransactionPayment, SubscribeEvents, }; - pub type TargetBApi = Api; + pub type TargetBApi = Api>, TungsteniteRpcClient>; // impl ParentchainApiTrait for TargetBApi {} } diff --git a/service/src/main_impl.rs b/service/src/main_impl.rs index 98b0f984c6..cdf580bf49 100644 --- a/service/src/main_impl.rs +++ b/service/src/main_impl.rs @@ -54,8 +54,10 @@ use regex::Regex; use sgx_types::*; use sp_runtime::traits::{Header as HeaderT, IdentifyAccount}; use substrate_api_client::{ - api::XtStatus, rpc::HandleSubscription, GetAccountInformation, GetBalance, GetChainInfo, - GetStorage, SubmitAndWatch, SubscribeChain, SubscribeEvents, + api::XtStatus, + rpc::{HandleSubscription, Request, Subscribe}, + Api, GetAccountInformation, GetBalance, GetChainInfo, GetStorage, SubmitAndWatch, + SubscribeChain, SubscribeEvents, }; use teerex_primitives::{AnySigner, MultiEnclave}; @@ -74,7 +76,7 @@ use crate::{ use enclave_bridge_primitives::ShardIdentifier; use ita_parentchain_interface::{ integritee::{api_client_types::IntegriteeApi, api_factory::IntegriteeNodeApiFactory}, - ParentchainApiTrait, + ParentchainApiTrait, ParentchainRuntimeConfig, }; use itc_parentchain::primitives::ParentchainId; use itp_node_api::api_client::ChainApi; @@ -512,12 +514,9 @@ fn start_worker( .expect("our enclave should be registered at this point"); trace!("verified that our enclave is registered: {:?}", my_enclave); - let (we_are_primary_validateer, re_init_parentchain_needed) = match integritee_rpc_api - .primary_worker_for_shard(shard, None) - .unwrap() - { - Some(primary_enclave) => - match primary_enclave.instance_signer() { + let (we_are_primary_validateer, re_init_parentchain_needed) = + match integritee_rpc_api.primary_worker_for_shard(shard, None).unwrap() { + Some(primary_enclave) => match primary_enclave.instance_signer() { AnySigner::Known(MultiSigner::Ed25519(primary)) => if primary.encode() == tee_accountid.encode() { println!("We are primary worker on this shard and we have been previously running."); @@ -552,24 +551,24 @@ fn start_worker( ); }, }, - None => { - println!("We are the primary worker on this shard and the shard is untouched. Will initialize it"); - enclave.init_shard(shard.encode()).unwrap(); - if WorkerModeProvider::worker_mode() != WorkerMode::Teeracle { - enclave - .init_shard_creation_parentchain_header( - shard, - &ParentchainId::Integritee, - ®ister_enclave_xt_header, - ) - .unwrap(); - debug!("shard config should be initialized on integritee network now"); - (true, true) - } else { - (true, false) - } - }, - }; + None => { + println!("We are the primary worker on this shard and the shard is untouched. Will initialize it"); + enclave.init_shard(shard.encode()).unwrap(); + if WorkerModeProvider::worker_mode() != WorkerMode::Teeracle { + enclave + .init_shard_creation_parentchain_header( + shard, + &ParentchainId::Integritee, + ®ister_enclave_xt_header, + ) + .unwrap(); + debug!("shard config should be initialized on integritee network now"); + (true, true) + } else { + (true, false) + } + }, + }; debug!("getting shard creation: {:?}", enclave.get_shard_creation_info(shard)); initialization_handler.registered_on_parentchain(); @@ -878,15 +877,18 @@ where handles } -fn init_parentchain( +fn init_parentchain( enclave: &Arc, - node_api: &ParentchainApi, + node_api: &Api, Client>, tee_account_id: &AccountId32, parentchain_id: ParentchainId, shard: &ShardIdentifier, -) -> (Arc>, Header) +) -> (Arc>, Header) where E: EnclaveBase + Sidechain, + u128: From, + Tip: Copy + Default + Encode, + Client: Request + Subscribe, { let parentchain_handler = Arc::new( ParentchainHandler::new_with_automatic_light_client_allocation( @@ -1036,12 +1038,17 @@ fn register_collateral( } } -fn send_integritee_extrinsic( +fn send_integritee_extrinsic( extrinsic: Vec, - api: &ParentchainApi, + api: &Api, Client>, fee_payer: &AccountId32, is_development_mode: bool, -) -> ServiceResult { +) -> ServiceResult +where + u128: From, + Tip: Copy + Default + Encode, + Client: Request + Subscribe, +{ let timeout = Duration::from_secs(5 * 60); let (sender, receiver) = mpsc::channel(); let local_fee_payer = fee_payer.clone(); @@ -1103,12 +1110,18 @@ fn send_integritee_extrinsic( } } -fn start_parentchain_header_subscription_thread( +fn start_parentchain_header_subscription_thread( shutdown_flag: Arc, - parentchain_handler: Arc>, + parentchain_handler: Arc>, last_synced_header: Header, shard: ShardIdentifier, -) -> thread::JoinHandle<()> { +) -> thread::JoinHandle<()> +where + EnclaveApi: EnclaveBase + Sidechain, + u128: From, + Tip: Copy + Default + Encode, + Client: Request + Subscribe, +{ let parentchain_id = *parentchain_handler.parentchain_id(); thread::Builder::new() .name(format!("{:?}_parentchain_sync_loop", parentchain_id)) @@ -1131,12 +1144,18 @@ fn start_parentchain_header_subscription_thread( /// 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( +fn subscribe_to_parentchain_new_headers( shutdown_flag: Arc, - parentchain_handler: Arc>, + parentchain_handler: Arc>, mut last_synced_header: Header, shard: ShardIdentifier, -) -> Result<(), Error> { +) -> Result<(), Error> +where + EnclaveApi: EnclaveBase + Sidechain, + u128: From, + Tip: Copy + Default + Encode, + Client: Request + Subscribe, +{ // TODO: this should be implemented by parentchain_handler directly, and not via // exposed parentchain_api let mut subscription = parentchain_handler From 3c811763332bed6a401266e1e0596edd9533b158 Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Fri, 22 Nov 2024 09:25:32 +0100 Subject: [PATCH 06/23] prometheus metrics wip --- service/src/parentchain_handler.rs | 34 +++++++++++++++++++----------- service/src/prometheus_metrics.rs | 4 +++- service/src/sidechain_setup.rs | 5 +++-- 3 files changed, 28 insertions(+), 15 deletions(-) diff --git a/service/src/parentchain_handler.rs b/service/src/parentchain_handler.rs index 11164730e0..4dd6bd4e91 100644 --- a/service/src/parentchain_handler.rs +++ b/service/src/parentchain_handler.rs @@ -19,7 +19,9 @@ use crate::error::{Error, ServiceResult}; use codec::{Decode, Encode}; use humantime::format_duration; -use ita_parentchain_interface::{integritee::Header, ParentchainApiTrait}; +use ita_parentchain_interface::{ + integritee::Header, ParentchainApiTrait, ParentchainRuntimeConfig, +}; use itc_parentchain::{ light_client::light_client_init_params::{GrandpaParams, SimpleParams}, primitives::{ParentchainId, ParentchainInitParams}, @@ -35,7 +37,8 @@ use sp_runtime::traits::Header as HeaderTrait; use std::{cmp::min, sync::Arc, time::Duration}; use substrate_api_client::{ ac_primitives::{Block, Header as HeaderT}, - GetChainInfo, + rpc::{Request, Subscribe}, + Api, GetChainInfo, }; const BLOCK_SYNC_BATCH_SIZE: u32 = 1000; @@ -65,21 +68,27 @@ pub trait HandleParentchain { } /// Handles the interaction between parentchain and enclave. -pub(crate) struct ParentchainHandler { - parentchain_api: ParentchainApi, +pub(crate) struct ParentchainHandler +where + u128: From, + Tip: Copy + Default + Encode, +{ + parentchain_api: Api, Client>, enclave_api: Arc, pub parentchain_init_params: ParentchainInitParams, } // #TODO: #1451: Reintroduce `ParentchainApi: ChainApi` once there is no trait bound conflict // any more with the api-clients own trait definitions. -impl ParentchainHandler +impl ParentchainHandler where EnclaveApi: EnclaveBase, - ParentchainApi: ParentchainApiTrait, + u128: From, + Tip: Copy + Default + Encode, + Client: Request + Subscribe, { pub fn new( - parentchain_api: ParentchainApi, + parentchain_api: Api, Client>, enclave_api: Arc, parentchain_init_params: ParentchainInitParams, ) -> Self { @@ -88,7 +97,7 @@ where // FIXME: Necessary in the future? Fix with #1080 pub fn new_with_automatic_light_client_allocation( - parentchain_api: ParentchainApi, + parentchain_api: Api, Client>, enclave_api: Arc, id: ParentchainId, shard: ShardIdentifier, @@ -133,7 +142,7 @@ where Ok(Self::new(parentchain_api, enclave_api, parentchain_init_params)) } - pub fn parentchain_api(&self) -> &ParentchainApi { + pub fn parentchain_api(&self) -> &Api, Client> { &self.parentchain_api } @@ -142,11 +151,12 @@ where } } -impl HandleParentchain - for ParentchainHandler +impl HandleParentchain for ParentchainHandler where EnclaveApi: Sidechain + EnclaveBase, - ParentchainApi: ParentchainApiTrait, + u128: From, + Tip: Copy + Default + Encode, + Client: Request + Subscribe, { fn init_parentchain_components(&self) -> ServiceResult
{ Ok(self diff --git a/service/src/prometheus_metrics.rs b/service/src/prometheus_metrics.rs index 58cd8de508..cd6df82704 100644 --- a/service/src/prometheus_metrics.rs +++ b/service/src/prometheus_metrics.rs @@ -353,6 +353,8 @@ pub struct PrometheusMarblerunEventActivation { pub quote: String, } +trait ParentchainAccountInfoSafe: ParentchainAccountInfo + Send + Sync + Sized {} + #[allow(clippy::too_many_arguments)] pub fn start_prometheus_metrics_server( enclave: &Arc, @@ -367,7 +369,7 @@ pub fn start_prometheus_metrics_server( ) where E: EnclaveBase + Sidechain, { - let mut account_info_providers: Vec>> = vec![]; + let mut account_info_providers: Vec> = vec![]; account_info_providers.push(Arc::new(ParentchainAccountInfoProvider::new( ParentchainId::Integritee, integritee_rpc_api.clone(), diff --git a/service/src/sidechain_setup.rs b/service/src/sidechain_setup.rs index 52a19afe10..f140c0fe58 100644 --- a/service/src/sidechain_setup.rs +++ b/service/src/sidechain_setup.rs @@ -22,6 +22,7 @@ use crate::{ parentchain_handler::HandleParentchain, }; use futures::executor::block_on; +use ita_parentchain_interface::integritee::api_client_types::IntegriteeApi; use itp_api_client_types::ParentchainApi; use itp_enclave_api::{enclave_base::EnclaveBase, sidechain::Sidechain}; use itp_node_api::api_client::{pallet_sidechain::PalletSidechainApi, PalletTeerexApi}; @@ -53,7 +54,7 @@ pub trait ParentchainIntegriteeSidechainInfo { } pub struct ParentchainIntegriteeSidechainInfoProvider { - node_api: ParentchainApi, + node_api: IntegriteeApi, shard: ShardIdentifier, } @@ -91,7 +92,7 @@ impl ParentchainIntegriteeSidechainInfo for ParentchainIntegriteeSidechainInfoPr } impl ParentchainIntegriteeSidechainInfoProvider { - pub fn new(node_api: ParentchainApi, shard: ShardIdentifier) -> Self { + pub fn new(node_api: IntegriteeApi, shard: ShardIdentifier) -> Self { ParentchainIntegriteeSidechainInfoProvider { node_api, shard } } } From e3f58294bc2d1c7f2becc2154520fa002b6dd076 Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Fri, 22 Nov 2024 10:16:18 +0100 Subject: [PATCH 07/23] finish metrics --- service/src/prometheus_metrics.rs | 131 +++++++++++++++++++++--------- 1 file changed, 94 insertions(+), 37 deletions(-) diff --git a/service/src/prometheus_metrics.rs b/service/src/prometheus_metrics.rs index cd6df82704..77e7ae0672 100644 --- a/service/src/prometheus_metrics.rs +++ b/service/src/prometheus_metrics.rs @@ -145,15 +145,20 @@ pub trait HandleMetrics { } /// Metrics handler implementation. This is for untrusted sources of metrics (non-enclave) -pub struct MetricsHandler { - wallets: Vec>, +pub struct MetricsHandler { + integritee_wallets: Vec>, + target_a_wallets: Vec>, + target_b_wallets: Vec>, sidechain: Arc, } #[async_trait] -impl HandleMetrics for MetricsHandler +impl HandleMetrics + for MetricsHandler where - Wallet: ParentchainAccountInfo + Send + Sync, + IntegriteeWallet: ParentchainAccountInfo + Send + Sync, + TargetAWallet: ParentchainAccountInfo + Send + Sync, + TargetBWallet: ParentchainAccountInfo + Send + Sync, Sidechain: ParentchainIntegriteeSidechainInfo + Send + Sync, { type ReplyType = String; @@ -174,24 +179,45 @@ where } } -impl MetricsHandler +impl + MetricsHandler where - Wallet: ParentchainAccountInfo + Send + Sync, + IntegriteeWallet: ParentchainAccountInfo + Send + Sync, + TargetAWallet: ParentchainAccountInfo + Send + Sync, + TargetBWallet: ParentchainAccountInfo + Send + Sync, Sidechain: ParentchainIntegriteeSidechainInfo + Send + Sync, { - pub fn new(wallets: Vec>, sidechain: Arc) -> Self { - MetricsHandler { wallets, sidechain } + pub fn new( + integritee_wallets: Vec>, + target_a_wallets: Vec>, + target_b_wallets: Vec>, + sidechain: Arc, + ) -> Self { + MetricsHandler { integritee_wallets, target_a_wallets, target_b_wallets, sidechain } } async fn update_all_account_metrics(&self) { - for wallet in &self.wallets { + for wallet in &self.integritee_wallets { if let Err(e) = Self::update_wallet_metrics(wallet).await { - error!("Failed to update wallet metrics: {:?}", e); + error!("Failed to update integritee wallet metrics: {:?}", e); + } + } + + for wallet in &self.target_a_wallets { + if let Err(e) = Self::update_wallet_metrics(wallet).await { + error!("Failed to update target a wallet metrics: {:?}", e); + } + } + for wallet in &self.target_b_wallets { + if let Err(e) = Self::update_wallet_metrics(wallet).await { + error!("Failed to update target b wallet metrics: {:?}", e); } } } - async fn update_wallet_metrics(wallet: &Wallet) -> ServiceResult<()> { + async fn update_wallet_metrics( + wallet: &Arc, + ) -> ServiceResult<()> { let balance = wallet.free_balance()?; let parentchain_id = wallet.parentchain_id()?; let account_and_role = wallet.account_and_role()?; @@ -353,8 +379,6 @@ pub struct PrometheusMarblerunEventActivation { pub quote: String, } -trait ParentchainAccountInfoSafe: ParentchainAccountInfo + Send + Sync + Sized {} - #[allow(clippy::too_many_arguments)] pub fn start_prometheus_metrics_server( enclave: &Arc, @@ -369,8 +393,14 @@ pub fn start_prometheus_metrics_server( ) where E: EnclaveBase + Sidechain, { - let mut account_info_providers: Vec> = vec![]; - account_info_providers.push(Arc::new(ParentchainAccountInfoProvider::new( + let mut integritee_account_info_providers: Vec>> = + vec![]; + let mut target_a_account_info_providers: Vec>> = + vec![]; + let mut target_b_account_info_providers: Vec>> = + vec![]; + + integritee_account_info_providers.push(Arc::new(ParentchainAccountInfoProvider::new( ParentchainId::Integritee, integritee_rpc_api.clone(), AccountAndRole::EnclaveSigner(tee_account_id.clone()), @@ -378,33 +408,56 @@ pub fn start_prometheus_metrics_server( let shielding_target = shielding_target.unwrap_or_default(); let shard_vault = enclave.get_ecc_vault_pubkey(shard).expect("shard vault must be defined by now"); - account_info_providers.push(Arc::new(ParentchainAccountInfoProvider::new( - shielding_target, - match shielding_target { - ParentchainId::Integritee => integritee_rpc_api.clone(), - ParentchainId::TargetA => maybe_target_a_rpc_api - .clone() - .expect("target A must be initialized to be used as shielding target"), - ParentchainId::TargetB => maybe_target_b_rpc_api - .clone() - .expect("target B must be initialized to be used as shielding target"), - }, - AccountAndRole::ShardVault( - enclave - .get_ecc_vault_pubkey(shard) - .expect("shard vault must be defined by now") - .into(), - ), - ))); + + match shielding_target { + ParentchainId::Integritee => + integritee_account_info_providers.push(Arc::new(ParentchainAccountInfoProvider::new( + shielding_target, + integritee_rpc_api.clone(), + AccountAndRole::ShardVault( + enclave + .get_ecc_vault_pubkey(shard) + .expect("shard vault must be defined by now") + .into(), + ), + ))), + ParentchainId::TargetA => + target_a_account_info_providers.push(Arc::new(ParentchainAccountInfoProvider::new( + shielding_target, + maybe_target_a_rpc_api + .clone() + .expect("target A must be initialized to be used as shielding target"), + AccountAndRole::ShardVault( + enclave + .get_ecc_vault_pubkey(shard) + .expect("shard vault must be defined by now") + .into(), + ), + ))), + ParentchainId::TargetB => + target_b_account_info_providers.push(Arc::new(ParentchainAccountInfoProvider::new( + shielding_target, + maybe_target_b_rpc_api + .clone() + .expect("target B must be initialized to be used as shielding target"), + AccountAndRole::ShardVault( + enclave + .get_ecc_vault_pubkey(shard) + .expect("shard vault must be defined by now") + .into(), + ), + ))), + }; + if let Some(api) = maybe_target_a_rpc_api { - account_info_providers.push(Arc::new(ParentchainAccountInfoProvider::new( + target_a_account_info_providers.push(Arc::new(ParentchainAccountInfoProvider::new( ParentchainId::TargetA, api, AccountAndRole::EnclaveSigner(tee_account_id.clone()), ))) }; if let Some(api) = maybe_target_b_rpc_api { - account_info_providers.push(Arc::new(ParentchainAccountInfoProvider::new( + target_b_account_info_providers.push(Arc::new(ParentchainAccountInfoProvider::new( ParentchainId::TargetB, api, AccountAndRole::EnclaveSigner(tee_account_id.clone()), @@ -413,8 +466,12 @@ pub fn start_prometheus_metrics_server( let sidechain_info_provider = Arc::new(ParentchainIntegriteeSidechainInfoProvider::new(integritee_rpc_api, *shard)); - let metrics_handler = - Arc::new(MetricsHandler::new(account_info_providers, sidechain_info_provider)); + let metrics_handler = Arc::new(MetricsHandler::new( + integritee_account_info_providers, + target_a_account_info_providers, + target_b_account_info_providers, + sidechain_info_provider, + )); tokio_handle.spawn(async move { if let Err(e) = start_metrics_server(metrics_handler, metrics_server_port).await { From 6a0bae129a343f8e82f927f3e427de02c467083c Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Fri, 22 Nov 2024 11:19:27 +0100 Subject: [PATCH 08/23] worker builds --- .../src/target_a/api_client_types.rs | 3 +- .../src/target_b/api_client_types.rs | 14 +- cli/src/oracle/commands/listen_to_exchange.rs | 3 +- cli/src/oracle/commands/listen_to_oracle.rs | 2 +- service/src/account_funding.rs | 26 ++-- service/src/main_impl.rs | 127 ++++++++++++------ service/src/ocall_bridge/component_factory.rs | 7 +- service/src/worker.rs | 30 ++--- 8 files changed, 127 insertions(+), 85 deletions(-) diff --git a/app-libs/parentchain-interface/src/target_a/api_client_types.rs b/app-libs/parentchain-interface/src/target_a/api_client_types.rs index 92be945287..822c75830b 100644 --- a/app-libs/parentchain-interface/src/target_a/api_client_types.rs +++ b/app-libs/parentchain-interface/src/target_a/api_client_types.rs @@ -85,7 +85,8 @@ mod api { Api, GetBalance, GetChainInfo, GetStorage, GetTransactionPayment, SubscribeEvents, }; - pub type TargetAApi = Api>, TungsteniteRpcClient>; + pub type TargetANodeConfig = ParentchainRuntimeConfig>; + pub type TargetAApi = Api; //impl ParentchainApiTrait for TargetAApi {} } diff --git a/app-libs/parentchain-interface/src/target_b/api_client_types.rs b/app-libs/parentchain-interface/src/target_b/api_client_types.rs index 26472604ef..49213bc893 100644 --- a/app-libs/parentchain-interface/src/target_b/api_client_types.rs +++ b/app-libs/parentchain-interface/src/target_b/api_client_types.rs @@ -47,17 +47,13 @@ pub mod traits { pub use substrate_api_client::{GetAccountInformation, GetChainInfo, GetStorage}; } -pub type TargetBTip = AssetTip; -pub type TargetBRuntimeConfig = - WithExtrinsicParams>; - // Configuration for the ExtrinsicParams. // // Pay in asset fees. // // This needs to be used if the node uses the `pallet_asset_tx_payment`. -pub type TargetBExtrinsicParams = GenericExtrinsicParams; -pub type TargetBAdditionalParams = GenericAdditionalParams; +// pub type TargetBExtrinsicParams = GenericExtrinsicParams; +// pub type TargetBAdditionalParams = GenericAdditionalParams; pub type TargetBSignedExtra = GenericSignedExtra; pub type TargetBSignature = Signature; @@ -73,7 +69,7 @@ pub use api::*; #[cfg(feature = "std")] mod api { - use crate::ParentchainRuntimeConfig; + use crate::{integritee::api_client_types::AssetTip, ParentchainRuntimeConfig}; use itp_api_client_types::PlainTip; use itp_node_api::api_client::AccountApi; use itp_types::parentchain::Balance; @@ -85,7 +81,9 @@ mod api { Api, GetBalance, GetChainInfo, GetStorage, GetTransactionPayment, SubscribeEvents, }; - pub type TargetBApi = Api>, TungsteniteRpcClient>; + pub type TargetBTip = AssetTip; + pub type TargetBNodeConfig = ParentchainRuntimeConfig; + pub type TargetBApi = Api, TungsteniteRpcClient>; // impl ParentchainApiTrait for TargetBApi {} } diff --git a/cli/src/oracle/commands/listen_to_exchange.rs b/cli/src/oracle/commands/listen_to_exchange.rs index f301ee9c1b..957c16cb1b 100644 --- a/cli/src/oracle/commands/listen_to_exchange.rs +++ b/cli/src/oracle/commands/listen_to_exchange.rs @@ -16,7 +16,6 @@ */ use crate::{command_utils::get_chain_api, Cli}; -use itp_node_api::api_client::ParentchainApi; use itp_time_utils::{duration_now, remaining_time}; use itp_types::parentchain::ExchangeRateUpdated; use log::*; @@ -42,7 +41,7 @@ impl ListenToExchangeRateEventsCmd { } } -pub fn count_exchange_rate_update_events(api: &ParentchainApi, duration: Duration) -> u32 { +pub fn count_exchange_rate_update_events(api: &IntegriteeApi, duration: Duration) -> u32 { let stop = duration_now() + duration; //subscribe to events diff --git a/cli/src/oracle/commands/listen_to_oracle.rs b/cli/src/oracle/commands/listen_to_oracle.rs index dfbb874356..cdd4f21480 100644 --- a/cli/src/oracle/commands/listen_to_oracle.rs +++ b/cli/src/oracle/commands/listen_to_oracle.rs @@ -41,7 +41,7 @@ impl ListenToOracleEventsCmd { } } -fn count_oracle_update_events(api: &ParentchainApi, duration: Duration) -> EventCount { +fn count_oracle_update_events(api: &IntegriteeApi, duration: Duration) -> EventCount { let stop = duration_now() + duration; //subscribe to events diff --git a/service/src/account_funding.rs b/service/src/account_funding.rs index 9a9df3c332..84b9be32a5 100644 --- a/service/src/account_funding.rs +++ b/service/src/account_funding.rs @@ -20,7 +20,7 @@ use codec::Encode; use ita_parentchain_interface::{ integritee::api_client_types::Config, ParentchainApiTrait, ParentchainRuntimeConfig, }; -use itp_node_api::api_client::{AccountApi, ParentchainApi, TEEREX}; +use itp_node_api::api_client::{AccountApi, TEEREX}; use itp_settings::worker::REGISTERING_FEE_FACTOR_FOR_INIT_FUNDS; use itp_types::{ parentchain::{AccountId, Balance, Index, ParentchainId}, @@ -142,7 +142,7 @@ where /// in --dev mode: let Alice pay for missing funds /// in production mode: wait for manual transfer before continuing pub fn setup_reasonable_account_funding( - api: &Api, Client>, + api: Api, Client>, accountid: &AccountId32, parentchain_id: ParentchainId, is_development_mode: bool, @@ -150,10 +150,10 @@ pub fn setup_reasonable_account_funding( where u128: From, Tip: Copy + Default + Encode, - Client: Request + Subscribe, + Client: Request + Subscribe + Clone, { loop { - let needed = estimate_funds_needed_to_run_for_a_while(api, accountid, parentchain_id)?; + let needed = estimate_funds_needed_to_run_for_a_while(&api, accountid, parentchain_id)?; let free = api.get_free_balance(accountid)?; let missing_funds = needed.saturating_sub(free); @@ -163,7 +163,7 @@ where if is_development_mode { info!("[{:?}] Alice will grant {:?} to {:?}", parentchain_id, missing_funds, accountid); - bootstrap_funds_from_alice(api, accountid, missing_funds)?; + bootstrap_funds_from_alice(api.clone(), accountid, missing_funds)?; } else { error!( "[{:?}] Enclave account needs funding. please send at least {:?} to {:?}", @@ -233,7 +233,7 @@ where } pub fn estimate_fee( - api: &ParentchainApi, + api: &Api, Client>, encoded_extrinsic: Vec, ) -> Result where @@ -256,7 +256,7 @@ where /// Alice sends some funds to the account. only for dev chains testing fn bootstrap_funds_from_alice( - api: &Api, Client>, + api: Api, Client>, accountid: &AccountId32, funding_amount: u128, ) -> Result<(), Error> @@ -265,6 +265,8 @@ where Tip: Copy + Default + Encode, Client: Request + Subscribe, { + let mut api = api; + let alice = AccountKeyring::Alice.pair(); let alice_acc = AccountId32::from(*alice.public().as_array_ref()); @@ -281,19 +283,17 @@ where return Err(Error::ApplicationSetup) } - let mut alice_signer_api = api.clone(); - alice_signer_api.set_signer(alice.into()); + api.set_signer(alice.into()); println!("[+] send extrinsic: bootstrap funding Enclave from Alice's funds"); - let xt = alice_signer_api - .balance_transfer_allow_death(MultiAddress::Id(accountid.clone()), funding_amount); - let xt_report = alice_signer_api.submit_and_watch_extrinsic_until(xt, XtStatus::InBlock)?; + let xt = api.balance_transfer_allow_death(MultiAddress::Id(accountid.clone()), funding_amount); + let xt_report = api.submit_and_watch_extrinsic_until(xt, XtStatus::InBlock)?; info!( "[<] L1 extrinsic success. extrinsic hash: {:?} / status: {:?}", xt_report.extrinsic_hash, xt_report.status ); // Verify funds have arrived. - let free_balance = alice_signer_api.get_free_balance(accountid); + let free_balance = api.get_free_balance(accountid); trace!("TEE's NEW free balance = {:?}", free_balance); Ok(()) diff --git a/service/src/main_impl.rs b/service/src/main_impl.rs index cdf580bf49..f70218d9ec 100644 --- a/service/src/main_impl.rs +++ b/service/src/main_impl.rs @@ -75,7 +75,12 @@ use crate::{ }; use enclave_bridge_primitives::ShardIdentifier; use ita_parentchain_interface::{ - integritee::{api_client_types::IntegriteeApi, api_factory::IntegriteeNodeApiFactory}, + integritee::{ + api_client_types::{IntegriteeApi, IntegriteeTip}, + api_factory::IntegriteeNodeApiFactory, + }, + target_a::api_client_types::{TargetAApi, TargetANodeConfig}, + target_b::api_client_types::{TargetBApi, TargetBNodeConfig}, ParentchainApiTrait, ParentchainRuntimeConfig, }; use itc_parentchain::primitives::ParentchainId; @@ -96,7 +101,10 @@ use std::{ thread, time::Duration, }; -use substrate_api_client::ac_node_api::{EventRecord, Phase::ApplyExtrinsic}; +use substrate_api_client::{ + ac_node_api::{EventRecord, Phase::ApplyExtrinsic}, + rpc::TungsteniteRpcClient, +}; use tokio::{runtime::Handle, task::JoinHandle, time::Instant}; const VERSION: &str = env!("CARGO_PKG_VERSION"); @@ -104,8 +112,7 @@ const VERSION: &str = env!("CARGO_PKG_VERSION"); #[cfg(feature = "link-binary")] pub type EnclaveWorker = Worker< Config, - IntegriteeNodeApiFactory, - IntegriteeApi, + ParentchainRuntimeConfig, Enclave, InitializationHandler, >; @@ -173,13 +180,15 @@ pub(crate) fn main() { Arc::new(BlockFetcher::::new(untrusted_peer_fetcher)); let enclave_metrics_receiver = Arc::new(EnclaveMetricsReceiver {}); - let maybe_target_a_parentchain_api_factory = config - .target_a_parentchain_rpc_endpoint() - .map(|url| Arc::new(NodeApiFactory::new(url, AccountKeyring::Alice.pair()))); + let maybe_target_a_parentchain_api_factory = + config.target_a_parentchain_rpc_endpoint().map(|url| { + Arc::new(NodeApiFactory::::new(url, AccountKeyring::Alice.pair())) + }); - let maybe_target_b_parentchain_api_factory = config - .target_b_parentchain_rpc_endpoint() - .map(|url| Arc::new(NodeApiFactory::new(url, AccountKeyring::Alice.pair()))); + let maybe_target_b_parentchain_api_factory = + config.target_b_parentchain_rpc_endpoint().map(|url| { + Arc::new(NodeApiFactory::::new(url, AccountKeyring::Alice.pair())) + }); // initialize o-call bridge with a concrete factory implementation OCallBridge::initialize(Arc::new(OCallBridgeComponentFactory::new( @@ -306,7 +315,7 @@ fn start_worker( shard: &ShardIdentifier, enclave: Arc, sidechain_storage: Arc, - integritee_rpc_api: ParentchainApi, + integritee_rpc_api: IntegriteeApi, tokio_handle_getter: Arc, initialization_handler: Arc, quoting_enclave_target_info: Option, @@ -670,7 +679,7 @@ fn start_worker( let mut handles = init_target_parentchain( &enclave, &tee_accountid, - &api, + api.clone(), shard, ParentchainId::TargetA, is_development_mode, @@ -693,7 +702,7 @@ fn start_worker( let mut handles = init_target_parentchain( &enclave, &tee_accountid, - &api, + api.clone(), shard, ParentchainId::TargetB, is_development_mode, @@ -764,24 +773,56 @@ fn start_worker( fn init_provided_shard_vault( shard: &ShardIdentifier, enclave: &Arc, - integritee_rpc_api: ParentchainApi, - maybe_target_a_rpc_api: Option, - maybe_target_b_rpc_api: Option, + integritee_rpc_api: IntegriteeApi, + maybe_target_a_rpc_api: Option, + maybe_target_b_rpc_api: Option, shielding_target: Option, we_are_primary_validateer: bool, ) { let shielding_target = shielding_target.unwrap_or_default(); - let rpc_api = match shielding_target { - ParentchainId::Integritee => integritee_rpc_api, - ParentchainId::TargetA => maybe_target_a_rpc_api - .expect("target A must be initialized to be used as shielding target"), - ParentchainId::TargetB => maybe_target_b_rpc_api - .expect("target B must be initialized to be used as shielding target"), + match shielding_target { + ParentchainId::Integritee => init_vault( + shard, + enclave, + &integritee_rpc_api, + shielding_target, + we_are_primary_validateer, + ), + ParentchainId::TargetA => init_vault( + shard, + enclave, + &maybe_target_a_rpc_api + .expect("target A must be initialized to be used as shielding target"), + shielding_target, + we_are_primary_validateer, + ), + ParentchainId::TargetB => init_vault( + shard, + enclave, + &maybe_target_b_rpc_api + .expect("target B must be initialized to be used as shielding target"), + shielding_target, + we_are_primary_validateer, + ), }; - let funding_balance = shard_vault_initial_funds(&rpc_api).unwrap(); +} + +fn init_vault( + shard: &ShardIdentifier, + enclave: &Arc, + node_api: &Api, Client>, + shielding_target: ParentchainId, + we_are_primary_validateer: bool, +) where + E: EnclaveBase, + u128: From, + Tip: Copy + Default + Encode, + Client: Request, +{ + let funding_balance = shard_vault_initial_funds(&node_api).unwrap(); if let Ok(shard_vault) = enclave.get_ecc_vault_pubkey(shard) { // verify if proxy is set up on chain - let nonce = rpc_api.get_account_nonce(&AccountId::from(shard_vault)).unwrap(); + let nonce = node_api.get_account_nonce(&AccountId::from(shard_vault)).unwrap(); println!( "[{:?}] shard vault account is already initialized in state: {} with nonce {}", shielding_target, @@ -810,10 +851,10 @@ fn init_provided_shard_vault( } } -fn init_target_parentchain( +fn init_target_parentchain( enclave: &Arc, tee_account_id: &AccountId32, - node_api: &ParentchainApi, + node_api: Api, Client>, shard: &ShardIdentifier, parentchain_id: ParentchainId, is_development_mode: bool, @@ -821,11 +862,19 @@ fn init_target_parentchain( ) -> Vec> where E: EnclaveBase + Sidechain, + u128: From, + Tip: Copy + Default + Encode + Send + Sync + 'static, + Client: Request + Subscribe + Clone + Send + Sync + 'static, { - setup_reasonable_account_funding(node_api, tee_account_id, parentchain_id, is_development_mode) - .unwrap_or_else(|_| { - panic!("[{:?}] Could not fund parentchain enclave account", parentchain_id) - }); + setup_reasonable_account_funding( + node_api.clone(), + tee_account_id, + parentchain_id, + is_development_mode, + ) + .unwrap_or_else(|_| { + panic!("[{:?}] Could not fund parentchain enclave account", parentchain_id) + }); // we attempt to set shard creation for this parentchain in case it hasn't been done before let api_head = node_api.get_header(None).unwrap().unwrap(); @@ -868,7 +917,7 @@ where .name(format!("{:?}_parentchain_event_subscription", parentchain_id)) .spawn(move || { ita_parentchain_interface::event_subscriber::subscribe_to_parentchain_events( - node_api_clone, + &node_api_clone, parentchain_id, shutdown_flag, ) @@ -888,7 +937,7 @@ where E: EnclaveBase + Sidechain, u128: From, Tip: Copy + Default + Encode, - Client: Request + Subscribe, + Client: Request + Subscribe + Clone, { let parentchain_handler = Arc::new( ParentchainHandler::new_with_automatic_light_client_allocation( @@ -929,7 +978,7 @@ where /// considered initialized and ready for the next worker to start. fn spawn_worker_for_shard_polling( shard: &ShardIdentifier, - node_api: ParentchainApi, + node_api: IntegriteeApi, initialization_handler: Arc, ) where InitializationHandler: TrackInitialization + Sync + Send + 'static, @@ -1018,7 +1067,7 @@ fn register_quotes_from_marblerun( } #[cfg(feature = "dcap")] fn register_collateral( - api: &ParentchainApi, + api: &IntegriteeApi, enclave: &dyn RemoteAttestation, accountid: &AccountId32, is_development_mode: bool, @@ -1046,8 +1095,8 @@ fn send_integritee_extrinsic( ) -> ServiceResult where u128: From, - Tip: Copy + Default + Encode, - Client: Request + Subscribe, + Tip: Copy + Default + Encode + Send + Sync + 'static, + Client: Request + Subscribe + Clone + Send + Sync + 'static, { let timeout = Duration::from_secs(5 * 60); let (sender, receiver) = mpsc::channel(); @@ -1069,7 +1118,7 @@ where if missing_funds > 0 { setup_reasonable_account_funding( - &local_api, + local_api.clone(), &local_fee_payer, ParentchainId::Integritee, is_development_mode, @@ -1119,8 +1168,8 @@ fn start_parentchain_header_subscription_thread( where EnclaveApi: EnclaveBase + Sidechain, u128: From, - Tip: Copy + Default + Encode, - Client: Request + Subscribe, + Tip: Copy + Default + Encode + Send + Sync + 'static, + Client: Request + Subscribe + Send + Sync + 'static, { let parentchain_id = *parentchain_handler.parentchain_id(); thread::Builder::new() diff --git a/service/src/ocall_bridge/component_factory.rs b/service/src/ocall_bridge/component_factory.rs index 4b5053b086..6d36702e06 100644 --- a/service/src/ocall_bridge/component_factory.rs +++ b/service/src/ocall_bridge/component_factory.rs @@ -157,9 +157,10 @@ impl< TokioHandle, MetricsReceiver, > where - IntegriteeRuntimeConfig: Config, - TargetARuntimeConfig: Config, - TargetBRuntimeConfig: Config, + IntegriteeRuntimeConfig: + Config + 'static, + TargetARuntimeConfig: Config + 'static, + TargetBRuntimeConfig: Config + 'static, ::ExtrinsicSigner: From, ::ExtrinsicSigner: From, ::ExtrinsicSigner: From, diff --git a/service/src/worker.rs b/service/src/worker.rs index 289863866c..634c4d7840 100644 --- a/service/src/worker.rs +++ b/service/src/worker.rs @@ -41,33 +41,28 @@ use std::{ marker::PhantomData, sync::{Arc, RwLock}, }; +use substrate_api_client::rpc::TungsteniteRpcClient; use teerex_primitives::MultiEnclave; use url::Url as UrlType; pub type WorkerResult = Result; pub type Url = String; -pub struct Worker< - Config, - NodeConfig: NodeRuntimeConfig, - Client: Request, - Enclave, - InitializationHandler, -> { +pub struct Worker { _config: Config, // unused yet, but will be used when more methods are migrated to the worker _enclave_api: Arc, - node_api_factory: Arc>, + node_api_factory: Arc>, initialization_handler: Arc, peers: RwLock>, } -impl - Worker +impl + Worker { pub fn new( config: Config, enclave_api: Arc, - node_api_factory: Arc>, + node_api_factory: Arc>, initialization_handler: Arc, peers: Vec, ) -> Self { @@ -88,11 +83,10 @@ pub trait AsyncBlockBroadcaster { } #[async_trait] -impl AsyncBlockBroadcaster - for Worker +impl AsyncBlockBroadcaster + for Worker where - NodeConfig: NodeRuntimeConfig, - Client: Request, + NodeConfig: NodeRuntimeConfig + Send + Sync, Enclave: Send + Sync, InitializationHandler: TrackInitialization + Send + Sync, { @@ -150,11 +144,11 @@ pub trait UpdatePeers { } } -impl UpdatePeers - for Worker +impl UpdatePeers + for Worker where NodeConfig: NodeRuntimeConfig, - Client: Request, + ::ExtrinsicSigner: From, { fn search_peers(&self, shard: ShardIdentifier) -> WorkerResult> { let node_api = self From f38415ca28ed088b938c3ddcd27cf5fa59488e1a Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Fri, 22 Nov 2024 11:33:30 +0100 Subject: [PATCH 09/23] fix unused warnings --- .../src/event_subscriber.rs | 1 - .../src/integritee/api_client_types.rs | 17 ++------- app-libs/parentchain-interface/src/lib.rs | 37 +++---------------- .../src/target_a/api_client_types.rs | 17 ++------- .../src/target_b/api_client_types.rs | 25 ++++--------- .../api-client-extensions/src/account.rs | 20 ---------- core-primitives/node-api/factory/src/lib.rs | 2 +- service/src/account_funding.rs | 4 +- service/src/main_impl.rs | 16 +++++--- .../src/ocall_bridge/worker_on_chain_ocall.rs | 2 +- service/src/parentchain_handler.rs | 4 +- service/src/worker.rs | 1 - 12 files changed, 34 insertions(+), 112 deletions(-) diff --git a/app-libs/parentchain-interface/src/event_subscriber.rs b/app-libs/parentchain-interface/src/event_subscriber.rs index 9732c1996a..abf5fe0905 100644 --- a/app-libs/parentchain-interface/src/event_subscriber.rs +++ b/app-libs/parentchain-interface/src/event_subscriber.rs @@ -17,7 +17,6 @@ extern crate alloc; use alloc::sync::Arc; use core::sync::atomic::{AtomicBool, Ordering}; -use itp_api_client_types::ParentchainApi; use itp_node_api::api_client::AccountApi; use itp_types::parentchain::{ AddedSgxEnclave, BalanceTransfer, ExtrinsicFailed, Hash, ParentchainId, diff --git a/app-libs/parentchain-interface/src/integritee/api_client_types.rs b/app-libs/parentchain-interface/src/integritee/api_client_types.rs index 1e873f77be..fffe06c883 100644 --- a/app-libs/parentchain-interface/src/integritee/api_client_types.rs +++ b/app-libs/parentchain-interface/src/integritee/api_client_types.rs @@ -24,7 +24,6 @@ pub use itp_types::parentchain::{ AccountData, AccountId, AccountInfo, Address, Balance, Hash, Index, Signature as PairSignature, }; use sp_runtime::generic; -use substrate_api_client::ac_primitives::{PlainTipExtrinsicParams, WithExtrinsicParams}; pub use substrate_api_client::{ ac_node_api::{ metadata::{InvalidMetadataError, Metadata, MetadataError}, @@ -43,14 +42,8 @@ pub use substrate_api_client::{ storage_key, Api, }; -// traits from the api-client -pub mod traits { - pub use substrate_api_client::{GetAccountInformation, GetChainInfo, GetStorage}; -} - pub type IntegriteeTip = PlainTip; -pub type IntegriteeRuntimeConfig = - WithExtrinsicParams>; +pub type IntegriteeRuntimeConfig = ParentchainRuntimeConfig; // Configuration for the ExtrinsicParams. // @@ -71,6 +64,7 @@ pub type Signature = Option<(Address, PairSignature, SignedExtra)>; pub type Block = generic::Block>; +use crate::ParentchainRuntimeConfig; #[cfg(feature = "std")] pub use api::*; use itp_types::parentchain::Header; @@ -79,17 +73,12 @@ use itp_types::parentchain::Header; mod api { use crate::ParentchainRuntimeConfig; use itp_api_client_types::PlainTip; - use itp_node_api::api_client::AccountApi; use itp_types::parentchain::Balance; pub use substrate_api_client::{ api::Error as ApiClientError, rpc::{tungstenite_client::TungsteniteRpcClient, Error as RpcClientError}, - }; - use substrate_api_client::{ - Api, GetBalance, GetChainInfo, GetStorage, GetTransactionPayment, SubscribeEvents, + Api, }; pub type IntegriteeApi = Api>, TungsteniteRpcClient>; - - // impl ParentchainApiTrait for IntegriteeApi {} } diff --git a/app-libs/parentchain-interface/src/lib.rs b/app-libs/parentchain-interface/src/lib.rs index 2f6ef64e2f..102ddb9136 100644 --- a/app-libs/parentchain-interface/src/lib.rs +++ b/app-libs/parentchain-interface/src/lib.rs @@ -25,23 +25,12 @@ extern crate sgx_tstd as std; use crate::integritee::api_client_types::Config; use codec::{Decode, Encode}; use core::marker::PhantomData; -use itp_api_client_types::{ExtrinsicParams, GenericExtrinsicParams}; -use itp_node_api::api_client::{AccountApi, ChainApi}; -use itp_types::parentchain::{AccountId, Balance, Hash, Header, Index}; +use itp_api_client_types::GenericExtrinsicParams; +use itp_types::parentchain::Hash; use sp_core::{crypto::AccountId32, sr25519}; -use sp_runtime::{ - generic::{Block, UncheckedExtrinsic}, - MultiAddress, MultiSignature, -}; -use sp_version::GetRuntimeVersionAt; -use substrate_api_client::{ - ac_primitives::{ - AccountData, AssetTipExtrinsicParams, BlakeTwo256, ExtrinsicSigner, Properties, - SubstrateBlock, SubstrateHeader, SubstrateOpaqueExtrinsic, - }, - extrinsic::BalancesExtrinsics, - GetAccountInformation, GetBalance, GetStorage, GetTransactionPayment, SubmitAndWatch, - SubscribeEvents, SystemApi, +use sp_runtime::{MultiAddress, MultiSignature}; +use substrate_api_client::ac_primitives::{ + BlakeTwo256, ExtrinsicSigner, SubstrateBlock, SubstrateHeader, SubstrateOpaqueExtrinsic, }; #[cfg(feature = "std")] @@ -76,21 +65,7 @@ pub fn decode_and_log_error(encoded: &mut &[u8]) -> Option { } } -/// a trait to aggreagate all traits we need in the service -pub trait ParentchainApiTrait: - AccountApi - + GetBalance - + GetStorage - + SystemApi - + BalancesExtrinsics
, Balance = Balance> - + ChainApi - + GetAccountInformation - + SubscribeEvents - + GetTransactionPayment - + SubmitAndWatch //+ GetRuntimeVersionAt>> -{ -} - +// Define the config that matches our parentchains. #[derive(Decode, Encode, Clone, Eq, PartialEq, Debug)] pub struct ParentchainRuntimeConfig { _phantom: PhantomData, diff --git a/app-libs/parentchain-interface/src/target_a/api_client_types.rs b/app-libs/parentchain-interface/src/target_a/api_client_types.rs index 822c75830b..254cc81f0c 100644 --- a/app-libs/parentchain-interface/src/target_a/api_client_types.rs +++ b/app-libs/parentchain-interface/src/target_a/api_client_types.rs @@ -23,7 +23,6 @@ pub use itp_types::parentchain::{ AccountData, AccountId, AccountInfo, Address, Balance, Hash, Index, Signature as PairSignature, }; -use substrate_api_client::ac_primitives::{PlainTipExtrinsicParams, WithExtrinsicParams}; pub use substrate_api_client::{ ac_node_api::{ metadata::{InvalidMetadataError, Metadata, MetadataError}, @@ -42,14 +41,8 @@ pub use substrate_api_client::{ storage_key, Api, }; -// traits from the api-client -pub mod traits { - pub use substrate_api_client::{GetAccountInformation, GetChainInfo, GetStorage}; -} - pub type TargetATip = PlainTip; -pub type TargetARuntimeConfig = - WithExtrinsicParams>; +pub type TargetARuntimeConfig = ParentchainRuntimeConfig; // Configuration for the ExtrinsicParams. // @@ -68,6 +61,7 @@ pub type TargetAUncheckedExtrinsic = /// Signature type of the [UncheckedExtrinsicV4]. pub type Signature = Option<(Address, PairSignature, SignedExtra)>; +use crate::ParentchainRuntimeConfig; #[cfg(feature = "std")] pub use api::*; @@ -75,18 +69,13 @@ pub use api::*; mod api { use crate::ParentchainRuntimeConfig; use itp_api_client_types::PlainTip; - use itp_node_api::api_client::AccountApi; use itp_types::parentchain::Balance; pub use substrate_api_client::{ api::Error as ApiClientError, rpc::{tungstenite_client::TungsteniteRpcClient, Error as RpcClientError}, - }; - use substrate_api_client::{ - Api, GetBalance, GetChainInfo, GetStorage, GetTransactionPayment, SubscribeEvents, + Api, }; pub type TargetANodeConfig = ParentchainRuntimeConfig>; pub type TargetAApi = Api; - - //impl ParentchainApiTrait for TargetAApi {} } diff --git a/app-libs/parentchain-interface/src/target_b/api_client_types.rs b/app-libs/parentchain-interface/src/target_b/api_client_types.rs index 49213bc893..fc0376b7ee 100644 --- a/app-libs/parentchain-interface/src/target_b/api_client_types.rs +++ b/app-libs/parentchain-interface/src/target_b/api_client_types.rs @@ -23,7 +23,6 @@ pub use itp_types::parentchain::{ AccountData, AccountId, AccountInfo, Address, Balance, Hash, Index, Signature as PairSignature, }; -use substrate_api_client::ac_primitives::{AssetTipExtrinsicParams, WithExtrinsicParams}; pub use substrate_api_client::{ ac_node_api::{ metadata::{InvalidMetadataError, Metadata, MetadataError}, @@ -42,11 +41,6 @@ pub use substrate_api_client::{ storage_key, Api, }; -// traits from the api-client -pub mod traits { - pub use substrate_api_client::{GetAccountInformation, GetChainInfo, GetStorage}; -} - // Configuration for the ExtrinsicParams. // // Pay in asset fees. @@ -55,6 +49,9 @@ pub mod traits { // pub type TargetBExtrinsicParams = GenericExtrinsicParams; // pub type TargetBAdditionalParams = GenericAdditionalParams; +pub type TargetBTip = AssetTip; +pub type TargetBRuntimeConfig = ParentchainRuntimeConfig; + pub type TargetBSignedExtra = GenericSignedExtra; pub type TargetBSignature = Signature; @@ -64,26 +61,18 @@ pub type TargetBUncheckedExtrinsic = /// Signature type of the [UncheckedExtrinsicV4]. pub type Signature = Option<(Address, PairSignature, SignedExtra)>; +use crate::ParentchainRuntimeConfig; #[cfg(feature = "std")] pub use api::*; #[cfg(feature = "std")] mod api { - use crate::{integritee::api_client_types::AssetTip, ParentchainRuntimeConfig}; - use itp_api_client_types::PlainTip; - use itp_node_api::api_client::AccountApi; - use itp_types::parentchain::Balance; + use super::TargetBRuntimeConfig; + use substrate_api_client::Api; pub use substrate_api_client::{ api::Error as ApiClientError, rpc::{tungstenite_client::TungsteniteRpcClient, Error as RpcClientError}, }; - use substrate_api_client::{ - Api, GetBalance, GetChainInfo, GetStorage, GetTransactionPayment, SubscribeEvents, - }; - - pub type TargetBTip = AssetTip; - pub type TargetBNodeConfig = ParentchainRuntimeConfig; - pub type TargetBApi = Api, TungsteniteRpcClient>; - // impl ParentchainApiTrait for TargetBApi {} + pub type TargetBApi = Api; } diff --git a/core-primitives/node-api/api-client-extensions/src/account.rs b/core-primitives/node-api/api-client-extensions/src/account.rs index 46e6129615..62f289a3e3 100644 --- a/core-primitives/node-api/api-client-extensions/src/account.rs +++ b/core-primitives/node-api/api-client-extensions/src/account.rs @@ -16,7 +16,6 @@ */ use crate::ApiResult; use itp_api_client_types::{traits::GetAccountInformation, Api, Config, Request}; -use substrate_api_client::ac_primitives::AccountData; /// ApiClient extension that contains some convenience methods around accounts. // Todo: make generic over `Config` type instead? @@ -29,25 +28,6 @@ pub trait AccountApi { fn get_free_balance(&self, who: &Self::AccountId) -> ApiResult; } -// impl AccountApi for Api -// where -// Client: Request, -// ParentchainRuntimeConfig: -// Config::Balance>>, -// { -// type AccountId = ::AccountId; -// type Index = ::Index; -// type Balance = ::Balance; -// -// fn get_nonce_of(&self, who: &Self::AccountId) -> ApiResult { -// Ok(self.get_account_info(who)?.map(|info| info.nonce).unwrap_or_default()) -// } -// -// fn get_free_balance(&self, who: &Self::AccountId) -> ApiResult { -// Ok(self.get_account_data(who)?.map(|data| data.free).unwrap_or_default()) -// } -// } - impl AccountApi for Api where Client: Request, diff --git a/core-primitives/node-api/factory/src/lib.rs b/core-primitives/node-api/factory/src/lib.rs index 89186855c0..cd0e5f0748 100644 --- a/core-primitives/node-api/factory/src/lib.rs +++ b/core-primitives/node-api/factory/src/lib.rs @@ -15,7 +15,7 @@ limitations under the License. */ -use itp_api_client_types::{traits::Request, Api, Config, ParentchainApi, TungsteniteRpcClient}; +use itp_api_client_types::{traits::Request, Api, Config, TungsteniteRpcClient}; use sp_core::sr25519; use std::marker::PhantomData; diff --git a/service/src/account_funding.rs b/service/src/account_funding.rs index 84b9be32a5..1b53ccea93 100644 --- a/service/src/account_funding.rs +++ b/service/src/account_funding.rs @@ -17,9 +17,7 @@ use crate::error::{Error, ServiceResult}; use codec::Encode; -use ita_parentchain_interface::{ - integritee::api_client_types::Config, ParentchainApiTrait, ParentchainRuntimeConfig, -}; +use ita_parentchain_interface::{integritee::api_client_types::Config, ParentchainRuntimeConfig}; use itp_node_api::api_client::{AccountApi, TEEREX}; use itp_settings::worker::REGISTERING_FEE_FACTOR_FOR_INIT_FUNDS; use itp_types::{ diff --git a/service/src/main_impl.rs b/service/src/main_impl.rs index f70218d9ec..4a6c7186ab 100644 --- a/service/src/main_impl.rs +++ b/service/src/main_impl.rs @@ -79,9 +79,9 @@ use ita_parentchain_interface::{ api_client_types::{IntegriteeApi, IntegriteeTip}, api_factory::IntegriteeNodeApiFactory, }, - target_a::api_client_types::{TargetAApi, TargetANodeConfig}, - target_b::api_client_types::{TargetBApi, TargetBNodeConfig}, - ParentchainApiTrait, ParentchainRuntimeConfig, + target_a::api_client_types::{TargetAApi, TargetARuntimeConfig}, + target_b::api_client_types::{TargetBApi, TargetBRuntimeConfig}, + ParentchainRuntimeConfig, }; use itc_parentchain::primitives::ParentchainId; use itp_node_api::api_client::ChainApi; @@ -182,12 +182,18 @@ pub(crate) fn main() { let maybe_target_a_parentchain_api_factory = config.target_a_parentchain_rpc_endpoint().map(|url| { - Arc::new(NodeApiFactory::::new(url, AccountKeyring::Alice.pair())) + Arc::new(NodeApiFactory::::new( + url, + AccountKeyring::Alice.pair(), + )) }); let maybe_target_b_parentchain_api_factory = config.target_b_parentchain_rpc_endpoint().map(|url| { - Arc::new(NodeApiFactory::::new(url, AccountKeyring::Alice.pair())) + Arc::new(NodeApiFactory::::new( + url, + AccountKeyring::Alice.pair(), + )) }); // initialize o-call bridge with a concrete factory implementation diff --git a/service/src/ocall_bridge/worker_on_chain_ocall.rs b/service/src/ocall_bridge/worker_on_chain_ocall.rs index 8dacbbb69a..3ef849d3d6 100644 --- a/service/src/ocall_bridge/worker_on_chain_ocall.rs +++ b/service/src/ocall_bridge/worker_on_chain_ocall.rs @@ -23,7 +23,7 @@ use ita_parentchain_interface::{ integritee::{api_client_types::IntegriteeApi, api_factory::IntegriteeNodeApiFactory}, target_a::{api_client_types::TargetAApi, api_factory::TargetANodeApiFactory}, target_b::{api_client_types::TargetBApi, api_factory::TargetBNodeApiFactory}, - ParentchainApiTrait, ParentchainRuntimeConfig, + ParentchainRuntimeConfig, }; use itp_api_client_types::{ParentchainApi, Request}; use itp_node_api::{ diff --git a/service/src/parentchain_handler.rs b/service/src/parentchain_handler.rs index 4dd6bd4e91..0db2d42b62 100644 --- a/service/src/parentchain_handler.rs +++ b/service/src/parentchain_handler.rs @@ -19,9 +19,7 @@ use crate::error::{Error, ServiceResult}; use codec::{Decode, Encode}; use humantime::format_duration; -use ita_parentchain_interface::{ - integritee::Header, ParentchainApiTrait, ParentchainRuntimeConfig, -}; +use ita_parentchain_interface::{integritee::Header, ParentchainRuntimeConfig}; use itc_parentchain::{ light_client::light_client_init_params::{GrandpaParams, SimpleParams}, primitives::{ParentchainId, ParentchainInitParams}, diff --git a/service/src/worker.rs b/service/src/worker.rs index 634c4d7840..f3cb7323a1 100644 --- a/service/src/worker.rs +++ b/service/src/worker.rs @@ -21,7 +21,6 @@ /// multiple traits. use crate::{config::Config, error::Error, initialized_service::TrackInitialization}; use async_trait::async_trait; -use ita_parentchain_interface::ParentchainApiTrait; use itc_rpc_client::direct_client::{DirectApi, DirectClient as DirectWorkerApi}; use itp_api_client_types::{Config as NodeRuntimeConfig, Request}; use itp_node_api::{ From bd7d29a1314955c8087b40ce066ec9a5b206d4b1 Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Fri, 22 Nov 2024 13:00:56 +0100 Subject: [PATCH 10/23] wip splitting up extrinsic factory --- core-primitives/extrinsics-factory/src/lib.rs | 64 +++++++++---- .../extrinsics-factory/src/mock.rs | 24 +++-- .../src/initialization/global_components.rs | 80 +++++++++++++---- .../src/initialization/parentchain/common.rs | 26 +++--- .../parentchain/integritee_parachain.rs | 8 +- .../parentchain/integritee_solochain.rs | 3 +- .../parentchain/target_a_parachain.rs | 11 +-- .../parentchain/target_a_solochain.rs | 9 +- .../parentchain/target_b_parachain.rs | 11 +-- .../parentchain/target_b_solochain.rs | 9 +- enclave-runtime/src/shard_vault.rs | 90 +++++++++++++------ enclave-runtime/src/utils.rs | 12 +-- 12 files changed, 234 insertions(+), 113 deletions(-) diff --git a/core-primitives/extrinsics-factory/src/lib.rs b/core-primitives/extrinsics-factory/src/lib.rs index 89b5909a29..01adb8330b 100644 --- a/core-primitives/extrinsics-factory/src/lib.rs +++ b/core-primitives/extrinsics-factory/src/lib.rs @@ -30,22 +30,24 @@ pub mod sgx_reexport_prelude { } use codec::Encode; +use core::marker::{PhantomData, PhantomPinned}; use error::Result; use itp_node_api::{ api_client::{ - ExtrinsicParams, ParentchainAdditionalParams, ParentchainExtrinsicParams, SignExtrinsic, + ExtrinsicParams, GenericAdditionalParams, GenericExtrinsicParams, + ParentchainExtrinsicParams, SignExtrinsic, }, metadata::{provider::AccessNodeMetadata, NodeMetadata}, }; use itp_nonce_cache::{MutateNonce, Nonce}; use itp_types::{ - parentchain::{AccountId, GenericMortality}, + parentchain::{AccountId, GenericMortality, Hash}, OpaqueCall, }; use sp_core::H256; use sp_runtime::OpaqueExtrinsic; use std::{sync::Arc, vec::Vec}; -use substrate_api_client::ac_compose_macros::compose_extrinsic_offline; +use substrate_api_client::{ac_compose_macros::compose_extrinsic_offline, ac_primitives::Config}; pub mod error; @@ -56,32 +58,44 @@ pub mod mock; /// /// Also increases the nonce counter for each extrinsic that is created. pub trait CreateExtrinsics { + type Config: Config; + type ExtrinsicParams: ExtrinsicParams< + ::Index, + ::Hash, + >; + fn create_extrinsics( &self, calls: &[(OpaqueCall, GenericMortality)], - extrinsics_params: Option, + extrinsics_params: Option>, ) -> Result>; } +pub type AdditionParamsOf = + ::Index, ::Hash>>::AdditionalParams; + /// Extrinsics factory -pub struct ExtrinsicsFactory +pub struct ExtrinsicsFactory where Signer: SignExtrinsic, NonceCache: MutateNonce, NodeMetadataRepository: AccessNodeMetadata, + NodeRuntimeConfig: Config, { genesis_hash: H256, signer: Signer, nonce_cache: Arc, pub node_metadata_repository: Arc, + phantom: PhantomData<(NodeRuntimeConfig, Tip)>, } -impl - ExtrinsicsFactory +impl + ExtrinsicsFactory where Signer: SignExtrinsic, NonceCache: MutateNonce, NodeMetadataRepository: AccessNodeMetadata, + NodeRuntimeConfig: Config, { pub fn new( genesis_hash: H256, @@ -89,7 +103,13 @@ where nonce_cache: Arc, node_metadata_repository: Arc, ) -> Self { - ExtrinsicsFactory { genesis_hash, signer, nonce_cache, node_metadata_repository } + ExtrinsicsFactory { + genesis_hash, + signer, + nonce_cache, + node_metadata_repository, + phantom: Default::default(), + } } pub fn with_signer(&self, signer: Signer, nonce_cache: Arc) -> Self { @@ -98,21 +118,29 @@ where signer, nonce_cache, node_metadata_repository: self.node_metadata_repository.clone(), + phantom: Default::default(), } } } -impl CreateExtrinsics - for ExtrinsicsFactory +impl CreateExtrinsics + for ExtrinsicsFactory where Signer: SignExtrinsic, NonceCache: MutateNonce, NodeMetadataRepository: AccessNodeMetadata, + NodeRuntimeConfig: Config, + u128: From, + Tip: Copy + Default + Encode, { + type Config = NodeRuntimeConfig; + + type ExtrinsicParams = GenericExtrinsicParams; + fn create_extrinsics( &self, calls: &[(OpaqueCall, GenericMortality)], - extrinsics_params: Option, + extrinsics_params: Option>, ) -> Result> { let mut nonce_lock = self.nonce_cache.load_for_mutation()?; let mut nonce_value = nonce_lock.0; @@ -126,17 +154,15 @@ where .iter() .map(|(call, mortality)| { let additional_extrinsic_params = extrinsics_params.unwrap_or_else(|| { - ParentchainAdditionalParams::new() - .era( - mortality.era, - mortality.mortality_checkpoint.unwrap_or(self.genesis_hash), - ) - .tip(0) + GenericAdditionalParams::new().era( + mortality.era, + mortality.mortality_checkpoint.unwrap_or(self.genesis_hash), + ) }); - let extrinsic_params = ParentchainExtrinsicParams::new( + let extrinsic_params = GenericExtrinsicParams::::new( runtime_spec_version, runtime_transaction_version, - nonce_value, + nonce_value.into(), self.genesis_hash, additional_extrinsic_params, ); diff --git a/core-primitives/extrinsics-factory/src/mock.rs b/core-primitives/extrinsics-factory/src/mock.rs index dfa6017a86..d73805b925 100644 --- a/core-primitives/extrinsics-factory/src/mock.rs +++ b/core-primitives/extrinsics-factory/src/mock.rs @@ -14,10 +14,13 @@ limitations under the License. */ - -use crate::{error::Result, CreateExtrinsics}; -use itp_node_api::api_client::ParentchainAdditionalParams; -use itp_types::{parentchain::GenericMortality, OpaqueCall}; +use crate::{error::Result, AdditionParamsOf, CreateExtrinsics}; +use codec::Encode; +use core::marker::PhantomData; +use itp_node_api::api_client::{ + Config, GenericAdditionalParams, GenericExtrinsicParams, ParentchainRuntimeConfig, PlainTip, +}; +use itp_types::{parentchain::GenericMortality, Balance, OpaqueCall, H256}; use sp_runtime::OpaqueExtrinsic; use std::vec::Vec; @@ -25,13 +28,20 @@ use std::vec::Vec; /// /// Returns an empty extrinsic. #[derive(Default, Clone)] -pub struct ExtrinsicsFactoryMock; +pub struct ExtrinsicsFactoryMock { + _phantom: PhantomData, +} + +impl CreateExtrinsics for ExtrinsicsFactoryMock { + type Config = ParentchainRuntimeConfig; + type ExtrinsicParams = GenericExtrinsicParams>; -impl CreateExtrinsics for ExtrinsicsFactoryMock { fn create_extrinsics( &self, _calls: &[(OpaqueCall, GenericMortality)], - _additional_params: Option, + _additional_params: Option< + AdditionParamsOf, + >, ) -> Result> { // Intention was to map an OpaqueCall to some dummy OpaqueExtrinsic, // so the output vector has the same size as the input one (and thus can be tested from the outside). diff --git a/enclave-runtime/src/initialization/global_components.rs b/enclave-runtime/src/initialization/global_components.rs index ac378c8597..531dfa9c8d 100644 --- a/enclave-runtime/src/initialization/global_components.rs +++ b/enclave-runtime/src/initialization/global_components.rs @@ -30,7 +30,14 @@ use crate::{ rpc::rpc_response_channel::RpcResponseChannel, tls_ra::seal_handler::SealHandler, }; -use ita_parentchain_interface::{integritee, target_a, target_b}; +use ita_parentchain_interface::{ + integritee, + integritee::api_client_types::{IntegriteeRuntimeConfig, IntegriteeTip}, + target_a, + target_a::api_client_types::{TargetARuntimeConfig, TargetATip}, + target_b, + target_b::api_client_types::{TargetBRuntimeConfig, TargetBTip}, +}; use ita_sgx_runtime::Runtime; use ita_stf::{Getter, State as StfState, Stf, TrustedCallSigned}; use itc_direct_rpc_server::{ @@ -144,8 +151,36 @@ pub type EnclaveSidechainApi = SidechainApi>; -pub type EnclaveExtrinsicsFactory = - ExtrinsicsFactory; + +pub type EnclaveExtrinsicsFactory = ExtrinsicsFactory< + EnclaveParentchainSigner, + NonceCache, + EnclaveNodeMetadataRepository, + NodeRuntimeConfig, + Tip, +>; + +pub type IntegriteeEnclaveExtrinsicsFactory = ExtrinsicsFactory< + EnclaveParentchainSigner, + NonceCache, + EnclaveNodeMetadataRepository, + IntegriteeRuntimeConfig, + IntegriteeTip, +>; +pub type TargetAEnclaveExtrinsicsFactory = ExtrinsicsFactory< + EnclaveParentchainSigner, + NonceCache, + EnclaveNodeMetadataRepository, + TargetARuntimeConfig, + TargetATip, +>; +pub type TargetBEnclaveExtrinsicsFactory = ExtrinsicsFactory< + EnclaveParentchainSigner, + NonceCache, + EnclaveNodeMetadataRepository, + TargetBRuntimeConfig, + TargetBTip, +>; pub type EnclaveValidatorAccessor = ValidatorAccessor< LightValidation, @@ -182,7 +217,7 @@ pub type IntegriteeParentchainBlockImporter = ParentchainBlockImporter< ParentchainBlock, EnclaveValidatorAccessor, EnclaveStfExecutor, - EnclaveExtrinsicsFactory, + IntegriteeEnclaveExtrinsicsFactory, IntegriteeParentchainIndirectCallsExecutor, >; @@ -224,7 +259,7 @@ pub type TargetAParentchainBlockImporter = ParentchainBlockImporter< ParentchainBlock, EnclaveValidatorAccessor, EnclaveStfExecutor, - EnclaveExtrinsicsFactory, + TargetAEnclaveExtrinsicsFactory, TargetAParentchainIndirectCallsExecutor, >; @@ -266,7 +301,7 @@ pub type TargetBParentchainBlockImporter = ParentchainBlockImporter< ParentchainBlock, EnclaveValidatorAccessor, EnclaveStfExecutor, - EnclaveExtrinsicsFactory, + TargetBEnclaveExtrinsicsFactory, TargetBParentchainIndirectCallsExecutor, >; @@ -320,7 +355,7 @@ pub type EnclaveBlockImportConfirmationHandler = BlockImportConfirmationHandler< ParentchainBlock, <::Block as SidechainBlockTrait>::HeaderType, EnclaveNodeMetadataRepository, - EnclaveExtrinsicsFactory, + IntegriteeEnclaveExtrinsicsFactory, EnclaveValidatorAccessor, >; pub type EnclaveSidechainBlockSyncer = PeerBlockSync< @@ -342,17 +377,26 @@ pub type EnclaveSealHandler = SealHandler< EnclaveStateHandler, EnclaveLightClientSeal, >; -pub type EnclaveOffchainWorkerExecutor = itc_offchain_worker_executor::executor::Executor< - ParentchainBlock, - EnclaveTopPoolAuthor, - EnclaveStfExecutor, - EnclaveStateHandler, - EnclaveValidatorAccessor, - EnclaveExtrinsicsFactory, - EnclaveStf, - EnclaveTrustedCallSigned, - EnclaveGetter, ->; + +pub type IntegriteeOffchainWorkerExecutor = + EnclaveOffchainWorkerExecutor; +pub type TargetAOffchainWorkerExecutor = + EnclaveOffchainWorkerExecutor; +pub type TargetBOffchainWorkerExecutor = + EnclaveOffchainWorkerExecutor; + +pub type EnclaveOffchainWorkerExecutor = + itc_offchain_worker_executor::executor::Executor< + ParentchainBlock, + EnclaveTopPoolAuthor, + EnclaveStfExecutor, + EnclaveStateHandler, + EnclaveValidatorAccessor, + ExtrinsicsFactory, + EnclaveStf, + EnclaveTrustedCallSigned, + EnclaveGetter, + >; // Base component instances //------------------------------------------------------------------------------------------------- diff --git a/enclave-runtime/src/initialization/parentchain/common.rs b/enclave-runtime/src/initialization/parentchain/common.rs index 01832132a0..235c736daa 100644 --- a/enclave-runtime/src/initialization/parentchain/common.rs +++ b/enclave-runtime/src/initialization/parentchain/common.rs @@ -21,16 +21,17 @@ use crate::{ global_components::{ EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOffchainWorkerExecutor, EnclaveParentchainSigner, EnclaveStfExecutor, EnclaveValidatorAccessor, - IntegriteeParentchainBlockImportDispatcher, IntegriteeParentchainBlockImportQueue, - IntegriteeParentchainBlockImporter, IntegriteeParentchainEventImportQueue, + IntegriteeEnclaveExtrinsicsFactory, IntegriteeParentchainBlockImportDispatcher, + IntegriteeParentchainBlockImportQueue, IntegriteeParentchainBlockImporter, + IntegriteeParentchainEventImportQueue, IntegriteeParentchainImmediateBlockImportDispatcher, IntegriteeParentchainIndirectCallsExecutor, - IntegriteeParentchainTriggeredBlockImportDispatcher, + IntegriteeParentchainTriggeredBlockImportDispatcher, TargetAEnclaveExtrinsicsFactory, TargetAParentchainBlockImportDispatcher, TargetAParentchainBlockImportQueue, TargetAParentchainBlockImporter, TargetAParentchainEventImportQueue, TargetAParentchainImmediateBlockImportDispatcher, TargetAParentchainIndirectCallsExecutor, - TargetAParentchainTriggeredBlockImportDispatcher, + TargetAParentchainTriggeredBlockImportDispatcher, TargetBEnclaveExtrinsicsFactory, TargetBParentchainBlockImportDispatcher, TargetBParentchainBlockImportQueue, TargetBParentchainBlockImporter, TargetBParentchainEventImportQueue, TargetBParentchainImmediateBlockImportDispatcher, @@ -43,6 +44,7 @@ use crate::{ EnclaveStfEnclaveSigner, }, }; +use ita_parentchain_interface::target_a::api_client_types::Config; use itp_component_container::ComponentGetter; use itp_nonce_cache::NonceCache; use itp_sgx_crypto::key_repository::AccessKey; @@ -55,7 +57,7 @@ use std::sync::Arc; pub(crate) fn create_integritee_parentchain_block_importer( validator_access: Arc, stf_executor: Arc, - extrinsics_factory: Arc, + extrinsics_factory: Arc, node_metadata_repository: Arc, shard_creation_info: ShardCreationInfo, ) -> Result { @@ -90,7 +92,7 @@ pub(crate) fn create_integritee_parentchain_block_importer( pub(crate) fn create_target_a_parentchain_block_importer( validator_access: Arc, stf_executor: Arc, - extrinsics_factory: Arc, + extrinsics_factory: Arc, node_metadata_repository: Arc, shard_creation_info: ShardCreationInfo, ) -> Result { @@ -125,7 +127,7 @@ pub(crate) fn create_target_a_parentchain_block_importer( pub(crate) fn create_target_b_parentchain_block_importer( validator_access: Arc, stf_executor: Arc, - extrinsics_factory: Arc, + extrinsics_factory: Arc, node_metadata_repository: Arc, shard_creation_info: ShardCreationInfo, ) -> Result { @@ -157,11 +159,11 @@ pub(crate) fn create_target_b_parentchain_block_importer( )) } -pub(crate) fn create_extrinsics_factory( +pub(crate) fn create_extrinsics_factory( genesis_hash: H256, nonce_cache: Arc, node_metadata_repository: Arc, -) -> Result> { +) -> Result>> { let signer = GLOBAL_SIGNING_KEY_REPOSITORY_COMPONENT.get()?.retrieve_key()?; Ok(Arc::new(EnclaveExtrinsicsFactory::new( @@ -176,7 +178,7 @@ pub(crate) fn create_integritee_offchain_immediate_import_dispatcher( stf_executor: Arc, block_importer: IntegriteeParentchainBlockImporter, validator_access: Arc, - extrinsics_factory: Arc, + extrinsics_factory: Arc, ) -> Result> { let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; let top_pool_author = GLOBAL_TOP_POOL_AUTHOR_COMPONENT.get()?; @@ -206,7 +208,7 @@ pub(crate) fn create_target_a_offchain_immediate_import_dispatcher( stf_executor: Arc, block_importer: TargetAParentchainBlockImporter, validator_access: Arc, - extrinsics_factory: Arc, + extrinsics_factory: Arc, ) -> Result> { let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; let top_pool_author = GLOBAL_TOP_POOL_AUTHOR_COMPONENT.get()?; @@ -236,7 +238,7 @@ pub(crate) fn create_target_b_offchain_immediate_import_dispatcher( stf_executor: Arc, block_importer: TargetBParentchainBlockImporter, validator_access: Arc, - extrinsics_factory: Arc, + extrinsics_factory: Arc, ) -> Result> { let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; let top_pool_author = GLOBAL_TOP_POOL_AUTHOR_COMPONENT.get()?; diff --git a/enclave-runtime/src/initialization/parentchain/integritee_parachain.rs b/enclave-runtime/src/initialization/parentchain/integritee_parachain.rs index d6264c2ea4..5f55a2ff52 100644 --- a/enclave-runtime/src/initialization/parentchain/integritee_parachain.rs +++ b/enclave-runtime/src/initialization/parentchain/integritee_parachain.rs @@ -19,9 +19,8 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, - EnclaveStfExecutor, EnclaveValidatorAccessor, - IntegriteeParentchainBlockImportDispatcher, + EnclaveNodeMetadataRepository, EnclaveOCallApi, EnclaveStfExecutor, + EnclaveValidatorAccessor, IntegriteeParentchainBlockImportDispatcher, GLOBAL_INTEGRITEE_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE, GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, @@ -39,6 +38,7 @@ use itp_settings::worker_mode::{ProvideWorkerMode, WorkerMode}; use itp_types::parentchain::ParentchainId; use std::{path::PathBuf, sync::Arc}; +use crate::initialization::global_components::IntegriteeEnclaveExtrinsicsFactory; pub use itc_parentchain::primitives::{ParachainBlock, ParachainHeader, ParachainParams}; use itp_stf_interface::ShardCreationInfo; @@ -48,7 +48,7 @@ pub struct IntegriteeParachainHandler { pub node_metadata_repository: Arc, pub stf_executor: Arc, pub validator_accessor: Arc, - pub extrinsics_factory: Arc, + pub extrinsics_factory: Arc, pub import_dispatcher: Arc, } diff --git a/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs b/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs index 37b95135e5..0dd6382912 100644 --- a/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs +++ b/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs @@ -39,6 +39,7 @@ use itp_settings::worker_mode::{ProvideWorkerMode, WorkerMode}; use itp_types::parentchain::ParentchainId; use std::{path::PathBuf, sync::Arc}; +use crate::initialization::global_components::IntegriteeEnclaveExtrinsicsFactory; pub use itc_parentchain::primitives::{SolochainBlock, SolochainHeader, SolochainParams}; use itp_stf_interface::ShardCreationInfo; @@ -47,7 +48,7 @@ pub struct IntegriteeSolochainHandler { pub node_metadata_repository: Arc, pub stf_executor: Arc, pub validator_accessor: Arc, - pub extrinsics_factory: Arc, + pub extrinsics_factory: Arc, pub import_dispatcher: Arc, } diff --git a/enclave-runtime/src/initialization/parentchain/target_a_parachain.rs b/enclave-runtime/src/initialization/parentchain/target_a_parachain.rs index 31799d636a..6f56f47c93 100644 --- a/enclave-runtime/src/initialization/parentchain/target_a_parachain.rs +++ b/enclave-runtime/src/initialization/parentchain/target_a_parachain.rs @@ -25,10 +25,11 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, - EnclaveStfExecutor, EnclaveValidatorAccessor, TargetAParentchainBlockImportDispatcher, - GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE, + EnclaveNodeMetadataRepository, EnclaveOCallApi, EnclaveStfExecutor, + EnclaveValidatorAccessor, TargetAEnclaveExtrinsicsFactory, + TargetAParentchainBlockImportDispatcher, GLOBAL_OCALL_API_COMPONENT, + GLOBAL_STATE_HANDLER_COMPONENT, GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL, + GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE, }, parentchain::common::{ create_extrinsics_factory, create_sidechain_triggered_import_dispatcher_for_target_a, @@ -51,7 +52,7 @@ pub struct TargetAParachainHandler { pub node_metadata_repository: Arc, pub stf_executor: Arc, pub validator_accessor: Arc, - pub extrinsics_factory: Arc, + pub extrinsics_factory: Arc, pub import_dispatcher: Arc, } diff --git a/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs b/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs index 4348dc8e19..aafb4b460f 100644 --- a/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs +++ b/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs @@ -20,9 +20,10 @@ use crate::{ initialization::{ global_components::{ EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, - EnclaveStfExecutor, EnclaveValidatorAccessor, TargetAParentchainBlockImportDispatcher, - GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE, + EnclaveStfExecutor, EnclaveValidatorAccessor, TargetAEnclaveExtrinsicsFactory, + TargetAParentchainBlockImportDispatcher, GLOBAL_OCALL_API_COMPONENT, + GLOBAL_STATE_HANDLER_COMPONENT, GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL, + GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE, }, parentchain::common::{ create_extrinsics_factory, create_sidechain_triggered_import_dispatcher_for_target_a, @@ -44,7 +45,7 @@ pub struct TargetASolochainHandler { pub node_metadata_repository: Arc, pub stf_executor: Arc, pub validator_accessor: Arc, - pub extrinsics_factory: Arc, + pub extrinsics_factory: Arc, pub import_dispatcher: Arc, } diff --git a/enclave-runtime/src/initialization/parentchain/target_b_parachain.rs b/enclave-runtime/src/initialization/parentchain/target_b_parachain.rs index 113103ee87..e04ddbc90e 100644 --- a/enclave-runtime/src/initialization/parentchain/target_b_parachain.rs +++ b/enclave-runtime/src/initialization/parentchain/target_b_parachain.rs @@ -25,10 +25,11 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, - EnclaveStfExecutor, EnclaveValidatorAccessor, TargetBParentchainBlockImportDispatcher, - GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE, + EnclaveNodeMetadataRepository, EnclaveOCallApi, EnclaveStfExecutor, + EnclaveValidatorAccessor, TargetBEnclaveExtrinsicsFactory, + TargetBParentchainBlockImportDispatcher, GLOBAL_OCALL_API_COMPONENT, + GLOBAL_STATE_HANDLER_COMPONENT, GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL, + GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE, }, parentchain::common::{ create_extrinsics_factory, create_sidechain_triggered_import_dispatcher_for_target_b, @@ -51,7 +52,7 @@ pub struct TargetBParachainHandler { pub node_metadata_repository: Arc, pub stf_executor: Arc, pub validator_accessor: Arc, - pub extrinsics_factory: Arc, + pub extrinsics_factory: Arc, pub import_dispatcher: Arc, } diff --git a/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs b/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs index edab731e6d..bcf706970d 100644 --- a/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs +++ b/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs @@ -20,9 +20,10 @@ use crate::{ initialization::{ global_components::{ EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, - EnclaveStfExecutor, EnclaveValidatorAccessor, TargetBParentchainBlockImportDispatcher, - GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE, + EnclaveStfExecutor, EnclaveValidatorAccessor, TargetBEnclaveExtrinsicsFactory, + TargetBParentchainBlockImportDispatcher, GLOBAL_OCALL_API_COMPONENT, + GLOBAL_STATE_HANDLER_COMPONENT, GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL, + GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE, }, parentchain::common::{ create_extrinsics_factory, create_sidechain_triggered_import_dispatcher_for_target_b, @@ -44,7 +45,7 @@ pub struct TargetBSolochainHandler { pub node_metadata_repository: Arc, pub stf_executor: Arc, pub validator_accessor: Arc, - pub extrinsics_factory: Arc, + pub extrinsics_factory: Arc, pub import_dispatcher: Arc, } diff --git a/enclave-runtime/src/shard_vault.rs b/enclave-runtime/src/shard_vault.rs index a79cd476f7..11e42071d4 100644 --- a/enclave-runtime/src/shard_vault.rs +++ b/enclave-runtime/src/shard_vault.rs @@ -16,7 +16,8 @@ use crate::{ error::{Error, Result as EnclaveResult}, initialization::global_components::{ - EnclaveStf, GLOBAL_OCALL_API_COMPONENT, GLOBAL_SIGNING_KEY_REPOSITORY_COMPONENT, + EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveStf, + GLOBAL_OCALL_API_COMPONENT, GLOBAL_SIGNING_KEY_REPOSITORY_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, }, std::string::ToString, @@ -31,9 +32,9 @@ use crate::{ }; use codec::{Compact, Decode, Encode}; use itp_component_container::ComponentGetter; -use itp_extrinsics_factory::CreateExtrinsics; +use itp_extrinsics_factory::{CreateExtrinsics, ExtrinsicsFactory}; use itp_node_api::{ - api_client::{PairSignature, StaticExtrinsicSigner}, + api_client::{Config, PairSignature, StaticExtrinsicSigner}, metadata::provider::{AccessNodeMetadata, Error as MetadataProviderError}, }; use itp_node_api_metadata::pallet_proxy::ProxyCallIndexes; @@ -47,6 +48,7 @@ use itp_types::{ OpaqueCall, ShardIdentifier, }; use log::*; +use primitive_types::H256; use sgx_types::sgx_status_t; use sp_core::crypto::{DeriveJunction, Pair}; use std::{slice, sync::Arc}; @@ -130,6 +132,61 @@ pub(crate) fn init_proxied_shard_vault_internal( parentchain_id: ParentchainId, funding_balance: Balance, ) -> EnclaveResult<()> { + match parentchain_id { + ParentchainId::Integritee => { + let enclave_extrinsics_factory = + get_extrinsic_factory_from_integritee_solo_or_parachain()?; + let node_metadata_repo = + get_node_metadata_repository_from_integritee_solo_or_parachain()?; + init_shard( + shard, + parentchain_id, + funding_balance, + enclave_extrinsics_factory, + node_metadata_repo, + ) + }, + ParentchainId::TargetA => { + let enclave_extrinsics_factory = + get_extrinsic_factory_from_target_a_solo_or_parachain()?; + let node_metadata_repo = + get_node_metadata_repository_from_target_a_solo_or_parachain()?; + init_shard( + shard, + parentchain_id, + funding_balance, + enclave_extrinsics_factory, + node_metadata_repo, + ) + }, + ParentchainId::TargetB => { + let enclave_extrinsics_factory = + get_extrinsic_factory_from_target_b_solo_or_parachain()?; + let node_metadata_repo = + get_node_metadata_repository_from_target_b_solo_or_parachain()?; + init_shard( + shard, + parentchain_id, + funding_balance, + enclave_extrinsics_factory, + node_metadata_repo, + ) + }, + } +} + +fn init_shard( + shard: ShardIdentifier, + parentchain_id: ParentchainId, + funding_balance: Balance, + enclave_extrinsics_factory: Arc>, + node_metadata_repository: Arc, +) -> EnclaveResult<()> +where + NodeRuntimeConfig: Config, + u128: From, + Tip: Copy + Default + Encode, +{ let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; if !state_handler .shard_exists(&shard) @@ -150,35 +207,12 @@ pub(crate) fn init_proxied_shard_vault_internal( EnclaveStf::init_shard_vault_account(&mut state, vault.public().into(), parentchain_id) .map_err(|e| Error::Stf(e.to_string()))?; state_handler.write_after_mutation(state, state_lock, &shard)?; - let (enclave_extrinsics_factory, node_metadata_repo) = match parentchain_id { - ParentchainId::Integritee => { - let enclave_extrinsics_factory = - get_extrinsic_factory_from_integritee_solo_or_parachain()?; - let node_metadata_repo = - get_node_metadata_repository_from_integritee_solo_or_parachain()?; - (enclave_extrinsics_factory, node_metadata_repo) - }, - ParentchainId::TargetA => { - let enclave_extrinsics_factory = - get_extrinsic_factory_from_target_a_solo_or_parachain()?; - let node_metadata_repo = - get_node_metadata_repository_from_target_a_solo_or_parachain()?; - (enclave_extrinsics_factory, node_metadata_repo) - }, - ParentchainId::TargetB => { - let enclave_extrinsics_factory = - get_extrinsic_factory_from_target_b_solo_or_parachain()?; - let node_metadata_repo = - get_node_metadata_repository_from_target_b_solo_or_parachain()?; - (enclave_extrinsics_factory, node_metadata_repo) - }, - }; info!( "[{:?}] send existential funds from enclave account to vault account: {:?}", parentchain_id, funding_balance ); - let call_ids = node_metadata_repo + let call_ids = node_metadata_repository .get_from_metadata(|m| m.call_indexes("Balances", "transfer_keep_alive"))? .map_err(MetadataProviderError::MetadataError)?; @@ -201,7 +235,7 @@ pub(crate) fn init_proxied_shard_vault_internal( .with_signer(StaticExtrinsicSigner::<_, PairSignature>::new(vault), nonce_cache); info!("[{:?}] register enclave signer as proxy for shard vault", parentchain_id); - let call_ids = node_metadata_repo + let call_ids = node_metadata_repository .get_from_metadata(|m| m.call_indexes("Proxy", "add_proxy"))? .map_err(MetadataProviderError::MetadataError)?; diff --git a/enclave-runtime/src/utils.rs b/enclave-runtime/src/utils.rs index 81c175a007..2f1c96350b 100644 --- a/enclave-runtime/src/utils.rs +++ b/enclave-runtime/src/utils.rs @@ -18,9 +18,9 @@ use crate::{ error::{Error, Result}, initialization::global_components::{ EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveStfEnclaveSigner, - EnclaveStfExecutor, EnclaveValidatorAccessor, - IntegriteeParentchainTriggeredBlockImportDispatcher, - TargetAParentchainTriggeredBlockImportDispatcher, + EnclaveStfExecutor, EnclaveValidatorAccessor, IntegriteeEnclaveExtrinsicsFactory, + IntegriteeParentchainTriggeredBlockImportDispatcher, TargetAEnclaveExtrinsicsFactory, + TargetAParentchainTriggeredBlockImportDispatcher, TargetBEnclaveExtrinsicsFactory, TargetBParentchainTriggeredBlockImportDispatcher, GLOBAL_INTEGRITEE_PARACHAIN_HANDLER_COMPONENT, GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE, GLOBAL_INTEGRITEE_SOLOCHAIN_HANDLER_COMPONENT, GLOBAL_OCALL_API_COMPONENT, @@ -206,7 +206,7 @@ pub(crate) fn get_node_metadata_repository_from_target_b_solo_or_parachain( } pub(crate) fn get_extrinsic_factory_from_integritee_solo_or_parachain( -) -> Result> { +) -> Result> { let extrinsics_factory = if let Ok(solochain_handler) = GLOBAL_INTEGRITEE_SOLOCHAIN_HANDLER_COMPONENT.get() { solochain_handler.extrinsics_factory.clone() @@ -219,7 +219,7 @@ pub(crate) fn get_extrinsic_factory_from_integritee_solo_or_parachain( } pub(crate) fn get_extrinsic_factory_from_target_a_solo_or_parachain( -) -> Result> { +) -> Result> { let extrinsics_factory = if let Ok(solochain_handler) = GLOBAL_TARGET_A_SOLOCHAIN_HANDLER_COMPONENT.get() { solochain_handler.extrinsics_factory.clone() @@ -232,7 +232,7 @@ pub(crate) fn get_extrinsic_factory_from_target_a_solo_or_parachain( } pub(crate) fn get_extrinsic_factory_from_target_b_solo_or_parachain( -) -> Result> { +) -> Result> { let extrinsics_factory = if let Ok(solochain_handler) = GLOBAL_TARGET_B_SOLOCHAIN_HANDLER_COMPONENT.get() { solochain_handler.extrinsics_factory.clone() From 1d63d85fe77476f4045aa52feaa5655677018c70 Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Fri, 22 Nov 2024 13:19:46 +0100 Subject: [PATCH 11/23] cleanup --- core-primitives/extrinsics-factory/src/lib.rs | 9 +-- .../extrinsics-factory/src/mock.rs | 7 +- .../parentchain/integritee_solochain.rs | 5 +- .../parentchain/target_a_solochain.rs | 4 +- .../parentchain/target_b_solochain.rs | 4 +- enclave-runtime/src/shard_vault.rs | 80 +++++++++++++++---- enclave-runtime/src/utils.rs | 4 +- 7 files changed, 77 insertions(+), 36 deletions(-) diff --git a/core-primitives/extrinsics-factory/src/lib.rs b/core-primitives/extrinsics-factory/src/lib.rs index 01adb8330b..01f3db3677 100644 --- a/core-primitives/extrinsics-factory/src/lib.rs +++ b/core-primitives/extrinsics-factory/src/lib.rs @@ -30,18 +30,15 @@ pub mod sgx_reexport_prelude { } use codec::Encode; -use core::marker::{PhantomData, PhantomPinned}; +use core::marker::PhantomData; use error::Result; use itp_node_api::{ - api_client::{ - ExtrinsicParams, GenericAdditionalParams, GenericExtrinsicParams, - ParentchainExtrinsicParams, SignExtrinsic, - }, + api_client::{ExtrinsicParams, GenericAdditionalParams, GenericExtrinsicParams, SignExtrinsic}, metadata::{provider::AccessNodeMetadata, NodeMetadata}, }; use itp_nonce_cache::{MutateNonce, Nonce}; use itp_types::{ - parentchain::{AccountId, GenericMortality, Hash}, + parentchain::{AccountId, GenericMortality}, OpaqueCall, }; use sp_core::H256; diff --git a/core-primitives/extrinsics-factory/src/mock.rs b/core-primitives/extrinsics-factory/src/mock.rs index d73805b925..267ddb5187 100644 --- a/core-primitives/extrinsics-factory/src/mock.rs +++ b/core-primitives/extrinsics-factory/src/mock.rs @@ -15,12 +15,9 @@ */ use crate::{error::Result, AdditionParamsOf, CreateExtrinsics}; -use codec::Encode; use core::marker::PhantomData; -use itp_node_api::api_client::{ - Config, GenericAdditionalParams, GenericExtrinsicParams, ParentchainRuntimeConfig, PlainTip, -}; -use itp_types::{parentchain::GenericMortality, Balance, OpaqueCall, H256}; +use itp_node_api::api_client::{GenericExtrinsicParams, ParentchainRuntimeConfig, PlainTip}; +use itp_types::{parentchain::GenericMortality, Balance, OpaqueCall}; use sp_runtime::OpaqueExtrinsic; use std::vec::Vec; diff --git a/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs b/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs index 0dd6382912..c3727debc4 100644 --- a/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs +++ b/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs @@ -19,9 +19,8 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, - EnclaveStfExecutor, EnclaveValidatorAccessor, - IntegriteeParentchainBlockImportDispatcher, + EnclaveNodeMetadataRepository, EnclaveOCallApi, EnclaveStfExecutor, + EnclaveValidatorAccessor, IntegriteeParentchainBlockImportDispatcher, GLOBAL_INTEGRITEE_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE, GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, diff --git a/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs b/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs index aafb4b460f..87e4e0b03f 100644 --- a/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs +++ b/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs @@ -19,8 +19,8 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, - EnclaveStfExecutor, EnclaveValidatorAccessor, TargetAEnclaveExtrinsicsFactory, + EnclaveNodeMetadataRepository, EnclaveOCallApi, EnclaveStfExecutor, + EnclaveValidatorAccessor, TargetAEnclaveExtrinsicsFactory, TargetAParentchainBlockImportDispatcher, GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE, diff --git a/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs b/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs index bcf706970d..e609782ec4 100644 --- a/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs +++ b/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs @@ -19,8 +19,8 @@ use crate::{ error::Result, initialization::{ global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, - EnclaveStfExecutor, EnclaveValidatorAccessor, TargetBEnclaveExtrinsicsFactory, + EnclaveNodeMetadataRepository, EnclaveOCallApi, EnclaveStfExecutor, + EnclaveValidatorAccessor, TargetBEnclaveExtrinsicsFactory, TargetBParentchainBlockImportDispatcher, GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE, diff --git a/enclave-runtime/src/shard_vault.rs b/enclave-runtime/src/shard_vault.rs index 11e42071d4..8b7137f372 100644 --- a/enclave-runtime/src/shard_vault.rs +++ b/enclave-runtime/src/shard_vault.rs @@ -32,7 +32,7 @@ use crate::{ }; use codec::{Compact, Decode, Encode}; use itp_component_container::ComponentGetter; -use itp_extrinsics_factory::{CreateExtrinsics, ExtrinsicsFactory}; +use itp_extrinsics_factory::CreateExtrinsics; use itp_node_api::{ api_client::{Config, PairSignature, StaticExtrinsicSigner}, metadata::provider::{AccessNodeMetadata, Error as MetadataProviderError}, @@ -258,6 +258,67 @@ pub(crate) fn add_shard_vault_proxy( shard: ShardIdentifier, proxy: &AccountId, ) -> EnclaveResult<()> { + let (vault, parentchain_id) = get_shard_vault_internal(shard)?; + + match parentchain_id { + ParentchainId::Integritee => { + let enclave_extrinsics_factory = + get_extrinsic_factory_from_integritee_solo_or_parachain()?; + let node_metadata_repo = + get_node_metadata_repository_from_integritee_solo_or_parachain()?; + add_shard_vault_proxy_int( + shard, + proxy, + vault, + parentchain_id, + enclave_extrinsics_factory, + node_metadata_repo, + ) + }, + ParentchainId::TargetA => { + let enclave_extrinsics_factory = + get_extrinsic_factory_from_target_a_solo_or_parachain()?; + let node_metadata_repo = + get_node_metadata_repository_from_target_a_solo_or_parachain()?; + add_shard_vault_proxy_int( + shard, + proxy, + vault, + parentchain_id, + enclave_extrinsics_factory, + node_metadata_repo, + ) + }, + ParentchainId::TargetB => { + let enclave_extrinsics_factory = + get_extrinsic_factory_from_target_b_solo_or_parachain()?; + let node_metadata_repo = + get_node_metadata_repository_from_target_b_solo_or_parachain()?; + add_shard_vault_proxy_int( + shard, + proxy, + vault, + parentchain_id, + enclave_extrinsics_factory, + node_metadata_repo, + ) + }, + } +} + +fn add_shard_vault_proxy_int( + shard: ShardIdentifier, + proxy: &AccountId, + vault: AccountId, + parentchain_id: ParentchainId, + enclave_extrinsics_factory: Arc>, + node_metadata_repository: Arc, +) -> EnclaveResult<()> +where + NodeRuntimeConfig: Config, + u128: From, + Tip: Copy + Default + Encode, +{ let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; if !state_handler .shard_exists(&shard) @@ -267,19 +328,6 @@ pub(crate) fn add_shard_vault_proxy( }; let ocall_api = GLOBAL_OCALL_API_COMPONENT.get()?; - let (vault, parentchain_id) = get_shard_vault_internal(shard)?; - - let enclave_extrinsics_factory = match parentchain_id { - ParentchainId::Integritee => get_extrinsic_factory_from_integritee_solo_or_parachain()?, - ParentchainId::TargetA => get_extrinsic_factory_from_target_a_solo_or_parachain()?, - ParentchainId::TargetB => get_extrinsic_factory_from_target_b_solo_or_parachain()?, - }; - let node_metadata_repo = match parentchain_id { - ParentchainId::Integritee => - get_node_metadata_repository_from_integritee_solo_or_parachain()?, - ParentchainId::TargetA => get_node_metadata_repository_from_target_a_solo_or_parachain()?, - ParentchainId::TargetB => get_node_metadata_repository_from_target_b_solo_or_parachain()?, - }; debug!( "adding proxy 0x{} to shard vault account 0x{} on {:?}", @@ -289,13 +337,13 @@ pub(crate) fn add_shard_vault_proxy( ); let add_proxy_call = OpaqueCall::from_tuple(&( - node_metadata_repo.get_from_metadata(|m| m.add_proxy_call_indexes())??, + node_metadata_repository.get_from_metadata(|m| m.add_proxy_call_indexes())??, Address::from(proxy.clone()), ProxyType::Any, 0u32, // delay )); let call = OpaqueCall::from_tuple(&( - node_metadata_repo.get_from_metadata(|m| m.proxy_call_indexes())??, + node_metadata_repository.get_from_metadata(|m| m.proxy_call_indexes())??, Address::from(vault), None::, add_proxy_call, diff --git a/enclave-runtime/src/utils.rs b/enclave-runtime/src/utils.rs index 2f1c96350b..14d6f621e0 100644 --- a/enclave-runtime/src/utils.rs +++ b/enclave-runtime/src/utils.rs @@ -17,8 +17,8 @@ use crate::{ error::{Error, Result}, initialization::global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveStfEnclaveSigner, - EnclaveStfExecutor, EnclaveValidatorAccessor, IntegriteeEnclaveExtrinsicsFactory, + EnclaveNodeMetadataRepository, EnclaveStfEnclaveSigner, EnclaveStfExecutor, + EnclaveValidatorAccessor, IntegriteeEnclaveExtrinsicsFactory, IntegriteeParentchainTriggeredBlockImportDispatcher, TargetAEnclaveExtrinsicsFactory, TargetAParentchainTriggeredBlockImportDispatcher, TargetBEnclaveExtrinsicsFactory, TargetBParentchainTriggeredBlockImportDispatcher, From b3e590a91d2c822b54c8ca4ddbc984b051f49576 Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Fri, 22 Nov 2024 13:20:49 +0100 Subject: [PATCH 12/23] remove unnecessary alias --- enclave-runtime/src/initialization/global_components.rs | 7 ------- 1 file changed, 7 deletions(-) diff --git a/enclave-runtime/src/initialization/global_components.rs b/enclave-runtime/src/initialization/global_components.rs index 531dfa9c8d..6adf0c5258 100644 --- a/enclave-runtime/src/initialization/global_components.rs +++ b/enclave-runtime/src/initialization/global_components.rs @@ -378,13 +378,6 @@ pub type EnclaveSealHandler = SealHandler< EnclaveLightClientSeal, >; -pub type IntegriteeOffchainWorkerExecutor = - EnclaveOffchainWorkerExecutor; -pub type TargetAOffchainWorkerExecutor = - EnclaveOffchainWorkerExecutor; -pub type TargetBOffchainWorkerExecutor = - EnclaveOffchainWorkerExecutor; - pub type EnclaveOffchainWorkerExecutor = itc_offchain_worker_executor::executor::Executor< ParentchainBlock, From 83f5a5be8767011a7e1e0aacf88d927178774732 Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Fri, 22 Nov 2024 14:24:40 +0100 Subject: [PATCH 13/23] remove core --- app-libs/parentchain-interface/src/lib.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/app-libs/parentchain-interface/src/lib.rs b/app-libs/parentchain-interface/src/lib.rs index 102ddb9136..63fcf7a6ec 100644 --- a/app-libs/parentchain-interface/src/lib.rs +++ b/app-libs/parentchain-interface/src/lib.rs @@ -18,7 +18,6 @@ #![cfg_attr(all(not(target_env = "sgx"), not(feature = "std")), no_std)] #![cfg_attr(target_env = "sgx", feature(rustc_private))] -extern crate core; #[cfg(all(not(feature = "std"), feature = "sgx"))] extern crate sgx_tstd as std; From 2c99de6ec89c98e131eb6789ea99d16735396a79 Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Fri, 22 Nov 2024 14:34:57 +0100 Subject: [PATCH 14/23] some cleanup --- .../src/integritee/api_client_types.rs | 30 ++++------------ app-libs/parentchain-interface/src/lib.rs | 24 +++++++++++-- .../src/target_a/api_client_types.rs | 29 ++++------------ .../src/target_b/api_client_types.rs | 34 +++++-------------- 4 files changed, 42 insertions(+), 75 deletions(-) diff --git a/app-libs/parentchain-interface/src/integritee/api_client_types.rs b/app-libs/parentchain-interface/src/integritee/api_client_types.rs index fffe06c883..fd33738fb5 100644 --- a/app-libs/parentchain-interface/src/integritee/api_client_types.rs +++ b/app-libs/parentchain-interface/src/integritee/api_client_types.rs @@ -20,36 +20,20 @@ //! You need to update this if you have a signed extension in your node that //! is different from the integritee-node, e.g., if you use the `pallet_asset_tx_payment`. +use crate::{ + GenericAdditionalParams, GenericExtrinsicParams, GenericSignedExtra, ParentchainRuntimeConfig, + PlainTip, UncheckedExtrinsicV4, +}; +use itp_types::parentchain::Header; pub use itp_types::parentchain::{ AccountData, AccountId, AccountInfo, Address, Balance, Hash, Index, Signature as PairSignature, }; use sp_runtime::generic; -pub use substrate_api_client::{ - ac_node_api::{ - metadata::{InvalidMetadataError, Metadata, MetadataError}, - EventDetails, Events, StaticEvent, - }, - ac_primitives::{ - config::{AssetRuntimeConfig, Config}, - extrinsics::{ - AssetTip, CallIndex, ExtrinsicParams, GenericAdditionalParams, GenericAdditionalSigned, - GenericExtrinsicParams, GenericSignedExtra, PlainTip, UncheckedExtrinsicV4, - }, - serde_impls::StorageKey, - signer::{SignExtrinsic, StaticExtrinsicSigner}, - }, - rpc::Request, - storage_key, Api, -}; -pub type IntegriteeTip = PlainTip; pub type IntegriteeRuntimeConfig = ParentchainRuntimeConfig; // Configuration for the ExtrinsicParams. -// -// Pay in asset fees. -// -// This needs to be used if the node uses the `pallet_asset_tx_payment`. +pub type IntegriteeTip = PlainTip; pub type IntegriteeExtrinsicParams = GenericExtrinsicParams; pub type IntegriteeAdditionalParams = GenericAdditionalParams; @@ -64,10 +48,8 @@ pub type Signature = Option<(Address, PairSignature, SignedExtra)>; pub type Block = generic::Block>; -use crate::ParentchainRuntimeConfig; #[cfg(feature = "std")] pub use api::*; -use itp_types::parentchain::Header; #[cfg(feature = "std")] mod api { diff --git a/app-libs/parentchain-interface/src/lib.rs b/app-libs/parentchain-interface/src/lib.rs index 63fcf7a6ec..decd7e5c0e 100644 --- a/app-libs/parentchain-interface/src/lib.rs +++ b/app-libs/parentchain-interface/src/lib.rs @@ -21,10 +21,8 @@ #[cfg(all(not(feature = "std"), feature = "sgx"))] extern crate sgx_tstd as std; -use crate::integritee::api_client_types::Config; use codec::{Decode, Encode}; use core::marker::PhantomData; -use itp_api_client_types::GenericExtrinsicParams; use itp_types::parentchain::Hash; use sp_core::{crypto::AccountId32, sr25519}; use sp_runtime::{MultiAddress, MultiSignature}; @@ -32,6 +30,24 @@ use substrate_api_client::ac_primitives::{ BlakeTwo256, ExtrinsicSigner, SubstrateBlock, SubstrateHeader, SubstrateOpaqueExtrinsic, }; +pub use substrate_api_client::{ + ac_node_api::{ + metadata::{InvalidMetadataError, Metadata, MetadataError}, + EventDetails, Events, StaticEvent, + }, + ac_primitives::{ + config::Config, + extrinsics::{ + AssetTip, CallIndex, ExtrinsicParams, GenericAdditionalParams, GenericAdditionalSigned, + GenericExtrinsicParams, GenericSignedExtra, PlainTip, UncheckedExtrinsicV4, + }, + serde_impls::StorageKey, + signer::{SignExtrinsic, StaticExtrinsicSigner}, + }, + rpc::Request, + storage_key, Api, +}; + #[cfg(feature = "std")] pub mod event_subscriber; pub mod extrinsic_parser; @@ -64,7 +80,9 @@ pub fn decode_and_log_error(encoded: &mut &[u8]) -> Option { } } -// Define the config that matches our parentchains. +/// Config matching the specs of the typical polkadot chains. +/// We can define some more if we realize that we need more +/// granular control than the tip. #[derive(Decode, Encode, Clone, Eq, PartialEq, Debug)] pub struct ParentchainRuntimeConfig { _phantom: PhantomData, diff --git a/app-libs/parentchain-interface/src/target_a/api_client_types.rs b/app-libs/parentchain-interface/src/target_a/api_client_types.rs index 254cc81f0c..259c4ff118 100644 --- a/app-libs/parentchain-interface/src/target_a/api_client_types.rs +++ b/app-libs/parentchain-interface/src/target_a/api_client_types.rs @@ -20,35 +20,19 @@ //! You need to update this if you have a signed extension in your node that //! is different from the integritee-node, e.g., if you use the `pallet_asset_tx_payment`. +use crate::{ + GenericAdditionalParams, GenericExtrinsicParams, GenericSignedExtra, ParentchainRuntimeConfig, + PlainTip, UncheckedExtrinsicV4, +}; pub use itp_types::parentchain::{ AccountData, AccountId, AccountInfo, Address, Balance, Hash, Index, Signature as PairSignature, }; -pub use substrate_api_client::{ - ac_node_api::{ - metadata::{InvalidMetadataError, Metadata, MetadataError}, - EventDetails, Events, StaticEvent, - }, - ac_primitives::{ - config::{AssetRuntimeConfig, Config}, - extrinsics::{ - AssetTip, CallIndex, ExtrinsicParams, GenericAdditionalParams, GenericAdditionalSigned, - GenericExtrinsicParams, GenericSignedExtra, PlainTip, UncheckedExtrinsicV4, - }, - serde_impls::StorageKey, - signer::{SignExtrinsic, StaticExtrinsicSigner}, - }, - rpc::Request, - storage_key, Api, -}; -pub type TargetATip = PlainTip; pub type TargetARuntimeConfig = ParentchainRuntimeConfig; // Configuration for the ExtrinsicParams. -// -// Pay in asset fees. -// -// This needs to be used if the node uses the `pallet_asset_tx_payment`. + +pub type TargetATip = PlainTip; pub type TargetAExtrinsicParams = GenericExtrinsicParams; pub type TargetAAdditionalParams = GenericAdditionalParams; @@ -61,7 +45,6 @@ pub type TargetAUncheckedExtrinsic = /// Signature type of the [UncheckedExtrinsicV4]. pub type Signature = Option<(Address, PairSignature, SignedExtra)>; -use crate::ParentchainRuntimeConfig; #[cfg(feature = "std")] pub use api::*; diff --git a/app-libs/parentchain-interface/src/target_b/api_client_types.rs b/app-libs/parentchain-interface/src/target_b/api_client_types.rs index fc0376b7ee..414b6211c6 100644 --- a/app-libs/parentchain-interface/src/target_b/api_client_types.rs +++ b/app-libs/parentchain-interface/src/target_b/api_client_types.rs @@ -20,37 +20,22 @@ //! You need to update this if you have a signed extension in your node that //! is different from the integritee-node, e.g., if you use the `pallet_asset_tx_payment`. +use crate::{ + AssetTip, GenericAdditionalParams, GenericExtrinsicParams, GenericSignedExtra, + ParentchainRuntimeConfig, UncheckedExtrinsicV4, +}; pub use itp_types::parentchain::{ AccountData, AccountId, AccountInfo, Address, Balance, Hash, Index, Signature as PairSignature, }; -pub use substrate_api_client::{ - ac_node_api::{ - metadata::{InvalidMetadataError, Metadata, MetadataError}, - EventDetails, Events, StaticEvent, - }, - ac_primitives::{ - config::{AssetRuntimeConfig, Config}, - extrinsics::{ - AssetTip, CallIndex, ExtrinsicParams, GenericAdditionalParams, GenericAdditionalSigned, - GenericExtrinsicParams, GenericSignedExtra, PlainTip, UncheckedExtrinsicV4, - }, - serde_impls::StorageKey, - signer::{SignExtrinsic, StaticExtrinsicSigner}, - }, - rpc::Request, - storage_key, Api, -}; + +pub type TargetBRuntimeConfig = ParentchainRuntimeConfig; // Configuration for the ExtrinsicParams. -// -// Pay in asset fees. -// -// This needs to be used if the node uses the `pallet_asset_tx_payment`. -// pub type TargetBExtrinsicParams = GenericExtrinsicParams; -// pub type TargetBAdditionalParams = GenericAdditionalParams; +// Using the AssetTip, as we assume that TargetB uses the `pallet_asset_tx_payment`. pub type TargetBTip = AssetTip; -pub type TargetBRuntimeConfig = ParentchainRuntimeConfig; +pub type TargetBExtrinsicParams = GenericExtrinsicParams; +pub type TargetBAdditionalParams = GenericAdditionalParams; pub type TargetBSignedExtra = GenericSignedExtra; pub type TargetBSignature = Signature; @@ -61,7 +46,6 @@ pub type TargetBUncheckedExtrinsic = /// Signature type of the [UncheckedExtrinsicV4]. pub type Signature = Option<(Address, PairSignature, SignedExtra)>; -use crate::ParentchainRuntimeConfig; #[cfg(feature = "std")] pub use api::*; From f77eba7a9fab137aa5428eba2018bd69daec5304 Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Fri, 22 Nov 2024 14:41:11 +0100 Subject: [PATCH 15/23] cleanup and remove naming ambiguities --- .../parentchain-interface/src/target_a/mod.rs | 6 +++--- .../parentchain-interface/src/target_b/mod.rs | 21 +++---------------- .../src/initialization/parentchain/common.rs | 2 +- service/src/account_funding.rs | 2 +- 4 files changed, 8 insertions(+), 23 deletions(-) diff --git a/app-libs/parentchain-interface/src/target_a/mod.rs b/app-libs/parentchain-interface/src/target_a/mod.rs index 433ec0a072..ee7df47e30 100644 --- a/app-libs/parentchain-interface/src/target_a/mod.rs +++ b/app-libs/parentchain-interface/src/target_a/mod.rs @@ -27,6 +27,7 @@ use crate::{ indirect_calls::timestamp_set::TimestampSetArgs, TargetA, }; +use api_client_types::TargetASignedExtra; use codec::{Decode, Encode}; pub use event_filter::FilterableEvents; pub use event_handler::ParentchainEventHandler; @@ -36,13 +37,12 @@ use itc_parentchain_indirect_calls_executor::{ filter_metadata::FilterIntoDataFrom, IndirectDispatch, }; -use itp_api_client_types::ParentchainSignedExtra; use itp_node_api::metadata::pallet_timestamp::TimestampCallIndexes; use itp_stf_primitives::traits::IndirectExecutor; use log::*; /// Parses the extrinsics corresponding to the parentchain. -pub type ParentchainExtrinsicParser = ExtrinsicParser; +pub type TargetAExtrinsicParser = ExtrinsicParser; /// The default indirect call (extrinsic-triggered) of the Target-A-Parachain. #[derive(Debug, Clone, Encode, Decode, Eq, PartialEq)] @@ -65,7 +65,7 @@ pub struct ExtrinsicFilter {} impl FilterIntoDataFrom for ExtrinsicFilter { type Output = IndirectCall; - type ParseParentchainMetadata = ParentchainExtrinsicParser; + type ParseParentchainMetadata = TargetAExtrinsicParser; fn filter_into_from_metadata( encoded_data: &[u8], diff --git a/app-libs/parentchain-interface/src/target_b/mod.rs b/app-libs/parentchain-interface/src/target_b/mod.rs index a092a567bd..e4eeeb4ade 100644 --- a/app-libs/parentchain-interface/src/target_b/mod.rs +++ b/app-libs/parentchain-interface/src/target_b/mod.rs @@ -27,6 +27,7 @@ use crate::{ indirect_calls::timestamp_set::TimestampSetArgs, TargetB, }; +use api_client_types::TargetBSignedExtra; use codec::{Decode, Encode}; pub use event_filter::FilterableEvents; pub use event_handler::ParentchainEventHandler; @@ -36,28 +37,12 @@ use itc_parentchain_indirect_calls_executor::{ filter_metadata::FilterIntoDataFrom, IndirectDispatch, }; -use itp_api_client_types::{ - AssetRuntimeConfig, AssetTip, GenericAdditionalParams, GenericExtrinsicParams, - GenericSignedExtra, PairSignature, ParentchainPlainTip, Signature, UncheckedExtrinsicV4, -}; use itp_node_api::metadata::pallet_timestamp::TimestampCallIndexes; use itp_stf_primitives::traits::IndirectExecutor; -use itp_types::parentchain::{Address, Balance, Hash, Index}; use log::*; -// We assume Asset Hub here (or any similar parachain) -// Pay in asset fees. -// This needs to be used if the node uses the `pallet_asset_tx_payment`. -pub type ParentchainExtrinsicParams = GenericExtrinsicParams>; -pub type ParentchainAdditionalParams = GenericAdditionalParams; - -pub type ParentchainUncheckedExtrinsic = - UncheckedExtrinsicV4; -pub type ParentchainSignedExtra = GenericSignedExtra; -pub type ParentchainSignature = Signature; - /// Parses the extrinsics corresponding to the parentchain. -pub type ParentchainExtrinsicParser = ExtrinsicParser; +pub type TargetBExtrinsicParser = ExtrinsicParser; /// The default indirect call (extrinsic-triggered) of the Target-A-Parachain. #[derive(Debug, Clone, Encode, Decode, Eq, PartialEq)] @@ -80,7 +65,7 @@ pub struct ExtrinsicFilter {} impl FilterIntoDataFrom for ExtrinsicFilter { type Output = IndirectCall; - type ParseParentchainMetadata = ParentchainExtrinsicParser; + type ParseParentchainMetadata = TargetBExtrinsicParser; fn filter_into_from_metadata( encoded_data: &[u8], diff --git a/enclave-runtime/src/initialization/parentchain/common.rs b/enclave-runtime/src/initialization/parentchain/common.rs index 235c736daa..05093bf953 100644 --- a/enclave-runtime/src/initialization/parentchain/common.rs +++ b/enclave-runtime/src/initialization/parentchain/common.rs @@ -44,7 +44,7 @@ use crate::{ EnclaveStfEnclaveSigner, }, }; -use ita_parentchain_interface::target_a::api_client_types::Config; +use ita_parentchain_interface::Config; use itp_component_container::ComponentGetter; use itp_nonce_cache::NonceCache; use itp_sgx_crypto::key_repository::AccessKey; diff --git a/service/src/account_funding.rs b/service/src/account_funding.rs index 1b53ccea93..a6926d9852 100644 --- a/service/src/account_funding.rs +++ b/service/src/account_funding.rs @@ -17,7 +17,7 @@ use crate::error::{Error, ServiceResult}; use codec::Encode; -use ita_parentchain_interface::{integritee::api_client_types::Config, ParentchainRuntimeConfig}; +use ita_parentchain_interface::{Config, ParentchainRuntimeConfig}; use itp_node_api::api_client::{AccountApi, TEEREX}; use itp_settings::worker::REGISTERING_FEE_FACTOR_FOR_INIT_FUNDS; use itp_types::{ From 47f5e610207c88bbfad85b37f749204668715431 Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Fri, 22 Nov 2024 15:46:50 +0100 Subject: [PATCH 16/23] fix test build --- core-primitives/extrinsics-factory/src/lib.rs | 28 +++++---------- .../extrinsics-factory/src/mock.rs | 13 +++++-- core-primitives/node-api/factory/src/lib.rs | 9 +++-- core/offchain-worker-executor/src/executor.rs | 4 +-- .../src/ocall_bridge/worker_on_chain_ocall.rs | 35 ------------------- service/src/worker.rs | 3 +- 6 files changed, 29 insertions(+), 63 deletions(-) diff --git a/core-primitives/extrinsics-factory/src/lib.rs b/core-primitives/extrinsics-factory/src/lib.rs index 01f3db3677..26e1702586 100644 --- a/core-primitives/extrinsics-factory/src/lib.rs +++ b/core-primitives/extrinsics-factory/src/lib.rs @@ -72,27 +72,16 @@ pub type AdditionParamsOf = ::Index, ::Hash>>::AdditionalParams; /// Extrinsics factory -pub struct ExtrinsicsFactory -where - Signer: SignExtrinsic, - NonceCache: MutateNonce, - NodeMetadataRepository: AccessNodeMetadata, - NodeRuntimeConfig: Config, -{ +pub struct ExtrinsicsFactory { genesis_hash: H256, signer: Signer, nonce_cache: Arc, pub node_metadata_repository: Arc, - phantom: PhantomData<(NodeRuntimeConfig, Tip)>, + _phantom: PhantomData<(NodeRuntimeConfig, Tip)>, } impl ExtrinsicsFactory -where - Signer: SignExtrinsic, - NonceCache: MutateNonce, - NodeMetadataRepository: AccessNodeMetadata, - NodeRuntimeConfig: Config, { pub fn new( genesis_hash: H256, @@ -105,7 +94,7 @@ where signer, nonce_cache, node_metadata_repository, - phantom: Default::default(), + _phantom: Default::default(), } } @@ -115,7 +104,7 @@ where signer, nonce_cache, node_metadata_repository: self.node_metadata_repository.clone(), - phantom: Default::default(), + _phantom: Default::default(), } } } @@ -137,7 +126,7 @@ where fn create_extrinsics( &self, calls: &[(OpaqueCall, GenericMortality)], - extrinsics_params: Option>, + extrinsics_params: Option>, ) -> Result> { let mut nonce_lock = self.nonce_cache.load_for_mutation()?; let mut nonce_value = nonce_lock.0; @@ -184,18 +173,17 @@ pub mod tests { use super::*; use itp_node_api::{ - api_client::{PairSignature, StaticExtrinsicSigner}, + api_client::{AssetRuntimeConfig, PairSignature, StaticExtrinsicSigner}, metadata::provider::NodeMetadataRepository, }; use itp_nonce_cache::{GetNonce, Nonce, NonceCache, NonceValue}; use sp_core::{ed25519, Pair}; - //use substrate_api_client::extrinsic::xt_primitives::UncheckedExtrinsicV4; #[test] pub fn creating_xts_increases_nonce_for_each_xt() { let nonce_cache = Arc::new(NonceCache::default()); let node_metadata_repo = Arc::new(NodeMetadataRepository::new(NodeMetadata::default())); - let extrinsics_factory = ExtrinsicsFactory::new( + let extrinsics_factory = ExtrinsicsFactory::<_, _, _, AssetRuntimeConfig, u128>::new( test_genesis_hash(), StaticExtrinsicSigner::<_, PairSignature>::new(test_account()), nonce_cache.clone(), @@ -218,7 +206,7 @@ pub mod tests { *nonce_cache1.load_for_mutation().unwrap() = Nonce(42); let node_metadata_repo = Arc::new(NodeMetadataRepository::new(NodeMetadata::default())); - let extrinsics_factory = ExtrinsicsFactory::new( + let extrinsics_factory = ExtrinsicsFactory::<_, _, _, AssetRuntimeConfig, u128>::new( test_genesis_hash(), StaticExtrinsicSigner::<_, PairSignature>::new(test_account()), nonce_cache1.clone(), diff --git a/core-primitives/extrinsics-factory/src/mock.rs b/core-primitives/extrinsics-factory/src/mock.rs index 267ddb5187..60102b57bc 100644 --- a/core-primitives/extrinsics-factory/src/mock.rs +++ b/core-primitives/extrinsics-factory/src/mock.rs @@ -16,19 +16,28 @@ */ use crate::{error::Result, AdditionParamsOf, CreateExtrinsics}; use core::marker::PhantomData; -use itp_node_api::api_client::{GenericExtrinsicParams, ParentchainRuntimeConfig, PlainTip}; use itp_types::{parentchain::GenericMortality, Balance, OpaqueCall}; use sp_runtime::OpaqueExtrinsic; use std::vec::Vec; +pub use itp_node_api::api_client::{ + Config, GenericExtrinsicParams, ParentchainRuntimeConfig, PlainTip, +}; + /// Mock of an extrinsics factory. To be used in unit tests. /// /// Returns an empty extrinsic. -#[derive(Default, Clone)] +#[derive(Clone)] pub struct ExtrinsicsFactoryMock { _phantom: PhantomData, } +impl Default for ExtrinsicsFactoryMock { + fn default() -> Self { + Self { _phantom: Default::default() } + } +} + impl CreateExtrinsics for ExtrinsicsFactoryMock { type Config = ParentchainRuntimeConfig; type ExtrinsicParams = GenericExtrinsicParams>; diff --git a/core-primitives/node-api/factory/src/lib.rs b/core-primitives/node-api/factory/src/lib.rs index cd0e5f0748..7dcfd215bd 100644 --- a/core-primitives/node-api/factory/src/lib.rs +++ b/core-primitives/node-api/factory/src/lib.rs @@ -15,10 +15,13 @@ limitations under the License. */ -use itp_api_client_types::{traits::Request, Api, Config, TungsteniteRpcClient}; use sp_core::sr25519; use std::marker::PhantomData; +pub use itp_api_client_types::{ + traits::Request, Api, AssetRuntimeConfig, Config, DefaultRuntimeConfig, TungsteniteRpcClient, +}; + /// Trait to create a node API, based on a node URL and signer. pub trait CreateNodeApi { fn create_api(&self) -> Result>; @@ -50,13 +53,13 @@ impl From for NodeApiFactoryError { pub type Result = std::result::Result; /// Node API factory implementation. -pub struct NodeApiFactory { +pub struct NodeApiFactory { node_url: String, signer: sr25519::Pair, _phantom: PhantomData<(NodeConfig, Client)>, } -impl NodeApiFactory { +impl NodeApiFactory { pub fn new(url: String, signer: sr25519::Pair) -> Self { NodeApiFactory { node_url: url, signer, _phantom: Default::default() } } diff --git a/core/offchain-worker-executor/src/executor.rs b/core/offchain-worker-executor/src/executor.rs index f07b2cc33c..4d4f412951 100644 --- a/core/offchain-worker-executor/src/executor.rs +++ b/core/offchain-worker-executor/src/executor.rs @@ -246,7 +246,7 @@ mod tests { use super::*; use codec::{Decode, Encode}; use itc_parentchain_light_client::mocks::validator_access_mock::ValidatorAccessMock; - use itp_extrinsics_factory::mock::ExtrinsicsFactoryMock; + use itp_extrinsics_factory::mock::{ExtrinsicsFactoryMock, ParentchainRuntimeConfig}; use itp_sgx_externalities::SgxExternalitiesTrait; use itp_stf_executor::mocks::StfExecutorMock; @@ -266,7 +266,7 @@ mod tests { type TestTopPoolAuthor = AuthorApiMock; type TestStfExecutor = StfExecutorMock; type TestValidatorAccess = ValidatorAccessMock; - type TestExtrinsicsFactory = ExtrinsicsFactoryMock; + type TestExtrinsicsFactory = ExtrinsicsFactoryMock; type TestExecutor = Executor< ParentchainBlock, TestTopPoolAuthor, diff --git a/service/src/ocall_bridge/worker_on_chain_ocall.rs b/service/src/ocall_bridge/worker_on_chain_ocall.rs index 3ef849d3d6..04cd3cd33e 100644 --- a/service/src/ocall_bridge/worker_on_chain_ocall.rs +++ b/service/src/ocall_bridge/worker_on_chain_ocall.rs @@ -354,38 +354,3 @@ fn log_extrinsics_to_file( } Ok(()) } - -#[cfg(test)] -mod tests { - - use super::*; - use itp_node_api::{ - api_client::ParentchainApi, - node_api_factory::{CreateNodeApi, Result as NodeApiResult}, - }; - use itp_sgx_temp_dir::TempDir; - use mockall::mock; - - #[test] - fn given_empty_worker_request_when_submitting_then_return_empty_response() { - mock! { - NodeApiFactory {} - impl CreateNodeApi for NodeApiFactory { - fn create_api(&self) -> NodeApiResult; - } - } - - let mock_node_api_factory = Arc::new(MockNodeApiFactory::new()); - let temp_dir = TempDir::new().unwrap(); - let on_chain_ocall = - WorkerOnChainOCall::new(mock_node_api_factory, None, None, temp_dir.path().into()); - - let response = on_chain_ocall - .worker_request(Vec::::new().encode(), ParentchainId::Integritee.encode()) - .unwrap(); - - assert!(!response.is_empty()); // the encoded empty vector is not empty - let decoded_response: Vec = Decode::decode(&mut response.as_slice()).unwrap(); - assert!(decoded_response.is_empty()); // decode the response, and we get an empty vector again - } -} diff --git a/service/src/worker.rs b/service/src/worker.rs index f3cb7323a1..09f0057b75 100644 --- a/service/src/worker.rs +++ b/service/src/worker.rs @@ -197,6 +197,7 @@ mod tests { worker::{AsyncBlockBroadcaster, Worker}, }; use frame_support::assert_ok; + use ita_parentchain_interface::integritee::api_client_types::IntegriteeRuntimeConfig; use itp_node_api::node_api_factory::NodeApiFactory; use its_primitives::types::block::SignedBlock as SignedSidechainBlock; use its_test::sidechain_block_builder::{SidechainBlockBuilder, SidechainBlockBuilderTrait}; @@ -235,7 +236,7 @@ mod tests { let untrusted_worker_port = "4000".to_string(); let peers = vec![format!("ws://{}", W1_URL), format!("ws://{}", W2_URL)]; - let worker = Worker::new( + let worker = Worker::<_, IntegriteeRuntimeConfig, _, _>::new( local_worker_config(W1_URL.into(), untrusted_worker_port.clone(), "30".to_string()), Arc::new(()), Arc::new(NodeApiFactory::new( From 64fab430fc2386006ef65730a1d4449f313b36f0 Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Fri, 22 Nov 2024 15:48:30 +0100 Subject: [PATCH 17/23] clippy --- service/src/ocall_bridge/worker_on_chain_ocall.rs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/service/src/ocall_bridge/worker_on_chain_ocall.rs b/service/src/ocall_bridge/worker_on_chain_ocall.rs index 04cd3cd33e..c068a2c5e2 100644 --- a/service/src/ocall_bridge/worker_on_chain_ocall.rs +++ b/service/src/ocall_bridge/worker_on_chain_ocall.rs @@ -109,21 +109,19 @@ where pub fn create_target_a_api( &self, ) -> OCallBridgeResult> { - Ok(self - .target_a_parentchain_api_factory + self.target_a_parentchain_api_factory .as_ref() .ok_or(OCallBridgeError::TargetAParentchainNotInitialized) - .and_then(|f| f.create_api().map_err(Into::into))?) + .and_then(|f| f.create_api().map_err(Into::into)) } pub fn create_target_b_api( &self, ) -> OCallBridgeResult> { - Ok(self - .target_b_parentchain_api_factory + self.target_b_parentchain_api_factory .as_ref() .ok_or(OCallBridgeError::TargetBParentchainNotInitialized) - .and_then(|f| f.create_api().map_err(Into::into))?) + .and_then(|f| f.create_api().map_err(Into::into)) } fn handle_requests< From 744d8f67265bbb211ce9db7f8a44de8b06e5f819 Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Fri, 22 Nov 2024 15:57:04 +0100 Subject: [PATCH 18/23] fix teeracle build --- cli/src/base_cli/commands/balance.rs | 8 ++------ cli/src/command_utils.rs | 10 ++++++---- cli/src/oracle/commands/listen_to_exchange.rs | 1 + cli/src/oracle/commands/listen_to_oracle.rs | 2 +- service/src/teeracle/mod.rs | 6 +++--- 5 files changed, 13 insertions(+), 14 deletions(-) diff --git a/cli/src/base_cli/commands/balance.rs b/cli/src/base_cli/commands/balance.rs index fe55bb24ad..8457f5978a 100644 --- a/cli/src/base_cli/commands/balance.rs +++ b/cli/src/base_cli/commands/balance.rs @@ -19,7 +19,7 @@ use crate::{ Cli, CliResult, CliResultOk, }; use log::info; -use substrate_api_client::{ac_primitives::AccountData, GetAccountInformation}; +use substrate_api_client::GetAccountInformation; #[derive(Parser)] pub struct BalanceCommand { @@ -31,11 +31,7 @@ impl BalanceCommand { pub(crate) fn run(&self, cli: &Cli) -> CliResult { let api = get_chain_api(cli); let accountid = get_accountid_from_str(&self.account); - let account_data = if let Some(data) = api.get_account_data(&accountid).unwrap() { - data - } else { - AccountData::default() - }; + let account_data = api.get_account_data(&accountid).unwrap().unwrap_or_default(); info!("{:?}", account_data); println!("{}", account_data.free); Ok(CliResultOk::Balance { balance: account_data.free }) diff --git a/cli/src/command_utils.rs b/cli/src/command_utils.rs index f4af81efab..988353e7cf 100644 --- a/cli/src/command_utils.rs +++ b/cli/src/command_utils.rs @@ -18,9 +18,11 @@ use crate::Cli; use base58::FromBase58; use chrono::{DateTime, Local, NaiveDateTime}; -use ita_parentchain_interface::integritee::{AccountId, Signature}; +use ita_parentchain_interface::integritee::{ + api_client_types::IntegriteeApi, AccountId, Signature, +}; use itc_rpc_client::direct_client::{DirectApi, DirectClient as DirectWorkerApi}; -use itp_node_api::api_client::{ParentchainApi, TungsteniteRpcClient}; +use itp_node_api::api_client::TungsteniteRpcClient; use itp_types::Moment; use log::*; use sgx_crypto_helper::rsa3072::Rsa3072PubKey; @@ -39,10 +41,10 @@ pub(crate) fn get_shielding_key(cli: &Cli) -> Result { worker_api_direct.get_rsa_pubkey().map_err(|e| e.to_string()) } -pub(crate) fn get_chain_api(cli: &Cli) -> ParentchainApi { +pub(crate) fn get_chain_api(cli: &Cli) -> IntegriteeApi { let url = format!("{}:{}", cli.node_url, cli.node_port); info!("connecting to {}", url); - ParentchainApi::new(TungsteniteRpcClient::new(&url, 5).unwrap()).unwrap() + IntegriteeApi::new(TungsteniteRpcClient::new(&url, 5).unwrap()).unwrap() } pub(crate) fn get_accountid_from_str(account: &str) -> AccountId { diff --git a/cli/src/oracle/commands/listen_to_exchange.rs b/cli/src/oracle/commands/listen_to_exchange.rs index 957c16cb1b..a794563c27 100644 --- a/cli/src/oracle/commands/listen_to_exchange.rs +++ b/cli/src/oracle/commands/listen_to_exchange.rs @@ -16,6 +16,7 @@ */ use crate::{command_utils::get_chain_api, Cli}; +use ita_parentchain_interface::integritee::api_client_types::IntegriteeApi; use itp_time_utils::{duration_now, remaining_time}; use itp_types::parentchain::ExchangeRateUpdated; use log::*; diff --git a/cli/src/oracle/commands/listen_to_oracle.rs b/cli/src/oracle/commands/listen_to_oracle.rs index cdd4f21480..38096e9810 100644 --- a/cli/src/oracle/commands/listen_to_oracle.rs +++ b/cli/src/oracle/commands/listen_to_oracle.rs @@ -16,7 +16,7 @@ */ use crate::{command_utils::get_chain_api, Cli}; -use itp_node_api::api_client::ParentchainApi; +use ita_parentchain_interface::integritee::api_client_types::IntegriteeApi; use itp_time_utils::{duration_now, remaining_time}; use itp_types::parentchain::OracleUpdated; use log::*; diff --git a/service/src/teeracle/mod.rs b/service/src/teeracle/mod.rs index 910d45043f..e150635fae 100644 --- a/service/src/teeracle/mod.rs +++ b/service/src/teeracle/mod.rs @@ -17,8 +17,8 @@ use crate::{error::ServiceResult, teeracle::schedule_periodic::schedule_periodic}; use codec::{Decode, Encode}; +use ita_parentchain_interface::integritee::api_client_types::IntegriteeApi; use itp_enclave_api::teeracle_api::TeeracleApi; -use itp_node_api::api_client::ParentchainApi; use itp_types::parentchain::Hash; use itp_utils::hex::hex_encode; use log::*; @@ -69,7 +69,7 @@ pub(crate) fn schedule_periodic_reregistration_thread( /// /// Note: Puts the current thread to sleep for `period`. pub(crate) fn start_periodic_market_update( - api: &ParentchainApi, + api: &IntegriteeApi, period: Duration, enclave_api: &E, tokio_handle: &Handle, @@ -97,7 +97,7 @@ pub(crate) fn start_periodic_market_update( } fn execute_oracle_update( - node_api: &ParentchainApi, + node_api: &IntegriteeApi, tokio_handle: &Handle, get_oracle_xt: F, ) -> ServiceResult<()> From a4e6b5d61abb7c76ae9f39a43a945b6b7119e58a Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Fri, 22 Nov 2024 15:59:28 +0100 Subject: [PATCH 19/23] fix attesteer build --- service/src/main_impl.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/service/src/main_impl.rs b/service/src/main_impl.rs index 4a6c7186ab..36cf8f0541 100644 --- a/service/src/main_impl.rs +++ b/service/src/main_impl.rs @@ -1013,7 +1013,7 @@ fn spawn_worker_for_shard_polling( #[cfg(feature = "attesteer")] fn fetch_marblerun_events_every_hour( - api: ParentchainApi, + api: IntegriteeApi, enclave: Arc, accountid: AccountId32, is_development_mode: bool, @@ -1044,7 +1044,7 @@ fn fetch_marblerun_events_every_hour( } #[cfg(feature = "attesteer")] fn register_quotes_from_marblerun( - api: &ParentchainApi, + api: &IntegriteeApi, enclave: Arc, accountid: &AccountId32, is_development_mode: bool, @@ -1052,7 +1052,7 @@ fn register_quotes_from_marblerun( marblerun_base_url: &str, ) { let enclave = enclave.as_ref(); - let events = prometheus_metrics::fetch_marblerun_events(marblerun_base_url) + let events = crate::prometheus_metrics::fetch_marblerun_events(marblerun_base_url) .map_err(|e| { info!("Fetching events from Marblerun failed with: {:?}, continuing with 0 events.", e); }) From 2c623602dd2cb5cf75622dc0ba657e8df376e4d3 Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Fri, 22 Nov 2024 16:04:56 +0100 Subject: [PATCH 20/23] Fix typo in `AdditionalParamsOf` --- core-primitives/extrinsics-factory/src/lib.rs | 6 +++--- core-primitives/extrinsics-factory/src/mock.rs | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/core-primitives/extrinsics-factory/src/lib.rs b/core-primitives/extrinsics-factory/src/lib.rs index 26e1702586..0dc1057f1d 100644 --- a/core-primitives/extrinsics-factory/src/lib.rs +++ b/core-primitives/extrinsics-factory/src/lib.rs @@ -64,11 +64,11 @@ pub trait CreateExtrinsics { fn create_extrinsics( &self, calls: &[(OpaqueCall, GenericMortality)], - extrinsics_params: Option>, + extrinsics_params: Option>, ) -> Result>; } -pub type AdditionParamsOf = +pub type AdditionalParamsOf = ::Index, ::Hash>>::AdditionalParams; /// Extrinsics factory @@ -126,7 +126,7 @@ where fn create_extrinsics( &self, calls: &[(OpaqueCall, GenericMortality)], - extrinsics_params: Option>, + extrinsics_params: Option>, ) -> Result> { let mut nonce_lock = self.nonce_cache.load_for_mutation()?; let mut nonce_value = nonce_lock.0; diff --git a/core-primitives/extrinsics-factory/src/mock.rs b/core-primitives/extrinsics-factory/src/mock.rs index 60102b57bc..840efddf66 100644 --- a/core-primitives/extrinsics-factory/src/mock.rs +++ b/core-primitives/extrinsics-factory/src/mock.rs @@ -14,7 +14,7 @@ limitations under the License. */ -use crate::{error::Result, AdditionParamsOf, CreateExtrinsics}; +use crate::{error::Result, AdditionalParamsOf, CreateExtrinsics}; use core::marker::PhantomData; use itp_types::{parentchain::GenericMortality, Balance, OpaqueCall}; use sp_runtime::OpaqueExtrinsic; @@ -46,7 +46,7 @@ impl CreateExtrinsics for ExtrinsicsFactoryMock { &self, _calls: &[(OpaqueCall, GenericMortality)], _additional_params: Option< - AdditionParamsOf, + AdditionalParamsOf, >, ) -> Result> { // Intention was to map an OpaqueCall to some dummy OpaqueExtrinsic, From fa0ccddbb8e6559525cd04029c162611783deb7a Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Fri, 22 Nov 2024 16:09:01 +0100 Subject: [PATCH 21/23] remove parentchainapi trait --- .../node-api/api-client-types/src/lib.rs | 18 ++++-------------- service/src/main_impl.rs | 2 +- .../src/ocall_bridge/worker_on_chain_ocall.rs | 2 +- service/src/sidechain_setup.rs | 1 - 4 files changed, 6 insertions(+), 17 deletions(-) diff --git a/core-primitives/node-api/api-client-types/src/lib.rs b/core-primitives/node-api/api-client-types/src/lib.rs index 8107ab7f5f..acae748757 100644 --- a/core-primitives/node-api/api-client-types/src/lib.rs +++ b/core-primitives/node-api/api-client-types/src/lib.rs @@ -77,17 +77,7 @@ pub type ParentchainSignature = Signature; pub type Signature = Option<(Address, PairSignature, SignedExtra)>; #[cfg(feature = "std")] -pub use api::*; - -#[cfg(feature = "std")] -mod api { - use super::ParentchainRuntimeConfig; - use substrate_api_client::Api; - - pub use substrate_api_client::{ - api::Error as ApiClientError, - rpc::{tungstenite_client::TungsteniteRpcClient, Error as RpcClientError}, - }; - - pub type ParentchainApi = Api; -} +pub use substrate_api_client::{ + api::Error as ApiClientError, + rpc::{tungstenite_client::TungsteniteRpcClient, Error as RpcClientError}, +}; diff --git a/service/src/main_impl.rs b/service/src/main_impl.rs index 36cf8f0541..662be30856 100644 --- a/service/src/main_impl.rs +++ b/service/src/main_impl.rs @@ -39,7 +39,7 @@ use itp_enclave_api::{ teeracle_api::TeeracleApi, }; use itp_node_api::{ - api_client::{AccountApi, PalletTeerexApi, ParentchainApi}, + api_client::{AccountApi, PalletTeerexApi}, metadata::NodeMetadata, node_api_factory::{CreateNodeApi, NodeApiFactory}, }; diff --git a/service/src/ocall_bridge/worker_on_chain_ocall.rs b/service/src/ocall_bridge/worker_on_chain_ocall.rs index c068a2c5e2..c0514e548d 100644 --- a/service/src/ocall_bridge/worker_on_chain_ocall.rs +++ b/service/src/ocall_bridge/worker_on_chain_ocall.rs @@ -25,7 +25,7 @@ use ita_parentchain_interface::{ target_b::{api_client_types::TargetBApi, api_factory::TargetBNodeApiFactory}, ParentchainRuntimeConfig, }; -use itp_api_client_types::{ParentchainApi, Request}; +use itp_api_client_types::Request; use itp_node_api::{ api_client::{AccountApi, Config}, node_api_factory::{CreateNodeApi, NodeApiFactory}, diff --git a/service/src/sidechain_setup.rs b/service/src/sidechain_setup.rs index f140c0fe58..ac99e80ed4 100644 --- a/service/src/sidechain_setup.rs +++ b/service/src/sidechain_setup.rs @@ -23,7 +23,6 @@ use crate::{ }; use futures::executor::block_on; use ita_parentchain_interface::integritee::api_client_types::IntegriteeApi; -use itp_api_client_types::ParentchainApi; use itp_enclave_api::{enclave_base::EnclaveBase, sidechain::Sidechain}; use itp_node_api::api_client::{pallet_sidechain::PalletSidechainApi, PalletTeerexApi}; use itp_settings::{ From 36779c8b4d27d871ea1b3e7bfb4f3fdfa86cebb5 Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Fri, 22 Nov 2024 16:43:07 +0100 Subject: [PATCH 22/23] fmt --- service/src/main_impl.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/service/src/main_impl.rs b/service/src/main_impl.rs index 662be30856..5c71895a83 100644 --- a/service/src/main_impl.rs +++ b/service/src/main_impl.rs @@ -679,9 +679,12 @@ fn start_worker( let maybe_target_a_rpc_api = if let Some(url) = config.target_a_parentchain_rpc_endpoint() { println!("Initializing parentchain TargetA with url: {}", url); - let api = NodeApiFactory::new(url, AccountKeyring::Alice.pair()) - .create_api() - .unwrap_or_else(|_| panic!("[TargetA] Failed to create parentchain node API")); + let api = ita_parentchain_interface::target_a::api_factory::TargetANodeApiFactory::new( + url, + AccountKeyring::Alice.pair(), + ) + .create_api() + .unwrap_or_else(|_| panic!("[TargetA] Failed to create parentchain node API")); let mut handles = init_target_parentchain( &enclave, &tee_accountid, From 81d37659505d1979eab04c760060138774d5f5e0 Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Fri, 22 Nov 2024 16:44:06 +0100 Subject: [PATCH 23/23] re-activate check for rarenewal period to derive account funding --- service/src/account_funding.rs | 56 +++++++++++++++++----------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/service/src/account_funding.rs b/service/src/account_funding.rs index a6926d9852..66a2293412 100644 --- a/service/src/account_funding.rs +++ b/service/src/account_funding.rs @@ -193,34 +193,34 @@ where min_required_funds += 1000 * transfer_fee; // // Check if this is an integritee chain and Compose a register_sgx_enclave extrinsic - // if let Ok(ra_renewal) = api.get_constant::("Teerex", "MaxAttestationRenewalPeriod") { - // info!("[{:?}] this chain has the teerex pallet. estimating RA fees", parentchain_id); - // let nonce = api.get_nonce_of(accountid)?; - // - // let encoded_xt: Bytes = compose_extrinsic_with_nonce!( - // api, - // nonce, - // TEEREX, - // "register_sgx_enclave", - // vec![0u8; SGX_RA_PROOF_MAX_LEN], - // Some(vec![0u8; MAX_URL_LEN]), - // SgxAttestationMethod::Dcap { proxied: false } - // ) - // .encode() - // .into(); - // let tx_fee = - // api.get_fee_details(&encoded_xt, None).unwrap().unwrap().inclusion_fee.unwrap(); - // let ra_fee = tx_fee.base_fee + tx_fee.len_fee + tx_fee.adjusted_weight_fee; - // info!( - // "[{:?}] one enclave registration costs {:?} and needs to be renewed every {:?}h", - // parentchain_id, - // ra_fee, - // ra_renewal / 1_000 / 3_600 - // ); - // min_required_funds += 5 * ra_fee; - // } else { - // info!("[{:?}] this chain has no teerex pallet, no need to add RA fees", parentchain_id); - // } + if let Ok(ra_renewal) = api.get_constant::("Teerex", "MaxAttestationRenewalPeriod") { + info!("[{:?}] this chain has the teerex pallet. estimating RA fees", parentchain_id); + let nonce = api.get_nonce_of(accountid)?; + + let encoded_xt: Bytes = compose_extrinsic_with_nonce!( + api, + nonce, + TEEREX, + "register_sgx_enclave", + vec![0u8; SGX_RA_PROOF_MAX_LEN], + Some(vec![0u8; MAX_URL_LEN]), + SgxAttestationMethod::Dcap { proxied: false } + ) + .encode() + .into(); + let tx_fee = + api.get_fee_details(&encoded_xt, None).unwrap().unwrap().inclusion_fee.unwrap(); + let ra_fee = tx_fee.base_fee + tx_fee.len_fee + tx_fee.adjusted_weight_fee; + info!( + "[{:?}] one enclave registration costs {:?} and needs to be renewed every {:?}h", + parentchain_id, + ra_fee, + ra_renewal / 1_000 / 3_600 + ); + min_required_funds += 5 * ra_fee; + } else { + info!("[{:?}] this chain has no teerex pallet, no need to add RA fees", parentchain_id); + } info!( "[{:?}] we estimate the funding requirement for the primary validateer (worst case) to be {:?}",