Skip to content

Commit ecbca3a

Browse files
zhizming-zhongjingleizhang
andauthored
Enclave update [4-1]: SGX-Runtime migration (#1303)
* runtime-migration first commit * minor update * remove comment out line --------- Co-authored-by: ericzhang <jingleizhang@users.noreply.github.com>
1 parent a50c615 commit ecbca3a

File tree

12 files changed

+103
-8
lines changed

12 files changed

+103
-8
lines changed

tee-worker/Cargo.lock

Lines changed: 0 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

tee-worker/app-libs/sgx-runtime/src/lib.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@
3131
#[cfg(feature = "evm")]
3232
mod evm;
3333

34+
mod migration;
35+
3436
#[cfg(feature = "evm")]
3537
pub use evm::{
3638
AddressMapping, EnsureAddressTruncated, EvmCall, FeeCalculator, FixedGasPrice,
@@ -105,13 +107,15 @@ pub type UncheckedExtrinsic =
105107
generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
106108
/// Extrinsic type that has already been checked.
107109
pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra>;
110+
108111
/// Executive: handles dispatch to the various modules.
109112
pub type Executive = frame_executive::Executive<
110113
Runtime,
111114
Block,
112115
frame_system::ChainContext<Runtime>,
113116
Runtime,
114117
AllPalletsWithSystem,
118+
migration::Upgrade,
115119
>;
116120

117121
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
use super::*;
2+
3+
use crate::{pallet_imt::migrations, Runtime};
4+
use frame_support::{traits::OnRuntimeUpgrade, weights::Weight};
5+
6+
// This is just an example of how to write a custom migration
7+
// It has no effect on tee-worker running
8+
// For more details, see: https://docs.substrate.io/maintain/runtime-upgrades/#storage-migration
9+
pub struct Upgrade;
10+
impl OnRuntimeUpgrade for Upgrade {
11+
fn on_runtime_upgrade() -> Weight {
12+
migrations::migrate_to_v1::<Runtime, IdentityManagement>()
13+
}
14+
}

tee-worker/app-libs/stf/src/stf_sgx.rs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,14 @@ use crate::test_genesis::test_genesis_setup;
2121
use crate::{helpers::enclave_signer_account, Stf, StfError, ENCLAVE_ACCOUNT_KEY};
2222
use codec::Encode;
2323
use frame_support::traits::{OriginTrait, UnfilteredDispatchable};
24+
use ita_sgx_runtime::Executive;
2425
use itp_node_api::metadata::{
2526
pallet_imp::IMPCallIndexes, pallet_teerex::TeerexCallIndexes, provider::AccessNodeMetadata,
2627
};
2728
use itp_sgx_externalities::SgxExternalitiesTrait;
2829
use itp_stf_interface::{
2930
parentchain_pallet::ParentchainPalletInterface,
31+
runtime_upgrade::RuntimeUpgradeInterface,
3032
sudo_pallet::SudoPalletInterface,
3133
system_pallet::{SystemPalletAccountInterface, SystemPalletEventInterface},
3234
ExecuteCall, ExecuteGetter, InitState, StateCallInterface, StateGetterInterface, UpdateState,
@@ -247,6 +249,42 @@ where
247249
}
248250
}
249251

252+
impl<Call, Getter, State, Runtime> RuntimeUpgradeInterface<State>
253+
for Stf<Call, Getter, State, Runtime>
254+
where
255+
State: SgxExternalitiesTrait,
256+
Runtime: frame_system::Config,
257+
{
258+
type Error = StfError;
259+
260+
fn on_runtime_upgrade(state: &mut State) -> Result<(), Self::Error> {
261+
// Returns if the runtime was upgraded since the last time this function was called.
262+
let runtime_upgraded =
263+
|| -> bool {
264+
let last = frame_system::LastRuntimeUpgrade::<Runtime>::get();
265+
let current = <<Runtime as frame_system::Config>::Version as frame_support::traits::Get<_>>::get();
266+
267+
if last.map(|v| v.was_upgraded(&current)).unwrap_or(true) {
268+
frame_system::LastRuntimeUpgrade::<Runtime>::put(
269+
frame_system::LastRuntimeUpgradeInfo::from(current),
270+
);
271+
debug!("Do some migraions");
272+
true
273+
} else {
274+
debug!("No need to migrate");
275+
false
276+
}
277+
};
278+
279+
state.execute_with(|| {
280+
if runtime_upgraded() {
281+
Executive::execute_on_runtime_upgrade();
282+
}
283+
});
284+
Ok(())
285+
}
286+
}
287+
250288
pub fn storage_hashes_to_update_per_shard(_shard: &ShardIdentifier) -> Vec<Vec<u8>> {
251289
Vec::new()
252290
}

tee-worker/core-primitives/stf-executor/Cargo.toml

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ sgx_tstd = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sd
1111
sgx_types = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git" }
1212

1313
# local dependencies
14-
ita-sgx-runtime = { path = "../../app-libs/sgx-runtime", default-features = false }
1514
ita-stf = { path = "../../app-libs/stf", default-features = false }
1615
itp-node-api = { path = "../node-api", default-features = false }
1716
itp-ocall-api = { path = "../ocall-api", default-features = false }
@@ -57,7 +56,6 @@ mocks = []
5756
std = [
5857
# local
5958
"ita-stf/std",
60-
"ita-sgx-runtime/std",
6159
"itp-node-api/std",
6260
"itp-ocall-api/std",
6361
"itp-sgx-crypto/std",

tee-worker/core-primitives/stf-executor/src/executor.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,8 @@ use itp_node_api::metadata::{
3333
use itp_ocall_api::{EnclaveAttestationOCallApi, EnclaveOnChainOCallApi};
3434
use itp_sgx_externalities::{SgxExternalitiesTrait, StateHash};
3535
use itp_stf_interface::{
36-
parentchain_pallet::ParentchainPalletInterface, ExecuteCall, StateCallInterface, UpdateState,
36+
parentchain_pallet::ParentchainPalletInterface, runtime_upgrade::RuntimeUpgradeInterface,
37+
ExecuteCall, StateCallInterface, UpdateState,
3738
};
3839
use itp_stf_primitives::types::ShardIdentifier;
3940
use itp_stf_state_handler::{handle_state::HandleState, query_shard_state::QueryShardState};
@@ -244,12 +245,13 @@ where
244245
Stf: UpdateState<
245246
StateHandler::StateT,
246247
<StateHandler::StateT as SgxExternalitiesTrait>::SgxExternalitiesDiffType,
247-
> + StateCallInterface<TrustedCallSigned, StateHandler::StateT, NodeMetadataRepository>,
248+
> + StateCallInterface<TrustedCallSigned, StateHandler::StateT, NodeMetadataRepository> + RuntimeUpgradeInterface<StateHandler::StateT>,
248249
<StateHandler::StateT as SgxExternalitiesTrait>::SgxExternalitiesDiffType:
249250
IntoIterator<Item = (Vec<u8>, Option<Vec<u8>>)>,
250251
<StateHandler::StateT as SgxExternalitiesTrait>::SgxExternalitiesDiffType:
251252
From<BTreeMap<Vec<u8>, Option<Vec<u8>>>>,
252253
<Stf as StateCallInterface<TrustedCallSigned, StateHandler::StateT, NodeMetadataRepository>>::Error: Debug,
254+
<Stf as RuntimeUpgradeInterface<StateHandler::StateT>>::Error: Debug,
253255
{
254256
type Externalities = StateHandler::StateT;
255257

@@ -273,6 +275,9 @@ where
273275
let mut state = prepare_state_function(state);
274276
let mut executed_and_failed_calls = Vec::<ExecutedOperation>::new();
275277

278+
// TODO: maybe we can move it to `prepare_state_function`. It seems more reasonable.
279+
let _ = Stf::on_runtime_upgrade(&mut state);
280+
276281
// Iterate through all calls until time is over.
277282
for trusted_call_signed in trusted_calls.into_iter() {
278283
// Break if allowed time window is over.

tee-worker/core-primitives/stf-interface/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ use itp_types::{OpaqueCall, ShardIdentifier};
3030
#[cfg(feature = "mocks")]
3131
pub mod mocks;
3232
pub mod parentchain_pallet;
33+
pub mod runtime_upgrade;
3334
pub mod sudo_pallet;
3435
pub mod system_pallet;
3536

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Copyright 2020-2023 Litentry Technologies GmbH.
2+
// This file is part of Litentry.
3+
//
4+
// Litentry is free software: you can redistribute it and/or modify
5+
// it under the terms of the GNU General Public License as published by
6+
// the Free Software Foundation, either version 3 of the License, or
7+
// (at your option) any later version.
8+
//
9+
// Litentry is distributed in the hope that it will be useful,
10+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
// GNU General Public License for more details.
13+
//
14+
// You should have received a copy of the GNU General Public License
15+
// along with Litentry. If not, see <https://www.gnu.org/licenses/>.
16+
17+
pub trait RuntimeUpgradeInterface<State> {
18+
type Error;
19+
20+
fn on_runtime_upgrade(state: &mut State) -> Result<(), Self::Error>;
21+
}

tee-worker/enclave-runtime/Cargo.lock

Lines changed: 0 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

tee-worker/enclave-runtime/src/test/tests_main.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -409,8 +409,8 @@ fn test_create_state_diff() {
409409
get_from_state_diff(&state_diff, &account_key_hash::<AccountId>(&receiver.into()));
410410

411411
// state diff should consist of the following updates:
412-
// (last_hash, sidechain block_number, sender_funds, receiver_funds, [no clear, after polkadot_v0.9.26 update], events)
413-
assert_eq!(state_diff.len(), 6);
412+
// (last_hash, sidechain block_number, sender_funds, receiver_funds, [no clear, after polkadot_v0.9.26 update], events, frame_system::LastRuntimeUpgradeInfo, pallet_identity_management_tee::migrations)
413+
assert_eq!(state_diff.len(), 8);
414414
assert_eq!(receiver_acc_info.data.free, 1000);
415415
assert_eq!(sender_acc_info.data.free, 1000);
416416
}

0 commit comments

Comments
 (0)