Skip to content
This repository was archived by the owner on Apr 18, 2025. It is now read-only.

Commit 6cda23f

Browse files
lispcsilathdiir
andauthored
upgrade zkevm-circuits and refactor mock_testnet.rs (#187)
* done * update * update * feat: batch proof (#191) * Add `BatchProof`. * Update agg-tests. * Fix an assert. * Add batch-proof dump. * Fix test. --------- Co-authored-by: Steven <[email protected]>
1 parent 09f24c5 commit 6cda23f

File tree

15 files changed

+289
-230
lines changed

15 files changed

+289
-230
lines changed

Cargo.lock

+10-10
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

bin/src/mock_testnet.rs

+86-108
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
1+
#![allow(dead_code)]
12
use anyhow::Result;
23
use ethers_providers::{Http, Provider};
3-
use itertools::Itertools;
44
use prover::{
55
inner::Prover,
66
utils::init_env_and_log,
77
zkevm::circuit::{
88
block_traces_to_witness_block, calculate_row_usage_of_witness_block, SuperCircuit,
9-
SUB_CIRCUIT_NAMES,
109
},
1110
};
1211
use reqwest::Url;
@@ -32,118 +31,117 @@ async fn main() {
3231
for i in setting.begin_batch..=setting.end_batch {
3332
log::info!("mock-testnet: requesting block traces of batch {i}");
3433

35-
let block_traces = match setting.prove_type {
36-
ProveType::Batch => get_traces_by_batch_api(&provider, &setting, i).await,
37-
ProveType::Block => get_traces_by_block_api(&provider, &setting, i).await,
38-
};
39-
40-
let block_traces = block_traces
41-
.unwrap_or_else(|_| panic!("mock-testnet: failed to request API with batch-{i}"));
42-
43-
if let Some(block_traces) = block_traces {
44-
let rows_only = true;
45-
let result = (|| {
46-
if rows_only {
47-
let gas_total: u64 = block_traces
48-
.iter()
49-
.map(|b| b.header.gas_used.as_u64())
50-
.sum();
51-
let witness_block = block_traces_to_witness_block(&block_traces)?;
52-
let rows = calculate_row_usage_of_witness_block(&witness_block)?;
53-
log::info!(
54-
"rows of batch {}(block range {:?} to {:?}):",
55-
i,
56-
block_traces.first().and_then(|b| b.header.number),
57-
block_traces.last().and_then(|b| b.header.number),
58-
);
59-
for (c, r) in SUB_CIRCUIT_NAMES.iter().zip_eq(rows.iter()) {
60-
log::info!("rows of {}: {}", c, r);
34+
let chunks = get_traces_by_block_api(&setting, i).await;
35+
36+
let chunks =
37+
chunks.unwrap_or_else(|_| panic!("mock-testnet: failed to request API with batch-{i}"));
38+
39+
match chunks {
40+
None => {
41+
log::info!("mock-testnet: finished to prove at batch-{i}");
42+
break;
43+
}
44+
Some(chunks) => {
45+
for chunk in chunks {
46+
let ii = chunk.index;
47+
log::info!("chunk {:?}", chunk);
48+
49+
// fetch traces
50+
let mut block_traces: Vec<BlockTrace> = vec![];
51+
for i in chunk.start_block_number..=chunk.end_block_number {
52+
log::info!("mock-testnet: requesting trace of block {i}");
53+
54+
let trace = provider
55+
.request("scroll_getBlockTraceByNumberOrHash", [format!("{i:#x}")])
56+
.await
57+
.unwrap();
58+
block_traces.push(trace);
59+
}
60+
61+
// mock prove or estimate rows
62+
let rows_only = true;
63+
let result = (|| {
64+
if rows_only {
65+
let gas_total: u64 = block_traces
66+
.iter()
67+
.map(|b| b.header.gas_used.as_u64())
68+
.sum();
69+
let witness_block = block_traces_to_witness_block(&block_traces)?;
70+
let rows = calculate_row_usage_of_witness_block(&witness_block)?;
71+
log::info!(
72+
"rows of batch {}(block range {:?} to {:?}):",
73+
i,
74+
block_traces.first().and_then(|b| b.header.number),
75+
block_traces.last().and_then(|b| b.header.number),
76+
);
77+
for r in &rows {
78+
log::info!("rows of {}: {}", r.name, r.row_num_real);
79+
}
80+
let row_num = rows.iter().map(|x| x.row_num_real).max().unwrap();
81+
log::info!(
82+
"final rows of chunk {}: row {}, gas {}, gas/row {:.2}",
83+
ii,
84+
row_num,
85+
gas_total,
86+
gas_total as f64 / row_num as f64
87+
);
88+
Ok(())
89+
} else {
90+
Prover::<SuperCircuit>::mock_prove_target_circuit_batch(&block_traces)
91+
}
92+
})();
93+
match result {
94+
Ok(_) => {
95+
log::info!(
96+
"mock-testnet: succeeded to prove {ii}th chunk inside batch {i}"
97+
)
98+
}
99+
Err(err) => log::error!(
100+
"mock-testnet: failed to prove {ii}th chunk inside batch {i}:\n{err:?}"
101+
),
61102
}
62-
let row_num = rows.iter().max().unwrap();
63-
log::info!(
64-
"final rows of batch {}: row {}, gas {}, gas/row {:.2}",
65-
i,
66-
row_num,
67-
gas_total,
68-
gas_total as f64 / *row_num as f64
69-
);
70-
Ok(())
71-
} else {
72-
Prover::<SuperCircuit>::mock_prove_target_circuit_batch(&block_traces)
73103
}
74-
})();
75-
match result {
76-
Ok(_) => log::info!("mock-testnet: succeeded to prove batch-{i}"),
77-
Err(err) => log::error!("mock-testnet: failed to prove batch-{i}:\n{err:?}"),
78104
}
79-
} else {
80-
log::info!("mock-testnet: finished to prove at batch-{i}");
81-
break;
82105
}
83106
}
84107

85108
log::info!("mock-testnet: end");
86109
}
87110

88-
/// Request block traces by API `l2_getTracesByBatchIndex`. Return None for no more batches.
89-
async fn get_traces_by_batch_api(
90-
provider: &Provider<Http>,
91-
_setting: &Setting,
92-
batch_index: i64,
93-
) -> Result<Option<Vec<BlockTrace>>> {
94-
// TODO: need to test this API.
95-
Ok(Some(
96-
provider
97-
.request("l2_getTracesByBatchIndex", [format!("{batch_index:#x}")])
98-
.await?,
99-
))
100-
}
101-
102-
/// Request block traces by API `scroll_getBlockTraceByNumberOrHash`. Return None for no more
103-
/// batches.
111+
/// Request block traces by first using rollup API to get chunk info, then fetching blocks from
112+
/// l2geth. Return None if no more batches.
104113
async fn get_traces_by_block_api(
105-
provider: &Provider<Http>,
106114
setting: &Setting,
107115
batch_index: i64,
108-
) -> Result<Option<Vec<BlockTrace>>> {
116+
) -> Result<Option<Vec<ChunkInfo>>> {
109117
let url = Url::parse_with_params(
110118
&setting.rollupscan_api_url,
111-
&[("index", batch_index.to_string())],
119+
&[("batch_index", batch_index.to_string())],
112120
)?;
113121

114122
let resp: RollupscanResponse = reqwest::get(url).await?.json().await?;
115-
116-
Ok(if let Some(batch) = resp.batch {
117-
let mut traces = vec![];
118-
for i in batch.start_block_number..=batch.end_block_number {
119-
log::info!("mock-testnet: requesting trace of block {i}");
120-
121-
let trace = provider
122-
.request("scroll_getBlockTraceByNumberOrHash", [format!("{i:#x}")])
123-
.await?;
124-
traces.push(trace);
125-
}
126-
127-
Some(traces)
128-
} else {
129-
None
130-
})
123+
log::info!("handling batch {}", resp.batch_index);
124+
Ok(resp.chunks)
131125
}
132126

133-
#[derive(Deserialize)]
127+
#[derive(Deserialize, Debug)]
134128
struct RollupscanResponse {
135-
batch: Option<RollupscanBatch>,
129+
batch_index: usize,
130+
chunks: Option<Vec<ChunkInfo>>,
136131
}
137132

138-
#[derive(Deserialize)]
139-
struct RollupscanBatch {
133+
#[derive(Deserialize, Debug)]
134+
struct ChunkInfo {
135+
index: i64,
136+
created_at: String,
137+
total_tx_num: i64,
138+
hash: String,
140139
start_block_number: i64,
141140
end_block_number: i64,
142141
}
143142

144143
#[derive(Debug)]
145144
struct Setting {
146-
prove_type: ProveType,
147145
begin_batch: i64,
148146
end_batch: i64,
149147
l2geth_api_url: String,
@@ -154,13 +152,9 @@ impl Setting {
154152
pub fn new() -> Self {
155153
let l2geth_api_url =
156154
env::var("L2GETH_API_URL").expect("mock-testnet: Must set env L2GETH_API_URL");
157-
let prove_type = env::var("PROVE_TYPE").ok().unwrap_or_default().into();
158155
let rollupscan_api_url = env::var("ROLLUPSCAN_API_URL");
159-
let rollupscan_api_url = match prove_type {
160-
ProveType::Batch => rollupscan_api_url.unwrap_or_default(),
161-
ProveType::Block => rollupscan_api_url
162-
.expect("mock-testnet: Must set env ROLLUPSCAN_API_URL for block type"),
163-
};
156+
let rollupscan_api_url =
157+
rollupscan_api_url.unwrap_or_else(|_| "http://10.0.3.119:8560/api/chunks".to_string());
164158
let begin_batch = env::var("PROVE_BEGIN_BATCH")
165159
.ok()
166160
.and_then(|n| n.parse().ok())
@@ -171,26 +165,10 @@ impl Setting {
171165
.unwrap_or(DEFAULT_END_BATCH);
172166

173167
Self {
174-
prove_type,
175168
begin_batch,
176169
end_batch,
177170
l2geth_api_url,
178171
rollupscan_api_url,
179172
}
180173
}
181174
}
182-
183-
#[derive(Debug)]
184-
enum ProveType {
185-
Batch,
186-
Block,
187-
}
188-
189-
impl From<String> for ProveType {
190-
fn from(s: String) -> Self {
191-
match s.as_str() {
192-
"batch" => Self::Batch,
193-
_ => Self::Block,
194-
}
195-
}
196-
}

prover/src/aggregator/prover.rs

+5-4
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use crate::{
22
common,
33
config::{AGG_DEGREES, LAYER3_DEGREE, LAYER4_DEGREE},
44
zkevm::circuit::storage_trace_to_padding_witness_block,
5-
ChunkProof, Proof,
5+
BatchProof, ChunkProof,
66
};
77
use aggregator::{ChunkHash, MAX_AGG_SNARKS};
88
use anyhow::Result;
@@ -32,7 +32,7 @@ impl Prover {
3232
chunk_hashes_proofs: Vec<(ChunkHash, ChunkProof)>,
3333
name: Option<&str>,
3434
output_dir: Option<&str>,
35-
) -> Result<Proof> {
35+
) -> Result<BatchProof> {
3636
let name = name.map_or_else(
3737
|| {
3838
chunk_hashes_proofs
@@ -60,11 +60,12 @@ impl Prover {
6060
)?;
6161
log::info!("Got final compression thin EVM proof (layer-4): {name}");
6262

63+
let batch_proof = BatchProof::from(evm_proof.proof);
6364
if let Some(output_dir) = output_dir {
64-
evm_proof.dump(output_dir, "agg")?;
65+
batch_proof.dump(output_dir, "agg")?;
6566
}
6667

67-
Ok(evm_proof.proof)
68+
Ok(batch_proof)
6869
}
6970

7071
// Generate previous snark before the final one.

prover/src/aggregator/verifier.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use crate::{common, config::LAYER4_DEGREE, io::read_all, utils::read_env_var, Proof};
1+
use crate::{common, config::LAYER4_DEGREE, io::read_all, utils::read_env_var, BatchProof};
22
use aggregator::CompressionCircuit;
33
use halo2_proofs::{
44
halo2curves::bn256::{Bn256, G1Affine},
@@ -53,8 +53,8 @@ impl Verifier {
5353
}
5454
}
5555

56-
pub fn verify_agg_evm_proof(&self, proof: &Proof) -> bool {
56+
pub fn verify_agg_evm_proof(&self, batch_proof: BatchProof) -> bool {
5757
self.inner
58-
.verify_evm_proof(self.deployment_code.clone(), proof)
58+
.verify_evm_proof(self.deployment_code.clone(), &batch_proof.proof_to_verify())
5959
}
6060
}

0 commit comments

Comments
 (0)