Skip to content

Commit

Permalink
fix: payload (#291)
Browse files Browse the repository at this point in the history
  • Loading branch information
ytqaljn authored Jan 24, 2024
1 parent 6643468 commit d6b1a72
Show file tree
Hide file tree
Showing 6 changed files with 44 additions and 29 deletions.
4 changes: 2 additions & 2 deletions crates/cestory/api/src/proto_generated/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,14 +254,14 @@ impl crate::crpc::SetEndpointRequest {
impl crate::crpc::GetEndpointResponse {
pub fn decode_endpoint_payload(
&self,
) -> Result<Option<ces_types::WorkerEndpointPayload>, ScaleDecodeError> {
) -> Result<Option<ces_types::WorkerAction>, ScaleDecodeError> {
self.encoded_endpoint_payload
.as_ref()
.map(|v| Decode::decode(&mut &v[..]))
.transpose()
}
pub fn new(
endpoint_payload: Option<ces_types::WorkerEndpointPayload>,
endpoint_payload: Option<ces_types::WorkerAction>,
signature: Option<::prost::alloc::vec::Vec<u8>>,
) -> Self {
Self {
Expand Down
5 changes: 3 additions & 2 deletions crates/cestory/src/ceseal_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use super::*;
use crate::system::System;
use ces_crypto::{key_share, sr25519::KDF, SecretKey};
use ces_types::{
attestation::{validate as validate_attestation_report, IasFields}, messaging::EncryptedKey, wrap_content_to_sign, AttestationReport, BasePayload, ChallengeHandlerInfo, EncryptedWorkerKey, HandoverChallenge, SignedContentType, WorkerEndpointPayload, WorkerRegistrationInfo
attestation::{validate as validate_attestation_report, IasFields}, messaging::EncryptedKey, wrap_content_to_sign, AttestationReport, BasePayload, ChallengeHandlerInfo, EncryptedWorkerKey, HandoverChallenge, SignedContentType, WorkerAction, WorkerEndpointPayload, WorkerRegistrationInfo
};
use cestory_api::{
blocks::{self, StorageState},
Expand Down Expand Up @@ -934,6 +934,7 @@ impl<Platform: pal::Platform + Serialize + DeserializeOwned> Ceseal<Platform> {
let endpoint = self.endpoint.clone();
let base_payload = BasePayload { pubkey: public_key, signing_time: block_time };
let endpoint_payload = WorkerEndpointPayload { endpoint, base: base_payload };
let endpoint_payload = WorkerAction::UpdateEndpoint(endpoint_payload);
let signature = self.sign_endpoint_payload(&endpoint_payload)?;
let resp = pb::GetEndpointResponse::new(Some(endpoint_payload.clone()), Some(signature));
self.signed_endpoint = Some(resp.clone());
Expand All @@ -951,7 +952,7 @@ impl<Platform: pal::Platform + Serialize + DeserializeOwned> Ceseal<Platform> {
}
}

fn sign_endpoint_payload(&mut self, payload: &WorkerEndpointPayload) -> CesealResult<Vec<u8>> {
fn sign_endpoint_payload(&mut self, payload: &WorkerAction) -> CesealResult<Vec<u8>> {
const MAX_PAYLOAD_SIZE: usize = 512;
let data_to_sign = payload.encode();
if data_to_sign.len() > MAX_PAYLOAD_SIZE {
Expand Down
13 changes: 11 additions & 2 deletions pallets/tee-worker/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ pub mod benchmarking;

use codec::{Decode, Encode};
use frame_support::{
dispatch::DispatchResult, pallet_prelude::*, traits::ReservableCurrency, transactional, BoundedVec, PalletId,
dispatch::DispatchResult, pallet_prelude::*, traits::ReservableCurrency, BoundedVec, PalletId,
traits::{Get, StorageVersion, UnixTime},
};
pub use pallet::*;
Expand Down Expand Up @@ -46,7 +46,6 @@ pub mod pallet {
use codec::{Decode, Encode};
use frame_support::{
dispatch::DispatchResult,
Blake2_128Concat,
};
use scale_info::TypeInfo;

Expand Down Expand Up @@ -331,6 +330,16 @@ pub mod pallet {
ensure_signed(origin)?;

if let WorkerAction::Exit(payload) = payload {
ensure!(sig.len() == 64, Error::<T>::InvalidSignatureLength);
let sig =
sp_core::sr25519::Signature::try_from(sig.as_slice()).or(Err(Error::<T>::MalformedSignature))?;
let encoded_data = payload.encode();
let data_to_sign = wrap_content_to_sign(&encoded_data, SignedContentType::EndpointInfo);
ensure!(
sp_io::crypto::sr25519_verify(&sig, &data_to_sign, &payload.pubkey),
Error::<T>::InvalidSignature
);

ensure!(<Workers<T>>::count() > 1, Error::<T>::LastWorker);
ensure!(<Workers<T>>::contains_key(&payload.pubkey), Error::<T>::WorkerNotFound);

Expand Down
6 changes: 3 additions & 3 deletions standalone/chain/node/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ pub fn cess_testnet_generate_config() -> ChainSpec {
// Properties
Some(
serde_json::from_str(
"{\"tokenDecimals\": 12, \"tokenSymbol\": \"TCESS\", \"SS58Prefix\": 11330}",
"{\"tokenDecimals\": 18, \"tokenSymbol\": \"TCESS\", \"SS58Prefix\": 11330}",
)
.expect("Provided valid json map"),
),
Expand Down Expand Up @@ -395,7 +395,7 @@ pub fn cess_main() -> ChainSpec {
// Properties
Some(
serde_json::from_str(
"{\"tokenDecimals\": 12, \"tokenSymbol\": \"TCESS\", \"SS58Prefix\": 11330}",
"{\"tokenDecimals\": 18, \"tokenSymbol\": \"TCESS\", \"SS58Prefix\": 11330}",
)
.expect("Provided valid json map"),
),
Expand Down Expand Up @@ -431,7 +431,7 @@ pub fn development_config() -> ChainSpec {
// Properties
Some(
serde_json::from_str(
"{\"tokenDecimals\": 12, \"tokenSymbol\": \"TCESS\", \"SS58Prefix\": 11330}",
"{\"tokenDecimals\": 18, \"tokenSymbol\": \"TCESS\", \"SS58Prefix\": 11330}",
)
.expect("Provided valid json map"),
),
Expand Down
2 changes: 1 addition & 1 deletion standalone/chain/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ impl OnUnbalanced<NegativeImbalance> for DealWithFees {
}
}

pub const MILLICENTS: Balance = 10_000_000;
pub const MILLICENTS: Balance = 10_000_000_000_000;
pub const CENTS: Balance = 1_000 * MILLICENTS; // assume this is worth about a cent.
pub const DOLLARS: Balance = 100 * CENTS;

Expand Down
43 changes: 24 additions & 19 deletions standalone/teeworker/cifrost/src/endpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use crate::{
Args,
};
use anyhow::{anyhow, Context, Result};
use ces_types::WorkerEndpointPayload;
use ces_types::{WorkerAction};
use cestory_api::crpc::SetEndpointRequest;
use cesxt::subxt::config::polkadot::PolkadotExtrinsicParamsBuilder as Params;
use log::{error, info};
Expand Down Expand Up @@ -69,29 +69,34 @@ pub async fn try_update_worker_endpoint(
}
Some(payload) => {
// update endpoint if the public_endpoint arg changed
let former: WorkerEndpointPayload =
let former: WorkerAction =
Decode::decode(&mut &payload[..]).context("decode payload error")?;
match args.public_endpoint.clone() {
Some(endpoint) => {
if former.endpoint != Some(endpoint.clone()) || former.endpoint.is_none() {
match cc
.set_endpoint(Request::new(SetEndpointRequest::new(endpoint)))
.await
{
Ok(resp) => resp
.into_inner()
.encoded_endpoint_payload
.ok_or(anyhow!("BUG: can't be None"))?,
Err(e) => {
error!("call ceseal.set_endpoint() response error: {:?}", e);
return Ok(false);
if let WorkerAction::UpdateEndpoint(former) = former {
match args.public_endpoint.clone() {
Some(endpoint) => {
if former.endpoint != Some(endpoint.clone()) || former.endpoint.is_none() {
match cc
.set_endpoint(Request::new(SetEndpointRequest::new(endpoint)))
.await
{
Ok(resp) => resp
.into_inner()
.encoded_endpoint_payload
.ok_or(anyhow!("BUG: can't be None"))?,
Err(e) => {
error!("call ceseal.set_endpoint() response error: {:?}", e);
return Ok(false);
}
}
} else {
payload
}
} else {
payload
}
None => payload,
}
None => payload,
} else {
error!("call ceseal.set_endpoint() payload type error");
return Ok(false);
}
}
};
Expand Down

0 comments on commit d6b1a72

Please sign in to comment.