Skip to content

Commit

Permalink
x = sha256(sha256(blob), kzg_commit(blob))
Browse files Browse the repository at this point in the history
sha256(blob) -- inside
kzg_commit(blob) -- ouside
sha256(sha256(blob), kzg_commit(blob)) -- inside -> PI
  • Loading branch information
CeciliaZ030 committed Jun 24, 2024
1 parent 886b04b commit 7ae6319
Show file tree
Hide file tree
Showing 13 changed files with 148 additions and 134 deletions.
34 changes: 11 additions & 23 deletions core/src/interfaces.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,45 +125,33 @@ impl ProofType {
pub async fn run_prover(
&self,
input: GuestInput,
output: &mut GuestOutput,
output: &GuestOutput,
config: &Value,
) -> RaikoResult<Proof> {
match self {
ProofType::Native => NativeProver::run(input, output, config)
.await
.map_err(|e| e.into()),
ProofType::Sp1 => {

#[cfg(feature = "sp1")]
{
output.proof_of_equivalence = proof_of_equivalence(input);
return sp1_driver::Sp1Prover::run(input, output, config)
.await
.map_err(|e| e.into());
}
#[cfg(not(feature = "sp1"))]
return sp1_driver::Sp1Prover::run(input, output, config)
.await
.map_err(|e| e.into());
Err(RaikoError::FeatureNotSupportedError(self.clone()))
}
ProofType::Risc0 => {
#[cfg(feature = "risc0")]
{
output.proof_of_equivalence = proof_of_equivalence(input);
return risc0_driver::Risc0Prover::run(input, output, config)
.await
.map_err(|e| e.into());
}
#[cfg(not(feature = "risc0"))]
return risc0_driver::Risc0Prover::run(input, output, config)
.await
.map_err(|e| e.into());
Err(RaikoError::FeatureNotSupportedError(self.clone()))
}
ProofType::Sgx => {
#[cfg(feature = "sgx")]
{
// Sgx guest runs proof_of_version_hash
output.proof_of_equivalence = None;
return sgx_prover::SgxProver::run(input, output, config)
.await
.map_err(|e| e.into());
}
#[cfg(not(feature = "sgx"))]
return sgx_prover::SgxProver::run(input, output, config)
.await
.map_err(|e| e.into());
Err(RaikoError::FeatureNotSupportedError(self.clone()))
}
}
Expand Down
3 changes: 0 additions & 3 deletions core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,12 +118,9 @@ impl Raiko {
&input.block_hash_reference,
"block hash unexpected",
)?;

// proof_of_equivalence is generated depending on prover type
let output = GuestOutput {
header,
hash: pi,
proof_of_equivalence: None,
};

Ok(output)
Expand Down
6 changes: 3 additions & 3 deletions core/src/preflight.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ async fn prepare_taiko_chain_input(
.await?;

// Fetch the tx data from either calldata or blobdata
let (tx_data, tx_blob_hash, kzg_settings) = if proposal_event.meta.blobUsed {
let (tx_data, blob_commitment, kzg_settings) = if proposal_event.meta.blobUsed {
debug!("blob active");
// Get the blob hashes attached to the propose tx
let blob_hashes = proposal_tx.blob_versioned_hashes.unwrap_or_default();
Expand All @@ -298,7 +298,7 @@ async fn prepare_taiko_chain_input(
eip4844::get_kzg_proof_commitment(&blob, &kzg_settings).map_err(|e| anyhow!(e))?;
set_commitment_proof(&proof, &commitment).map_err(|e| anyhow!(e))?;

(blob, Some(blob_hash), Some(kzg_settings))
(blob, Some(commitment), Some(kzg_settings))
} else {
// Get the tx list data directly from the propose transaction data
let proposal_call = proposeBlockCall::abi_decode(&proposal_tx.input, false)
Expand All @@ -324,7 +324,7 @@ async fn prepare_taiko_chain_input(
l1_header: to_header(&l1_state_block.header),
tx_data,
anchor_tx: serde_json::to_string(&anchor_tx).map_err(RaikoError::Serde)?,
tx_blob_hash,
blob_commitment,
kzg_settings,
block_proposed: proposal_event,
prover_data,
Expand Down
17 changes: 7 additions & 10 deletions lib/src/builder/execute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,16 +177,13 @@ impl TxExecStrategy for TkoTxExecStrategy {
let num_transactions = transactions.len();
for (tx_no, tx) in take(&mut transactions).into_iter().enumerate() {
if !is_optimistic {
cfg_if::cfg_if! {
if #[cfg(all(all(target_os = "zkvm", target_vendor = "succinct"), feature = "sp1-cycle-tracker"))]{
println!(
"{:?}",
&format!("\rprocessing tx {tx_no}/{num_transactions}...")
);
} else {
inplace_print(&format!("\rprocessing tx {tx_no}/{num_transactions}..."));
}
}
CycleTracker::println(|| {
println!(
"{:?}",
&format!("\rprocessing tx {tx_no}/{num_transactions}...")
);
});
inplace_print(&format!("\rprocessing tx {tx_no}/{num_transactions}..."));
} else {
trace!("\rprocessing tx {tx_no}/{num_transactions}...");
}
Expand Down
28 changes: 8 additions & 20 deletions lib/src/builder/finalize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use crate::{
primitives::{
keccak::keccak,
mpt::{MptNode, StateAccount},
},
}, CycleTracker,
};

pub trait BlockFinalizeStrategy<D>
Expand All @@ -42,12 +42,9 @@ impl BlockFinalizeStrategy<MemDb> for MemDbBlockFinalizeStrategy {
fn finalize(mut block_builder: BlockBuilder<MemDb>) -> Result<(AlloyConsensusHeader, MptNode)> {
let db: MemDb = block_builder.db.take().expect("DB not initialized");

#[cfg(feature = "sp1-cycle-tracker")]
{
let mut account_touched = 0;
let mut storage_touched = 0;
}

// "sp1-cycle-tracker" debug fields
let mut account_touched = 0;
let mut storage_touched = 0;
// apply state updates
let mut state_trie = mem::take(&mut block_builder.input.parent_state_trie);
for (address, account) in &db.accounts {
Expand All @@ -64,11 +61,7 @@ impl BlockFinalizeStrategy<MemDb> for MemDbBlockFinalizeStrategy {
state_trie.delete(&state_trie_index)?;
continue;
}

#[cfg(feature = "sp1-cycle-tracker")]
{
account_touched += 1;
}
account_touched += 1;

// otherwise, compute the updated storage root for that account
let state_storage = &account.storage;
Expand All @@ -93,11 +86,7 @@ impl BlockFinalizeStrategy<MemDb> for MemDbBlockFinalizeStrategy {
} else {
storage_trie.insert_rlp(&storage_trie_index, *value)?;
}

#[cfg(feature = "sp1-cycle-tracker")]
{
storage_touched += 1;
}
storage_touched += 1;
}

storage_trie.hash()
Expand All @@ -112,11 +101,10 @@ impl BlockFinalizeStrategy<MemDb> for MemDbBlockFinalizeStrategy {
state_trie.insert_rlp(&state_trie_index, state_account)?;
}

#[cfg(feature = "sp1-cycle-tracker")]
{
CycleTracker::println(|| {
println!("finalize Account touched {:?}", account_touched);
println!("finalize Storage touched {:?}", storage_touched);
}
});

// update result header with the new state root
let mut header = block_builder.header.take().expect("Header not initialized");
Expand Down
37 changes: 8 additions & 29 deletions lib/src/builder/initialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ use crate::{
mpt::StateAccount,
Bytes,
},
utils::HeaderHasher,
utils::HeaderHasher, CycleTracker,
};

pub trait DbInitStrategy<D>
Expand Down Expand Up @@ -62,15 +62,10 @@ impl DbInitStrategy<MemDb> for MemDbInitStrategy {
.map(|bytes| (keccak(&bytes).into(), bytes))
.collect();

#[cfg(all(
all(target_os = "zkvm", target_vendor = "succinct"),
feature = "sp1-cycle-tracker"
))]
{
let mut account_touched = 0;
let mut storage_touched = 0;
}

// "sp1-cycle-tracker" debug fields
let mut account_touched = 0;
let mut storage_touched = 0;
// Load account data into db
let mut accounts = HashMap::with_capacity(block_builder.input.parent_storage.len());
for (address, (storage_trie, slots)) in &mut block_builder.input.parent_storage {
Expand All @@ -91,13 +86,7 @@ impl DbInitStrategy<MemDb> for MemDbInitStrategy {
storage_trie.hash()
);
}
#[cfg(all(
all(target_os = "zkvm", target_vendor = "succinct"),
feature = "sp1-cycle-tracker"
))]
{
account_touched += 1;
}
account_touched += 1;

// load the corresponding code
let code_hash = state_account.code_hash;
Expand All @@ -118,13 +107,7 @@ impl DbInitStrategy<MemDb> for MemDbInitStrategy {
.get_rlp(&keccak(slot.to_be_bytes::<32>()))?
.unwrap_or_default();
storage.insert(slot, value);
#[cfg(all(
all(target_os = "zkvm", target_vendor = "succinct"),
feature = "sp1-cycle-tracker"
))]
{
storage_touched += 1;
}
storage_touched += 1;
}

let mem_account = DbAccount {
Expand All @@ -142,14 +125,10 @@ impl DbInitStrategy<MemDb> for MemDbInitStrategy {
}
guest_mem_forget(contracts);

#[cfg(all(
all(target_os = "zkvm", target_vendor = "succinct"),
feature = "sp1-cycle-tracker"
))]
{
CycleTracker::println(|| {
println!("initialize_db Account touch {account_touched:?}");
println!("initialize_db Storage touch {storage_touched:?}");
}
});

// prepare block hash history
let mut block_hashes =
Expand Down
8 changes: 4 additions & 4 deletions lib/src/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,13 @@ use anyhow::{anyhow, Result};
use revm::primitives::HashMap;
use serde::{Deserialize, Serialize};
use serde_with::serde_as;

use crate::serde_helper::option_array_48;
#[cfg(not(feature = "std"))]
use crate::no_std::*;
use crate::{
consts::ChainSpec,
primitives::{mpt::MptNode, Address, Bytes, B256, U256},
serde_with::{RlpBytes, RlpHexBytes},
serde_helper::{RlpBytes, RlpHexBytes},
};

/// Represents the state of an account's storage.
Expand Down Expand Up @@ -95,7 +95,8 @@ pub struct TaikoGuestInput {
pub anchor_tx: String,
pub block_proposed: BlockProposed,
pub prover_data: TaikoProverData,
pub tx_blob_hash: Option<B256>,
#[serde(with = "option_array_48")]
pub blob_commitment: Option<[u8; 48]>,
pub kzg_settings: Option<TaikoKzgSettings>,
pub skip_verify_blob: bool,
}
Expand All @@ -112,7 +113,6 @@ pub struct GuestOutput {
#[serde_as(as = "RlpHexBytes")]
pub header: AlloyConsensusHeader,
pub hash: B256,
pub proof_of_equivalence: Option<KzgField>,
}

sol! {
Expand Down
68 changes: 66 additions & 2 deletions lib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,14 @@ impl CycleTracker {
))]
println!("cycle-tracker-end: {self.title}");
}

pub fn println(inner: impl Fn() -> ()) {
#[cfg(all(
all(target_os = "zkvm", target_vendor = "succinct"),
feature = "sp1-cycle-tracker"
))]
inner()
}
}

pub struct Measurement {
Expand Down Expand Up @@ -206,8 +214,10 @@ where
}
}

pub mod serde_with {
use serde::{Deserialize, Deserializer, Serialize, Serializer};
pub mod serde_helper {
use core::marker::PhantomData;

use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer};
use serde_with::{DeserializeAs, SerializeAs};

use super::RlpBytes as _;
Expand Down Expand Up @@ -269,4 +279,58 @@ pub mod serde_with {
T::decode_bytes(bytes).map_err(serde::de::Error::custom)
}
}

pub mod option_array_48 {
use super::*;
use serde::{de, ser};

pub fn serialize<S>(value: &Option<[u8; 48]>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match value {
Some(arr) => arr.serialize(serializer),
None => serializer.serialize_none(),
}
}

pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<[u8; 48]>, D::Error>
where
D: Deserializer<'de>,
{
struct OptionArrayVisitor;

impl<'de> de::Visitor<'de> for OptionArrayVisitor {
type Value = Option<[u8; 48]>;

fn expecting(&self, formatter: &mut core::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("an option of a 48-byte array")
}

fn visit_none<E>(self) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(None)
}

fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
let vec = Vec::<u8>::deserialize(deserializer)?;
if vec.len() == 48 {
let mut array = [0u8; 48];
array.copy_from_slice(&vec);
Ok(Some(array))
} else {
Err(de::Error::custom("expected a 48-byte array"))
}
}
}

deserializer.deserialize_option(OptionArrayVisitor)
}
}

}
Loading

0 comments on commit 7ae6319

Please sign in to comment.