feat(tee-key-preexec): add support for Solidity-compatible pubkey in report_data

This PR is part of the effort to implement on-chain TEE proof
verification. This PR goes hand in hand with https://github.com/matter-labs/zksync-era/pull/3414.
This commit is contained in:
Patryk Bęza 2024-12-20 12:19:19 +01:00
parent e5cca31ac0
commit 2d04ba0508
No known key found for this signature in database
GPG key ID: 9AD1B44D9F6258EC
13 changed files with 828 additions and 43 deletions

View file

@ -12,6 +12,7 @@ repository.workspace = true
[dependencies]
anyhow.workspace = true
clap.workspace = true
hex.workspace = true
rand.workspace = true
secp256k1.workspace = true
teepot.workspace = true

View file

@ -8,9 +8,12 @@
use anyhow::{Context, Result};
use clap::Parser;
use secp256k1::{rand, Keypair, PublicKey, Secp256k1, SecretKey};
use core::convert::AsRef;
use secp256k1::{rand, Secp256k1};
use std::{ffi::OsString, os::unix::process::CommandExt, process::Command};
use teepot::quote::get_quote;
use teepot::{
ethereum::public_key_to_ethereum_address, prover::reportdata::ReportDataV1, quote::get_quote,
};
use tracing::error;
use tracing_log::LogTracer;
use tracing_subscriber::{fmt, prelude::*, EnvFilter, Registry};
@ -37,14 +40,13 @@ fn main_with_error() -> Result<()> {
tracing::subscriber::set_global_default(subscriber).context("Failed to set logger")?;
let args = Args::parse();
let mut rng = rand::thread_rng();
let secp = Secp256k1::new();
let keypair = Keypair::new(&secp, &mut rng);
let signing_key = SecretKey::from_keypair(&keypair);
let verifying_key = PublicKey::from_keypair(&keypair);
let verifying_key_bytes = verifying_key.serialize();
let tee_type = match get_quote(verifying_key_bytes.as_ref()) {
let (signing_key, verifying_key) = secp.generate_keypair(&mut rng);
let ethereum_address = public_key_to_ethereum_address(&verifying_key);
let report_data = ReportDataV1 { ethereum_address };
let report_data_bytes: [u8; 64] = report_data.into();
let tee_type = match get_quote(report_data_bytes.as_ref()) {
Ok((tee_type, quote)) => {
// save quote to file
std::fs::write(TEE_QUOTE_FILE, quote)?;
@ -85,3 +87,24 @@ fn main() -> Result<()> {
}
ret
}
#[cfg(test)]
mod tests {
use secp256k1::{PublicKey, Secp256k1, SecretKey};
use super::*;
#[test]
fn test_public_key_to_address() {
let secp = Secp256k1::new();
let secret_key_bytes =
hex::decode("c87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3")
.unwrap();
let secret_key = SecretKey::from_slice(&secret_key_bytes).unwrap();
let public_key = PublicKey::from_secret_key(&secp, &secret_key);
let expected_address = hex::decode("627306090abaB3A6e1400e9345bC60c78a8BEf57").unwrap();
let address = public_key_to_ethereum_address(&public_key);
assert_eq!(address, expected_address.as_slice());
}
}

View file

@ -12,5 +12,6 @@ anyhow.workspace = true
clap.workspace = true
hex.workspace = true
secp256k1.workspace = true
sha3.workspace = true
teepot.workspace = true
zksync_basic_types.workspace = true

View file

@ -5,10 +5,13 @@
use anyhow::{Context, Result};
use clap::{Args, Parser, Subcommand};
use secp256k1::{ecdsa::Signature, Message, PublicKey};
use core::convert::TryInto;
use hex::encode;
use secp256k1::{Message, PublicKey};
use std::{fs, io::Read, path::PathBuf, str::FromStr, time::UNIX_EPOCH};
use teepot::{
client::TcbLevel,
ethereum::recover_signer,
quote::{error, tee_qv_get_collateral, verify_quote_with_collateral, QuoteVerificationResult},
};
use zksync_basic_types::H256;
@ -87,14 +90,25 @@ fn verify_signature(
let reportdata = &quote_verification_result.quote.get_report_data();
let public_key = PublicKey::from_slice(reportdata)?;
println!("Public key from attestation quote: {}", public_key);
let signature_bytes = fs::read(&signature_args.signature_file)?;
let signature = Signature::from_compact(&signature_bytes)?;
let root_hash_msg = Message::from_digest_slice(&signature_args.root_hash.0)?;
if signature.verify(&root_hash_msg, &public_key).is_ok() {
println!("Signature verified successfully");
} else {
println!("Failed to verify signature");
}
let signature_bytes: &[u8] = &fs::read(&signature_args.signature_file)?;
let ethereum_address_from_quote = &quote_verification_result.quote.get_report_data()[..20];
let root_hash_bytes = signature_args.root_hash.as_bytes();
let root_hash_msg = Message::from_digest_slice(root_hash_bytes)?;
let ethereum_address_from_signature =
recover_signer(&signature_bytes.try_into()?, &root_hash_msg)?;
let verification_successful = ethereum_address_from_signature == ethereum_address_from_quote;
println!(
"Signature '{}' {}. Ethereum address from attestation quote: {}. Ethereum address from signature: {}.",
encode(signature_bytes),
if verification_successful {
"verified successfully"
} else {
"verification failed"
},
encode(ethereum_address_from_quote),
encode(ethereum_address_from_signature)
);
Ok(())
}

View file

@ -2,11 +2,13 @@
// Copyright (c) 2023-2024 Matter Labs
use crate::{args::AttestationPolicyArgs, client::JsonRpcClient};
use anyhow::{Context, Result};
use anyhow::{anyhow, Context, Result};
use hex::encode;
use secp256k1::{constants::PUBLIC_KEY_SIZE, ecdsa::Signature, Message, PublicKey};
use secp256k1::{ecdsa::Signature, Message};
use teepot::{
client::TcbLevel,
ethereum::recover_signer,
prover::reportdata::ReportData,
quote::{
error::QuoteContext, tee_qv_get_collateral, verify_quote_with_collateral,
QuoteVerificationResult, Report,
@ -15,6 +17,51 @@ use teepot::{
use tracing::{debug, info, warn};
use zksync_basic_types::{L1BatchNumber, H256};
struct TeeProof {
report: ReportData,
root_hash: H256,
signature: Vec<u8>,
}
impl TeeProof {
pub fn new(report: ReportData, root_hash: H256, signature: Vec<u8>) -> Self {
Self {
report,
root_hash,
signature,
}
}
pub fn verify(&self) -> Result<bool> {
match &self.report {
ReportData::V0(report) => {
let signature = Signature::from_compact(&self.signature)?;
let root_hash_msg = Message::from_digest_slice(&self.root_hash.0)?;
Ok(signature.verify(&root_hash_msg, &report.pubkey).is_ok())
}
ReportData::V1(report) => {
let ethereum_address_from_report = report.ethereum_address;
let root_hash_msg = Message::from_digest_slice(self.root_hash.as_bytes())?;
let signature_bytes: [u8; 65] = self
.signature
.clone()
.try_into()
.map_err(|e| anyhow!("{:?}", e))?;
let ethereum_address_from_signature =
recover_signer(&signature_bytes, &root_hash_msg)?;
debug!(
"Root hash: {}. Ethereum address from the attestation quote: {}. Ethereum address from the signature: {}.",
self.root_hash,
encode(ethereum_address_from_report),
encode(ethereum_address_from_signature),
);
Ok(ethereum_address_from_signature == ethereum_address_from_report)
}
ReportData::Unknown(_) => Ok(false),
}
}
}
pub async fn verify_batch_proof(
quote_verification_result: &QuoteVerificationResult,
attestation_policy: &AttestationPolicyArgs,
@ -26,23 +73,12 @@ pub async fn verify_batch_proof(
return Ok(false);
}
let batch_no = batch_number.0;
let public_key = PublicKey::from_slice(
&quote_verification_result.quote.get_report_data()[..PUBLIC_KEY_SIZE],
)?;
debug!(batch_no, "public key: {}", public_key);
let root_hash = node_client.get_root_hash(batch_number).await?;
debug!(batch_no, "root hash: {}", root_hash);
let is_verified = verify_signature(signature, public_key, root_hash)?;
if is_verified {
info!(batch_no, signature = %encode(signature), "Signature verified successfully.");
} else {
warn!(batch_no, signature = %encode(signature), "Failed to verify signature!");
}
Ok(is_verified)
let report_data_bytes = quote_verification_result.quote.get_report_data();
let report_data = ReportData::try_from(report_data_bytes)?;
let tee_proof = TeeProof::new(report_data, root_hash, signature.to_vec());
let verification_successful = tee_proof.verify().is_ok();
Ok(verification_successful)
}
pub fn verify_attestation_quote(attestation_quote_bytes: &[u8]) -> Result<QuoteVerificationResult> {
@ -85,12 +121,6 @@ pub fn log_quote_verification_summary(quote_verification_result: &QuoteVerificat
);
}
fn verify_signature(signature: &[u8], public_key: PublicKey, root_hash: H256) -> Result<bool> {
let signature = Signature::from_compact(signature)?;
let root_hash_msg = Message::from_digest_slice(&root_hash.0)?;
Ok(signature.verify(&root_hash_msg, &public_key).is_ok())
}
fn is_quote_matching_policy(
attestation_policy: &AttestationPolicyArgs,
quote_verification_result: &QuoteVerificationResult,