Skip to content

Commit

Permalink
Merge branch 'dev' into 1861-vc-ids
Browse files Browse the repository at this point in the history
  • Loading branch information
kziemianek committed Aug 4, 2023
2 parents 4cd3ef1 + 9b4168f commit c3f1d24
Show file tree
Hide file tree
Showing 7 changed files with 50 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,8 @@ impl<Block: ParentchainBlockTrait, OcallApi: EnclaveOnChainOCallApi>
}

// A valid grandpa proof proves finalization of all previous unjustified blocks.
relay.header_hashes.append(&mut relay.unjustified_headers);
relay.header_hashes.push(header.hash());
relay.justify_headers();
relay.push_header_hash(header.hash());

relay.set_last_finalized_block_header(header);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,7 @@ where
}

fn genesis_hash(&self) -> Result<HashFor<Block>, Error> {
let relay = self.get_relay();
let hash = relay.header_hashes.get(0).ok_or(Error::NoGenesis)?;
Ok(*hash)
Ok(self.get_relay().genesis_hash)
}

fn latest_finalized_header(&self) -> Result<Block::Header, Error> {
Expand Down
40 changes: 34 additions & 6 deletions tee-worker/core/parentchain/light-client/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,33 +21,61 @@ use sp_runtime::{
traits::{Block as BlockT, Header as HeaderT},
OpaqueExtrinsic,
};
use std::{fmt, vec::Vec};
use std::{collections::VecDeque, fmt, vec::Vec};

/// Defines the amount of parentchain headers to keep.
pub const PARENTCHAIN_HEADER_PRUNING: u64 = 1000;

#[derive(Encode, Decode, Clone, PartialEq)]
pub struct RelayState<Block: BlockT> {
pub genesis_hash: Block::Hash,
pub last_finalized_block_header: Block::Header,
pub penultimate_finalized_block_header: Block::Header,
pub current_validator_set: AuthorityList,
pub current_validator_set_id: SetId,
pub header_hashes: Vec<Block::Hash>,
header_hashes: VecDeque<Block::Hash>,
pub unjustified_headers: Vec<Block::Hash>, // Finalized headers without grandpa proof
pub verify_tx_inclusion: Vec<OpaqueExtrinsic>, // Transactions sent by the relay
pub scheduled_change: Option<ScheduledChangeAtBlock<Block::Header>>, // Scheduled Authorities change as indicated in the header's digest.
}

impl<Block: BlockT> RelayState<Block> {
pub fn push_header_hash(&mut self, header: Block::Hash) {
self.header_hashes.push_back(header);

if self.header_hashes.len() > PARENTCHAIN_HEADER_PRUNING as usize {
self.header_hashes.pop_front().expect("Tested above that is not empty; qed");
}
}

pub fn justify_headers(&mut self) {
self.header_hashes.extend(&mut self.unjustified_headers.iter());
self.unjustified_headers.clear();

while self.header_hashes.len() > PARENTCHAIN_HEADER_PRUNING as usize {
self.header_hashes.pop_front().expect("Tested above that is not empty; qed");
}
}

pub fn header_hashes(&self) -> &VecDeque<Block::Hash> {
&self.header_hashes
}
}

#[derive(Encode, Decode, Clone, PartialEq)]
pub struct ScheduledChangeAtBlock<Header: HeaderT> {
pub at_block: Header::Number,
pub next_authority_list: AuthorityList,
}

impl<Block: BlockT> RelayState<Block> {
pub fn new(block_header: Block::Header, validator_set: AuthorityList) -> Self {
pub fn new(genesis: Block::Header, validator_set: AuthorityList) -> Self {
RelayState {
header_hashes: vec![block_header.hash()],
last_finalized_block_header: block_header.clone(),
genesis_hash: genesis.hash(),
header_hashes: vec![genesis.hash()].into(),
last_finalized_block_header: genesis.clone(),
// is it bad to initialize with the same? Header trait does no implement default...
penultimate_finalized_block_header: block_header,
penultimate_finalized_block_header: genesis,
current_validator_set: validator_set,
current_validator_set_id: 0,
unjustified_headers: Vec::new(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,7 @@ where
)
})?
.format();
let payload = credential.to_json().map_err(|_| {
VCMPError::RequestVCFailed(self.req.assertion.clone(), ErrorDetail::ParseError)
})?;
debug!("Credential payload: {}", payload);
let payload = credential.issuer.mrenclave.clone();
let (enclave_account, sig) = signer.sign_vc_with_self(payload.as_bytes()).map_err(|e| {
VCMPError::RequestVCFailed(
self.req.assertion.clone(),
Expand Down
12 changes: 10 additions & 2 deletions tee-worker/sidechain/consensus/slots/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ pub trait SimpleSlotWorker<ParentchainBlock: ParentchainBlockTrait> {

let latest_parentchain_header = match self.peek_latest_parentchain_header() {
Ok(Some(peeked_header)) => peeked_header,
Ok(None) => slot_info.last_imported_parentchain_head.clone(),
Ok(None) => slot_info.last_imported_parentchain_head,
Err(e) => {
warn!(
target: logging_target,
Expand Down Expand Up @@ -321,15 +321,23 @@ pub trait SimpleSlotWorker<ParentchainBlock: ParentchainBlockTrait> {
},
};

// TODO(Kai@litentry): comment out the time slot check for now
// It's an audacious change: it means we'll always produce a block once proposed, even though it comes late.
// The rationale is we are having one-worker set-up, with this single block author, it's more important to produce
// a block with stf update at all than producing "timely" blocks. We don't have a sync or slot-scheduling issue.
//
// We meed more tests to tell if it can be applied to multiple workers (e.g. in CI) - it might create forks.
/*
if !timestamp_within_slot(&slot_info, &proposing.block) {
warn!(
target: logging_target,
"⌛️ Discarding proposal for slot {}, block number {}; block production took too long",
"⌛️ Discarding proposal for slot {}, block number {}; block production took too long",
*slot, proposing.block.block().header().block_number(),
);
return None
}
*/

if last_imported_header.is_some() {
println!(
Expand Down
1 change: 1 addition & 0 deletions tee-worker/sidechain/consensus/slots/src/slots.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ pub fn slot_ends_at(slot: Slot, slot_duration: Duration) -> Duration {
Duration::from_millis(*slot.saturating_add(1u64) * (slot_duration.as_millis() as u64))
}

#[allow(dead_code)]
pub(crate) fn timestamp_within_slot<
ParentchainBlock: ParentchainBlockTrait,
SignedSidechainBlock: SignedSidechainBlockTrait,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -230,9 +230,8 @@ export async function verifySignature(data: any, index: HexString, proofJson: an
const res = (await api.query.teerex.enclaveRegistry(count)).toHuman() as EnclaveResult;
// Check vc index
expect(index).to.be.eq(data.id);

const signature = Buffer.from(hexToU8a(`0x${proofJson.proofValue}`));
const message = Buffer.from(JSON.stringify(data));
const message = Buffer.from(data.issuer.mrenclave);
const vcPubkey = Buffer.from(hexToU8a(`${res.vcPubkey}`));

const isValid = await ed.verify(signature, message, vcPubkey);
Expand Down

0 comments on commit c3f1d24

Please sign in to comment.