Skip to content

Commit 3b3eac6

Browse files
committed
Check mrenclave and scheduled height before produce blocks(fix #1295)
1 parent 7f33bd9 commit 3b3eac6

File tree

17 files changed

+228
-53
lines changed

17 files changed

+228
-53
lines changed

tee-worker/Cargo.lock

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

tee-worker/core/parentchain/indirect-calls-executor/src/executor/litentry/get_scheduled_enclave.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ impl ScheduledEnclaveUpdate {
5656
sidechain_block_number,
5757
mr_enclave,
5858
};
59-
let old_enclaves = GLOBAL_SIDECHAIN_SCHEDULED_ENCLABES.get()?;
59+
let old_enclaves = GLOBAL_SIDECHAIN_SCHEDULED_ENCLABES.get().unwrap_or_default();
6060
// unwrap is safe here, because GLOBAL_SIDECHAIN_SCHEDULED_ENCLABES is initialized in `init_enclave()`
6161
let mut scheduled_enclaves = Arc::<ScheduledEnclaves>::try_unwrap(old_enclaves).unwrap();
6262
scheduled_enclaves.add_scheduled_enclave(scheduled_enclave)?;

tee-worker/enclave-runtime/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,7 @@ itp-top-pool-author = { path = "../core-primitives/top-pool-author", default-fea
126126
itp-types = { path = "../core-primitives/types", default-features = false }
127127
itp-utils = { path = "../core-primitives/utils", default-features = false, features = ["sgx"] }
128128
its-block-verification = { path = "../sidechain/block-verification", default-features = false }
129+
its-consensus-common = { path = "../sidechain/consensus/common", default-features = false, features = ["sgx"] }
129130
its-primitives = { path = "../sidechain/primitives", default-features = false }
130131
its-sidechain = { path = "../sidechain/sidechain-crate", default-features = false, features = ["sgx"] }
131132

tee-worker/enclave-runtime/src/initialization/mod.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ use itc_tls_websocket_server::{
6060
use itp_attestation_handler::IntelAttestationHandler;
6161
use itp_component_container::{ComponentGetter, ComponentInitializer};
6262
use itp_enclave_scheduled::{ScheduledEnclaveHandle, ScheduledEnclaves};
63+
use itp_ocall_api::EnclaveAttestationOCallApi;
6364
use itp_primitives_cache::GLOBAL_PRIMITIVES_CACHE;
6465
use itp_settings::files::STATE_SNAPSHOTS_CACHE_SIZE;
6566
use itp_sgx_crypto::{aes, ed25519, rsa3072, AesSeal, Ed25519Seal, Rsa3072Seal};
@@ -72,6 +73,7 @@ use itp_stf_state_handler::{
7273
use itp_top_pool::pool::Options as PoolOptions;
7374
use itp_top_pool_author::author::AuthorTopFilter;
7475
use itp_types::ShardIdentifier;
76+
use its_consensus_common::block_production_suspension::set_global_block_suspender;
7577
use its_sidechain::block_composer::BlockComposer;
7678
use log::*;
7779
use sp_core::crypto::Pair;
@@ -130,6 +132,9 @@ pub(crate) fn init_enclave(mu_ra_url: String, untrusted_worker_url: String) -> E
130132
let ocall_api = Arc::new(OcallApi);
131133
GLOBAL_OCALL_API_COMPONENT.initialize(ocall_api.clone());
132134

135+
let mr_enclave = ocall_api.get_mrenclave_of_self()?.m;
136+
set_global_block_suspender(false, mr_enclave);
137+
133138
// For debug purposes, list shards. no problem to panic if fails.
134139
let shards = state_handler.list_shards().unwrap();
135140
debug!("found the following {} shards on disk:", shards.len());

tee-worker/service/src/setup.rs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@ use crate::error::{Error, ServiceResult};
2020
use codec::Encode;
2121
use itp_enclave_api::{enclave_base::EnclaveBase, Enclave};
2222
use itp_settings::files::{
23-
LAST_SLOT_BIN, LIGHT_CLIENT_DB, SHARDS_PATH, SHIELDING_KEY_FILE, SIDECHAIN_STORAGE_PATH,
24-
SIGNING_KEY_FILE,
23+
LAST_SLOT_BIN, LIGHT_CLIENT_DB, SCHEDULED_ENCLAVE_FILE, SHARDS_PATH, SHIELDING_KEY_FILE,
24+
SIDECHAIN_STORAGE_PATH, SIGNING_KEY_FILE,
2525
};
2626
use itp_types::ShardIdentifier;
2727
use log::*;
@@ -49,6 +49,7 @@ pub(crate) fn initialize_shard_and_keys(
4949
println!("[+] Generate key files");
5050
generate_signing_key_file(enclave);
5151
generate_shielding_key_file(enclave);
52+
generate_scheduled_enclave_file();
5253

5354
Ok(())
5455
}
@@ -96,6 +97,14 @@ pub(crate) fn generate_signing_key_file(enclave: &Enclave) {
9697
}
9798
}
9899

100+
pub(crate) fn generate_scheduled_enclave_file() {
101+
info!("*** Get scheduled enclaves from the TEE\n");
102+
let path = Path::new(SCHEDULED_ENCLAVE_FILE);
103+
if !path.exists() {
104+
let _file = File::create(SCHEDULED_ENCLAVE_FILE).unwrap();
105+
}
106+
}
107+
99108
pub(crate) fn generate_shielding_key_file(enclave: &Enclave) {
100109
info!("*** Get the public key from the TEE\n");
101110
let pubkey = enclave.get_rsa_shielding_pubkey().unwrap();
@@ -117,6 +126,7 @@ fn purge_files(root_directory: &Path) -> ServiceResult<()> {
117126

118127
remove_file_if_it_exists(root_directory, LAST_SLOT_BIN)?;
119128
remove_file_if_it_exists(root_directory, LIGHT_CLIENT_DB)?;
129+
remove_file_if_it_exists(root_directory, SCHEDULED_ENCLAVE_FILE)?;
120130
remove_file_if_it_exists(root_directory, light_client_backup_file().as_str())?;
121131

122132
Ok(())

tee-worker/sidechain/consensus/aura/Cargo.toml

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,10 @@ sp-runtime = { default-features = false, git = "https://github.com/paritytech/su
2020
# local deps
2121
ita-stf = { path = "../../../app-libs/stf", default-features = false }
2222
itc-parentchain-block-import-dispatcher = { path = "../../../core/parentchain/block-import-dispatcher", default-features = false }
23+
itc-parentchain-indirect-calls-executor = { path = "../../../core/parentchain/indirect-calls-executor", default-features = false }
24+
itp-component-container = { path = "../../../core-primitives/component-container", default-features = false, optional = true }
2325
itp-enclave-metrics = { path = "../../../core-primitives/enclave-metrics", default-features = false }
26+
itp-enclave-scheduled = { path = "../../../core-primitives/sgx/enclave-scheduled", default-features = false, optional = true }
2427
itp-ocall-api = { path = "../../../core-primitives/ocall-api", default-features = false }
2528
itp-settings = { path = "../../../core-primitives/settings" }
2629
itp-sgx-crypto = { path = "../../../core-primitives/sgx/crypto", default-features = false }
@@ -61,6 +64,9 @@ sgx = [
6164
"itp-stf-executor/sgx",
6265
"itp-stf-state-handler/sgx",
6366
"itp-time-utils/sgx",
67+
"itc-parentchain-indirect-calls-executor/sgx",
68+
"itp-component-container/sgx",
69+
"itp-enclave-scheduled/sgx",
6470
"itp-utils/sgx",
6571
"its-block-composer/sgx",
6672
"its-consensus-common/sgx",
@@ -80,6 +86,9 @@ std = [
8086
#local
8187
"ita-stf/std",
8288
"itc-parentchain-block-import-dispatcher/std",
89+
"itc-parentchain-indirect-calls-executor/std",
90+
"itp-enclave-scheduled/std",
91+
"itp-component-container/std",
8392
"itp-enclave-metrics/std",
8493
"itp-ocall-api/std",
8594
"itp-sgx-crypto/std",

tee-worker/sidechain/consensus/aura/src/block_importer.rs

Lines changed: 48 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,15 +23,23 @@ pub use its_consensus_common::BlockImport;
2323
use crate::{AuraVerifier, EnclaveOnChainOCallApi, SidechainBlockTrait};
2424
use ita_stf::hash::TrustedOperationOrHash;
2525
use itc_parentchain_block_import_dispatcher::triggered_dispatcher::TriggerParentchainBlockImport;
26+
use itc_parentchain_indirect_calls_executor::executor::litentry::get_scheduled_enclave::GLOBAL_SIDECHAIN_SCHEDULED_ENCLABES;
27+
use itp_component_container::component_container::ComponentGetter;
2628
use itp_enclave_metrics::EnclaveMetric;
29+
use itp_enclave_scheduled::ScheduledEnclaveHandle;
2730
use itp_ocall_api::{EnclaveMetricsOCallApi, EnclaveSidechainOCallApi};
2831
use itp_settings::sidechain::SLOT_DURATION;
2932
use itp_sgx_crypto::{key_repository::AccessKey, StateCrypto};
3033
use itp_sgx_externalities::SgxExternalities;
3134
use itp_stf_state_handler::handle_state::HandleState;
3235
use itp_top_pool_author::traits::{AuthorApi, OnBlockImported};
33-
use itp_types::H256;
34-
use its_consensus_common::Error as ConsensusError;
36+
use itp_types::{ShardIdentifier, H256};
37+
use its_consensus_common::{
38+
block_production_suspension::{
39+
BlockProductionSuspender, SuspendBlockProductionTrait, GLOBAL_BLOCK_SUSPENDER,
40+
},
41+
Error as ConsensusError,
42+
};
3543
use its_primitives::traits::{
3644
BlockData, Header as HeaderTrait, ShardIdentifierFor, SignedBlock as SignedBlockTrait,
3745
};
@@ -193,6 +201,7 @@ impl<
193201
type SidechainState = SgxExternalities;
194202
type StateCrypto = <StateKeyRepository as AccessKey>::KeyType;
195203
type Context = OCallApi;
204+
type BlockSuspender = BlockProductionSuspender;
196205

197206
fn verifier(
198207
&self,
@@ -236,9 +245,40 @@ impl<
236245
where
237246
F: FnOnce(&Self::SidechainState) -> Result<SignedSidechainBlock, ConsensusError>,
238247
{
239-
self.state_handler
248+
let sidechain_block = self
249+
.state_handler
240250
.execute_on_current(shard, |state, _| verifying_function(state))
241-
.map_err(|e| ConsensusError::Other(format!("{:?}", e).into()))?
251+
.map_err(|e| ConsensusError::Other(format!("{:?}", e).into()))??;
252+
let block_number = sidechain_block.block().header().block_number();
253+
// get schedule block_number and mr_enclave
254+
let scheduled_enclaves = GLOBAL_SIDECHAIN_SCHEDULED_ENCLABES
255+
.get()
256+
.map_err(|_| ConsensusError::GetScheduledEnclavesFailed)?;
257+
if let Some(scheduled_enclave) = scheduled_enclaves.get_next_scheduled_enclave(block_number)
258+
{
259+
let block_suspender = self.block_suspender();
260+
let scheduled_mr_enclave = scheduled_enclave.mr_enclave;
261+
let scheduled_block_number = scheduled_enclave.sidechain_block_number;
262+
let current_mr_enclave = block_suspender
263+
.current_mr_enclave()
264+
.map_err(|_| ConsensusError::GetMrEnclaveFailed)?;
265+
if current_mr_enclave != scheduled_mr_enclave {
266+
if scheduled_block_number <= block_number {
267+
block_suspender
268+
.suspend_for_production()
269+
.map_err(|_| ConsensusError::SetBlockSuspenderFailed)?;
270+
warn!("need to update, reason: enclave is outdated");
271+
}
272+
if scheduled_block_number == block_number {
273+
let old_id = ShardIdentifier::from_slice(&current_mr_enclave[..]);
274+
let new_id = ShardIdentifier::from_slice(&scheduled_mr_enclave[..]);
275+
self.state_handler
276+
.migrate_shard(old_id, new_id)
277+
.map_err(|_| ConsensusError::MigrationFailed)?;
278+
}
279+
}
280+
}
281+
Ok(sidechain_block)
242282
}
243283

244284
fn state_key(&self) -> Result<Self::StateCrypto, ConsensusError> {
@@ -251,6 +291,10 @@ impl<
251291
&self.ocall_api
252292
}
253293

294+
fn block_suspender(&self) -> Self::BlockSuspender {
295+
GLOBAL_BLOCK_SUSPENDER.clone()
296+
}
297+
254298
fn import_parentchain_block(
255299
&self,
256300
sidechain_block: &SignedSidechainBlock::Block,

tee-worker/sidechain/consensus/aura/src/lib.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,10 @@ use itc_parentchain_block_import_dispatcher::triggered_dispatcher::TriggerParent
3434
use itp_ocall_api::EnclaveOnChainOCallApi;
3535
use itp_time_utils::duration_now;
3636
use its_block_verification::slot::slot_author;
37-
use its_consensus_common::{Environment, Error as ConsensusError, Proposer};
37+
use its_consensus_common::{
38+
block_production_suspension::{BlockProductionSuspender, GLOBAL_BLOCK_SUSPENDER},
39+
Environment, Error as ConsensusError, Proposer,
40+
};
3841
use its_consensus_slots::{SimpleSlotWorker, Slot, SlotInfo};
3942
use its_primitives::{
4043
traits::{Block as SidechainBlockTrait, Header as HeaderTrait, SignedBlock},
@@ -137,6 +140,7 @@ where
137140
type Claim = AuthorityPair::Public;
138141
type EpochData = Vec<AuthorityId<AuthorityPair>>;
139142
type Output = SignedSidechainBlock;
143+
type BlockSuspender = BlockProductionSuspender;
140144

141145
fn logging_target(&self) -> &'static str {
142146
"aura"
@@ -187,6 +191,10 @@ where
187191
self.environment.init(header, shard)
188192
}
189193

194+
fn block_suspender(&mut self) -> Self::BlockSuspender {
195+
GLOBAL_BLOCK_SUSPENDER.clone()
196+
}
197+
190198
fn proposing_remaining_duration(&self, slot_info: &SlotInfo<ParentchainBlock>) -> Duration {
191199
proposing_remaining_duration(slot_info, duration_now())
192200
}

tee-worker/sidechain/consensus/aura/src/test/block_importer_tests.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,13 @@ use crate::{block_importer::BlockImporter, test::fixtures::validateer, ShardIden
1919
use codec::Encode;
2020
use core::assert_matches::assert_matches;
2121
use itc_parentchain_block_import_dispatcher::trigger_parentchain_block_import_mock::TriggerParentchainBlockImportMock;
22+
use itc_parentchain_indirect_calls_executor::executor::litentry::get_scheduled_enclave::GLOBAL_SIDECHAIN_SCHEDULED_ENCLABES;
2223
use itc_parentchain_test::{
2324
parentchain_block_builder::ParentchainBlockBuilder,
2425
parentchain_header_builder::ParentchainHeaderBuilder,
2526
};
27+
use itp_component_container::ComponentInitializer;
28+
use itp_enclave_scheduled::ScheduledEnclaves;
2629
use itp_sgx_crypto::{aes::Aes, mocks::KeyRepositoryMock, StateCrypto};
2730
use itp_sgx_externalities::SgxExternalitiesDiffType;
2831
use itp_stf_state_handler::handle_state::HandleState;
@@ -146,15 +149,16 @@ fn default_authority_signed_block(
146149

147150
#[test]
148151
fn simple_block_import_works() {
152+
let scheduled_enclaves = ScheduledEnclaves::default();
153+
GLOBAL_SIDECHAIN_SCHEDULED_ENCLABES.initialize(Arc::new(scheduled_enclaves));
149154
let parentchain_header = ParentchainHeaderBuilder::default().build();
150155
let (block_importer, state_handler, _) =
151156
test_fixtures_with_default_import_trigger(&parentchain_header);
152157
let signed_sidechain_block =
153158
default_authority_signed_block(&parentchain_header, state_handler.as_ref());
154159

155-
block_importer
156-
.import_block(signed_sidechain_block, &parentchain_header)
157-
.unwrap();
160+
let result = block_importer.import_block(signed_sidechain_block, &parentchain_header);
161+
assert!(result.is_ok());
158162
}
159163

160164
#[test]

tee-worker/sidechain/consensus/common/Cargo.toml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,15 @@ version = "0.9.0"
66

77
[dependencies]
88
codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false }
9+
lazy_static = { version = "1.1.0", features = ["spin_no_std"] }
910
log = { version = "0.4", default-features = false }
1011
thiserror = { version = "1.0.26", optional = true }
1112

1213
# local deps
14+
itc-parentchain-indirect-calls-executor = { path = "../../../core/parentchain/indirect-calls-executor", default-features = false }
1315
itc-parentchain-light-client = { path = "../../../core/parentchain/light-client", default-features = false }
1416
itp-block-import-queue = { path = "../../../core-primitives/block-import-queue", default-features = false }
17+
itp-component-container = { path = "../../../core-primitives/component-container", default-features = false, optional = true }
1518
itp-extrinsics-factory = { path = "../../../core-primitives/extrinsics-factory", default-features = false }
1619
itp-node-api-metadata = { path = "../../../core-primitives/node-api/metadata", default-features = false }
1720
itp-node-api-metadata-provider = { path = "../../../core-primitives/node-api/metadata-provider", default-features = false }
@@ -50,10 +53,12 @@ sgx = [
5053
"itc-parentchain-light-client/sgx",
5154
"itp-block-import-queue/sgx",
5255
"itp-extrinsics-factory/sgx",
56+
"itp-component-container/sgx",
5357
"itp-node-api-metadata-provider/sgx",
5458
"itp-sgx-crypto/sgx",
5559
"itp-sgx-externalities/sgx",
5660
"its-state/sgx",
61+
"itc-parentchain-indirect-calls-executor/sgx",
5762
# scs
5863
"its-block-verification/sgx",
5964
]
@@ -63,10 +68,12 @@ std = [
6368
"thiserror",
6469
# local
6570
"itc-parentchain-light-client/std",
71+
"itp-component-container/std",
6672
"itp-block-import-queue/std",
6773
"itp-extrinsics-factory/std",
6874
"itp-node-api-metadata/std",
6975
"itp-node-api-metadata-provider/std",
76+
"itc-parentchain-indirect-calls-executor/std",
7077
"itp-ocall-api/std",
7178
"itp-sgx-crypto/std",
7279
"itp-sgx-externalities/std",

0 commit comments

Comments
 (0)