Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor block_convert #2

Merged
merged 2 commits into from
Mar 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 58 additions & 2 deletions zkevm-circuits/src/blob_circuit.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use ethers_core::types::TxpoolStatus;
use halo2_base::{
Context,
utils::{
Expand All @@ -13,8 +14,7 @@ use halo2_proofs::{

use bls12_381::{Scalar as Fp};
use itertools::Itertools;
use crate::{util::{SubCircuit, Challenges, SubCircuitConfig}, witness::{Block,CircuitBlob}};

use crate::{util::{SubCircuit, Challenges, SubCircuitConfig}, witness::{Block, Transaction, CircuitBlob}};
use std::{io::Read, marker::PhantomData};
use eth_types::{Field, ToBigEndian, ToLittleEndian, ToScalar, H256};

Expand Down Expand Up @@ -74,6 +74,22 @@ impl<F: Field> BlobCircuit<F> {
_marker: PhantomData::default(),
}
}

pub fn partial_blob(txs: &Vec<Transaction>) -> Vec<Fp> {
match block_to_blob(txs) {
Ok(blob) => {
let mut result: Vec<Fp> = Vec::new();
for chunk in blob.chunks(32) {
let reverse: Vec<u8> = chunk.iter().rev().cloned().collect();
result.push(Fp::from_bytes(reverse.as_slice().try_into().unwrap()).unwrap());
}
log::trace!("partial blob: {:?}", result);
result

}
Err(_) => Vec::new(),
}
}
}


Expand Down Expand Up @@ -412,3 +428,43 @@ impl<F: Field> SubCircuit<F> for BlobCircuit<F>{
}
}


const MAX_BLOB_DATA_SIZE: usize = 4096 * 31 - 4;

pub fn block_to_blob(txs: &Vec<Transaction>) -> Result<Vec<u8>, String> {
// get data from block.txs.rlp_signed
let data: Vec<u8> = txs
.iter()
.flat_map(|tx| &tx.rlp_signed)
.cloned()
.collect();

if data.len() > MAX_BLOB_DATA_SIZE {
return Err(format!("data is too large for blob. len={}", data.len()));
}

let mut result:Vec<u8> = vec![];

result.push(0);
result.extend_from_slice(&(data.len() as u32).to_le_bytes());
let offset = std::cmp::min(27, data.len());
result.extend_from_slice(&data[..offset]);

if data.len() <= 27 {
for _ in 0..(27 - data.len()) {
result.push(0);
}
return Ok(result);
}

for chunk in data[27..].chunks(31) {
let len = std::cmp::min(31, chunk.len());
result.push(0);
result.extend_from_slice(&chunk[..len]);
for _ in 0..(31 - len) {
result.push(0);
}
}

Ok(result)
}
62 changes: 40 additions & 22 deletions zkevm-circuits/src/witness/block.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
use bls12_381::Fp;
use bls12_381::Scalar as Fp;
use ethers_core::types::Signature;
use std::{
collections::{BTreeMap, HashMap},
io::Write,
ptr::null,
};

#[cfg(any(feature = "test", test))]
use crate::evm_circuit::{detect_fixed_table_tags, EvmCircuit};

use crate::{
blob_circuit::{
block_to_blob,
util::{poly_eval_partial, FP_S},
},
evm_circuit::util::rlc,
table::{BlockContextFieldTag, RwTableTag},
util::SubCircuit,
Expand All @@ -22,14 +24,16 @@ use bus_mapping::{
Error,
};
use eth_types::{sign_types::SignData, Address, Field, ToLittleEndian, ToScalar, Word, U256};
use halo2_proofs::circuit::Value;
use halo2_proofs::{circuit::Value, halo2curves::FieldExt};
use itertools::Itertools;

use super::{
blob::BlockBlob, mpt::ZktrieState as MptState, step::step_convert, tx::tx_convert, Bytecode, CircuitBlob, ExecStep, MptUpdates, RwMap, Transaction
};
use crate::util::Challenges;

const BLOB_DATA_SIZE: usize = 4096 * 32;

// TODO: Remove fields that are duplicated in`eth_block`
/// Block is the struct used by all circuits, which contains all the needed
/// data for witness generation.
Expand Down Expand Up @@ -522,23 +526,41 @@ pub fn block_convert<F: Field>(
log::error!("withdraw root is not avaliable");
}

let txs = block
.txs()
.iter()
.enumerate()
.map(|(idx, tx)| {
let next_block_num = if idx + 1 < num_txs {
block.txs()[idx + 1].block_num
} else {
last_block_num + 1
};
tx_convert(tx, idx + 1, chain_id, next_block_num)
})
.collect();

let omega = Fp::from(123).pow(&[(FP_S - 12) as u64, 0, 0, 0]);
let mut batch_blob = [0u8; BLOB_DATA_SIZE];
let partial_result_bytes = block_to_blob(&txs).unwrap();
batch_blob[0..partial_result_bytes.len()].copy_from_slice(&partial_result_bytes);

let challenge_point = U256::from(1);

let mut result: Vec<Fp> = Vec::new();
for chunk in partial_result_bytes.chunks(32) {
let reverse: Vec<u8> = chunk.iter().rev().cloned().collect();
result.push(Fp::from_bytes(reverse.as_slice().try_into().unwrap()).unwrap());
}

let partial_result =
U256::from(poly_eval_partial(result, Fp::from_u128(1), omega, 0).to_bytes());

Ok(Block {
_marker: Default::default(),
context: block.into(),
rws,
txs: block
.txs()
.iter()
.enumerate()
.map(|(idx, tx)| {
let next_block_num = if idx + 1 < num_txs {
block.txs()[idx + 1].block_num
} else {
last_block_num + 1
};
tx_convert(tx, idx + 1, chain_id, next_block_num)
})
.collect(),
txs: txs,
sigs: block.txs().iter().map(|tx| tx.signature).collect(),
end_block_not_last,
end_block_last,
Expand Down Expand Up @@ -572,10 +594,6 @@ pub fn block_convert<F: Field>(
start_l1_queue_index: block.start_l1_queue_index,
precompile_events: block.precompile_events.clone(),
blob: BlockBlob::default(),
// batch_commit: Word::zero(),
// challenge_point: Word::zero(),
// index: 0,
// partial_result: Word::zero(),
})
}

Expand All @@ -597,4 +615,4 @@ pub fn block_convert_with_l1_queue_index<F: Field>(
/// Attach witness block with mpt states
pub fn block_apply_mpt_state<F: Field>(block: &mut Block<F>, mpt_state: &MptState) {
block.mpt_updates.fill_state_roots(mpt_state);
}
}
Loading