Skip to content

Commit

Permalink
update nonce via rpc before producing a new sidechain block (#1640)
Browse files Browse the repository at this point in the history
* update nonce via rpc before producing a new sidechain block

* clippy

* cleanup
  • Loading branch information
brenzi authored Nov 8, 2024
1 parent 78dc0b7 commit 7cfeaa5
Show file tree
Hide file tree
Showing 5 changed files with 54 additions and 8 deletions.
4 changes: 3 additions & 1 deletion core-primitives/types/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,19 +116,21 @@ pub enum WorkerRequest {
ChainStorage(Vec<u8>, Option<BlockHash>), // (storage_key, at_block)
/// for awareness: we call it unverified because there is no way how the enclave could verify the correctness of the information
LatestParentchainHeaderUnverified,
NextNonceFor(AccountId),
}

#[derive(Encode, Decode, Clone, Debug, PartialEq)]
pub enum WorkerResponse<H: HeaderTrait, V: Encode + Decode> {
ChainStorage(Vec<u8>, Option<V>, Option<Vec<Vec<u8>>>), // (storage_key, storage_value, storage_proof)
LatestParentchainHeaderUnverified(H),
NextNonce(Option<Nonce>),
}

impl<H: HeaderTrait> From<WorkerResponse<H, Vec<u8>>> for StorageEntry<Vec<u8>> {
fn from(response: WorkerResponse<H, Vec<u8>>) -> Self {
match response {
WorkerResponse::ChainStorage(key, value, proof) => StorageEntry { key, value, proof },
WorkerResponse::LatestParentchainHeaderUnverified(_) => StorageEntry::default(),
_ => StorageEntry::default(),
}
}
}
Expand Down
2 changes: 2 additions & 0 deletions enclave-runtime/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
*/

use derive_more::From;
use itp_types::parentchain::ParentchainId;
use sgx_types::{sgx_quote3_error_t, sgx_status_t};
use std::{boxed::Box, result::Result as StdResult, string::String};

Expand Down Expand Up @@ -53,6 +54,7 @@ pub enum Error {
Attestation(itp_attestation_handler::error::Error),
Metadata(itp_node_api_metadata::error::Error),
BufferError(itp_utils::buffer::BufferError),
NonceUpdateFailed(ParentchainId),
Other(Box<dyn std::error::Error>),
}

Expand Down
10 changes: 9 additions & 1 deletion enclave-runtime/src/top_pool_execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ use crate::{
get_triggered_dispatcher_from_target_b_solo_or_parachain,
get_validator_accessor_from_integritee_solo_or_parachain,
get_validator_accessor_from_target_a_solo_or_parachain,
get_validator_accessor_from_target_b_solo_or_parachain,
get_validator_accessor_from_target_b_solo_or_parachain, update_nonce_cache,
},
};
use codec::Encode;
Expand Down Expand Up @@ -198,6 +198,14 @@ fn execute_top_pool_trusted_calls_internal() -> Result<()> {

let authority = GLOBAL_SIGNING_KEY_REPOSITORY_COMPONENT.get()?.retrieve_key()?;

update_nonce_cache(authority.public().into(), ParentchainId::Integritee)?;
if maybe_target_a_parentchain_import_dispatcher.is_some() {
update_nonce_cache(authority.public().into(), ParentchainId::TargetA)?;
}
if maybe_target_b_parentchain_import_dispatcher.is_some() {
update_nonce_cache(authority.public().into(), ParentchainId::TargetB)?;
}

match yield_next_slot(
slot_beginning_timestamp,
SLOT_DURATION,
Expand Down
38 changes: 34 additions & 4 deletions enclave-runtime/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,11 @@ use crate::{
IntegriteeParentchainTriggeredBlockImportDispatcher,
TargetAParentchainTriggeredBlockImportDispatcher,
TargetBParentchainTriggeredBlockImportDispatcher,
GLOBAL_INTEGRITEE_PARACHAIN_HANDLER_COMPONENT,
GLOBAL_INTEGRITEE_SOLOCHAIN_HANDLER_COMPONENT, GLOBAL_TARGET_A_PARACHAIN_HANDLER_COMPONENT,
GLOBAL_INTEGRITEE_PARACHAIN_HANDLER_COMPONENT, GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE,
GLOBAL_INTEGRITEE_SOLOCHAIN_HANDLER_COMPONENT, GLOBAL_OCALL_API_COMPONENT,
GLOBAL_TARGET_A_PARACHAIN_HANDLER_COMPONENT, GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE,
GLOBAL_TARGET_A_SOLOCHAIN_HANDLER_COMPONENT, GLOBAL_TARGET_B_PARACHAIN_HANDLER_COMPONENT,
GLOBAL_TARGET_B_SOLOCHAIN_HANDLER_COMPONENT,
GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE, GLOBAL_TARGET_B_SOLOCHAIN_HANDLER_COMPONENT,
},
ocall::OcallApi,
};
Expand All @@ -34,9 +35,10 @@ use codec::{Decode, Input};
use ita_stf::ParentchainHeader;
use itc_parentchain_block_import_dispatcher::BlockImportDispatcher;
use itp_component_container::ComponentGetter;
use itp_nonce_cache::{MutateNonce, Nonce};
use itp_ocall_api::EnclaveOnChainOCallApi;
use itp_types::{
parentchain::{GenericMortality, ParentchainId},
parentchain::{AccountId, GenericMortality, ParentchainId},
WorkerRequest, WorkerResponse,
};
use log::*;
Expand Down Expand Up @@ -326,3 +328,31 @@ pub(crate) fn try_mortality(blocks_to_live: u64, ocall_api: &OcallApi) -> Generi
GenericMortality::immortal()
}
}

/// fetch latest nonce and update nonce cache, considering the tx pool
pub(crate) fn update_nonce_cache(
enclave_account: AccountId,
parentchain_id: ParentchainId,
) -> Result<()> {
let ocall_api = GLOBAL_OCALL_API_COMPONENT.get()?;
let mut nonce_lock = match parentchain_id {
ParentchainId::Integritee => GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE.load_for_mutation(),
ParentchainId::TargetA => GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE.load_for_mutation(),
ParentchainId::TargetB => GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE.load_for_mutation(),
}
.map_err(|_| Error::NonceUpdateFailed(parentchain_id))?;

if let WorkerResponse::NextNonce(Some(nonce)) = ocall_api
.worker_request::<ParentchainHeader, Vec<u8>>(
[WorkerRequest::NextNonceFor(enclave_account)].into(),
&parentchain_id,
)?
.first()
.ok_or_else(|| Error::NonceUpdateFailed(parentchain_id))?
{
*nonce_lock = Nonce(*nonce);
debug!("updated nonce cache from rpc for {:?} to {}", parentchain_id, *nonce);
return Ok(())
}
Err(Error::NonceUpdateFailed(parentchain_id))
}
8 changes: 6 additions & 2 deletions service/src/ocall_bridge/worker_on_chain_ocall.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use crate::ocall_bridge::bridge_api::{OCallBridgeError, OCallBridgeResult, Worke
use chrono::Local;
use codec::{Decode, Encode};
use itp_api_client_types::ParentchainApi;
use itp_node_api::node_api_factory::CreateNodeApi;
use itp_node_api::{api_client::AccountApi, node_api_factory::CreateNodeApi};
use itp_types::{
parentchain::{Header as ParentchainHeader, ParentchainId},
DigestItem, WorkerRequest, WorkerResponse,
Expand All @@ -38,7 +38,7 @@ use std::{
use substrate_api_client::{
ac_primitives,
ac_primitives::{serde_impls::StorageKey, SubstrateHeader},
GetChainInfo, GetStorage, SubmitAndWatch, SubmitExtrinsic, XtStatus,
GetAccountInformation, GetChainInfo, GetStorage, SubmitAndWatch, SubmitExtrinsic, XtStatus,
};

pub struct WorkerOnChainOCall<F> {
Expand Down Expand Up @@ -129,6 +129,10 @@ where
ParentchainHeader::decode(&mut header.encode().as_slice()).unwrap(),
)
},
WorkerRequest::NextNonceFor(account) => {
let nonce = api.get_system_account_next_index(account).ok();
WorkerResponse::NextNonce(nonce)
},
})
.collect();

Expand Down

0 comments on commit 7cfeaa5

Please sign in to comment.