Skip to content
Closed
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
15 changes: 8 additions & 7 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ repository = "https://github.com/scroll-tech/scroll"
version = "4.5.8"

[workspace.dependencies]
scroll-zkvm-prover-euclid = { git = "https://github.com/scroll-tech/zkvm-prover", rev = "0dd7b19", package = "scroll-zkvm-prover" }
scroll-zkvm-verifier-euclid = { git = "https://github.com/scroll-tech/zkvm-prover", rev = "0dd7b19", package = "scroll-zkvm-verifier" }
scroll-zkvm-types = { git = "https://github.com/scroll-tech/zkvm-prover", rev = "0dd7b19" }
scroll-zkvm-prover-euclid = { git = "https://github.com/scroll-tech/zkvm-prover", rev = "0498edb", package = "scroll-zkvm-prover" }
scroll-zkvm-verifier-euclid = { git = "https://github.com/scroll-tech/zkvm-prover", rev = "0498edb", package = "scroll-zkvm-verifier" }
scroll-zkvm-types = { git = "https://github.com/scroll-tech/zkvm-prover", rev = "0498edb" }

sbv-primitives = { git = "https://github.com/scroll-tech/stateless-block-verifier", branch = "chore/upgrade", features = ["scroll"] }
sbv-utils = { git = "https://github.com/scroll-tech/stateless-block-verifier", branch = "chore/upgrade" }
Expand Down
43 changes: 17 additions & 26 deletions crates/libzkp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ pub use verifier::{TaskType, VerifierConfig};
mod utils;

use sbv_primitives::B256;
use scroll_zkvm_types::util::vec_as_base64;
use scroll_zkvm_types::{public_inputs::ForkName, util::vec_as_base64};
use serde::{Deserialize, Serialize};
use serde_json::value::RawValue;
use std::path::Path;
Expand All @@ -30,7 +30,7 @@ pub fn checkout_chunk_task(
pub fn gen_universal_task(
task_type: i32,
task_json: &str,
fork_name: &str,
fork_name_str: &str,
expected_vk: &[u8],
interpreter: Option<impl ChunkInterpreter>,
) -> eyre::Result<(B256, String, String)> {
Expand All @@ -48,19 +48,28 @@ pub fn gen_universal_task(

let (pi_hash, metadata, mut u_task) = match task_type {
x if x == TaskType::Chunk as i32 => {
let task = serde_json::from_str::<ChunkProvingTask>(task_json)?;
let mut task = serde_json::from_str::<ChunkProvingTask>(task_json)?;
let fork_name = ForkName::from(task.fork_name.to_lowercase().as_str());
task.fork_name = fork_name.to_string();
assert_eq!(fork_name_str, task.fork_name.as_str());
let (pi_hash, metadata, u_task) =
gen_universal_chunk_task(task, fork_name.into(), interpreter)?;
gen_universal_chunk_task(task, fork_name, interpreter)?;
(pi_hash, AnyMetaData::Chunk(metadata), u_task)
}
x if x == TaskType::Batch as i32 => {
let task = serde_json::from_str::<BatchProvingTask>(task_json)?;
let (pi_hash, metadata, u_task) = gen_universal_batch_task(task, fork_name.into())?;
let mut task = serde_json::from_str::<BatchProvingTask>(task_json)?;
let fork_name = ForkName::from(task.fork_name.to_lowercase().as_str());
task.fork_name = fork_name.to_string();
assert_eq!(fork_name_str, task.fork_name.as_str());
let (pi_hash, metadata, u_task) = gen_universal_batch_task(task, fork_name)?;
(pi_hash, AnyMetaData::Batch(metadata), u_task)
}
x if x == TaskType::Bundle as i32 => {
let task = serde_json::from_str::<BundleProvingTask>(task_json)?;
let (pi_hash, metadata, u_task) = gen_universal_bundle_task(task, fork_name.into())?;
let mut task = serde_json::from_str::<BundleProvingTask>(task_json)?;
let fork_name = ForkName::from(task.fork_name.to_lowercase().as_str());
task.fork_name = fork_name.to_string();
assert_eq!(fork_name_str, task.fork_name.as_str());
let (pi_hash, metadata, u_task) = gen_universal_bundle_task(task, fork_name)?;
(pi_hash, AnyMetaData::Bundle(metadata), u_task)
}
_ => return Err(eyre::eyre!("unrecognized task type {task_type}")),
Expand Down Expand Up @@ -111,24 +120,6 @@ pub fn verify_proof(proof: Vec<u8>, fork_name: &str, task_type: TaskType) -> eyr
let verifier = verifier::get_verifier(fork_name)?;

let ret = verifier.lock().unwrap().verify(task_type, &proof)?;

if let Ok(debug_value) = std::env::var("ZKVM_DEBUG_PROOF") {
use std::time::{SystemTime, UNIX_EPOCH};
if !ret && debug_value.to_lowercase() == "true" {
// Dump req.input to a temporary file
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let filename = format!("/tmp/proof_{}.json", timestamp);
if let Err(e) = std::fs::write(&filename, &proof) {
eprintln!("Failed to write proof to file {}: {}", filename, e);
} else {
println!("Dumped failed proof to {}", filename);
}
}
}

Ok(ret)
}

Expand Down
51 changes: 49 additions & 2 deletions crates/libzkp_c/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@ use std::sync::OnceLock;

static LOG_SETTINGS: OnceLock<Result<(), String>> = OnceLock::new();

fn enable_dump() -> bool {
static ZKVM_DEBUG_DUMP: OnceLock<bool> = OnceLock::new();
*ZKVM_DEBUG_DUMP.get_or_init(|| {
std::env::var("ZKVM_DEBUG")
.or_else(|_| std::env::var("ZKVM_DEBUG_PROOF"))
.map(|s| s.to_lowercase() == "true")
.unwrap_or(false)
})
}

/// # Safety
#[no_mangle]
pub unsafe extern "C" fn init_tracing() {
Expand Down Expand Up @@ -52,14 +62,33 @@ pub unsafe extern "C" fn init_l2geth(config: *const c_char) {

fn verify_proof(proof: *const c_char, fork_name: *const c_char, task_type: TaskType) -> c_char {
let fork_name_str = c_char_to_str(fork_name);
let proof_str = proof;
let proof = c_char_to_vec(proof);
tracing::info!("verify proof for fork {fork_name_str}, type {task_type}");

match libzkp::verify_proof(proof, fork_name_str, task_type) {
Err(e) => {
tracing::error!("{:?} verify failed, error: {:#}", task_type, e);
false as c_char
}
Ok(result) => result as c_char,
Ok(result) => {
if !result && enable_dump() {
use std::time::{SystemTime, UNIX_EPOCH};
// Dump req.input to a temporary file
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let filename = format!("/tmp/proof_{}.json", timestamp);
let cstr = unsafe { std::ffi::CStr::from_ptr(proof_str) };
if let Err(e) = std::fs::write(&filename, cstr.to_bytes()) {
eprintln!("Failed to write proof to file {}: {}", filename, e);
} else {
println!("Dumped failed proof to {}", filename);
}
}
result as c_char
}
}
Comment on lines +74 to 92
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Address potential race conditions and security concerns in debug dumping.

The debug dumping logic has several potential issues:

  1. Race condition: Using only timestamp for filename could cause collisions if multiple threads/processes call this simultaneously
  2. Security: Writing to /tmp might not be secure in all environments
  3. Portability: Hard-coded /tmp path won't work on Windows

Consider this improved implementation:

-                let filename = format!("/tmp/proof_{}.json", timestamp);
+                let filename = format!("/tmp/proof_{}_{}.json", std::process::id(), timestamp);

Or better yet, use a more robust approach:

-                let filename = format!("/tmp/proof_{}.json", timestamp);
+                let temp_dir = std::env::temp_dir();
+                let filename = temp_dir.join(format!("proof_{}_{}.json", std::process::id(), timestamp));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
Ok(result) => {
if !result && enable_dump() {
use std::time::{SystemTime, UNIX_EPOCH};
// Dump req.input to a temporary file
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let filename = format!("/tmp/proof_{}.json", timestamp);
let cstr = unsafe { std::ffi::CStr::from_ptr(proof_str) };
if let Err(e) = std::fs::write(&filename, cstr.to_bytes()) {
eprintln!("Failed to write proof to file {}: {}", filename, e);
} else {
println!("Dumped failed proof to {}", filename);
}
}
result as c_char
}
}
Ok(result) => {
if !result && enable_dump() {
use std::time::{SystemTime, UNIX_EPOCH};
// Dump req.input to a temporary file
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
- let filename = format!("/tmp/proof_{}.json", timestamp);
+ let temp_dir = std::env::temp_dir();
+ let filename = temp_dir.join(format!("proof_{}_{}.json", std::process::id(), timestamp));
let cstr = unsafe { std::ffi::CStr::from_ptr(proof_str) };
if let Err(e) = std::fs::write(&filename, cstr.to_bytes()) {
eprintln!("Failed to write proof to file {}: {}", filename.display(), e);
} else {
println!("Dumped failed proof to {}", filename.display());
}
}
result as c_char
}
🤖 Prompt for AI Agents
In crates/libzkp_c/src/lib.rs around lines 74 to 92, the debug dumping uses a
timestamp-based filename in /tmp, which risks race conditions, security issues,
and lacks portability. Fix this by generating a unique filename using a UUID or
a secure random value instead of just a timestamp, use a platform-independent
temporary directory obtained via standard library functions, and ensure file
permissions are set securely when writing the dump file.

}

Expand Down Expand Up @@ -150,10 +179,13 @@ pub unsafe extern "C" fn gen_universal_task(
&[]
};

let fork_name_str = c_char_to_str(fork_name);
tracing::info!("generate universtal task for fork {fork_name_str}, type {task_type}");

let ret = libzkp::gen_universal_task(
task_type,
&task_json,
c_char_to_str(fork_name),
fork_name_str,
expected_vk,
interpreter,
);
Expand All @@ -167,6 +199,21 @@ pub unsafe extern "C" fn gen_universal_task(
expected_pi_hash,
}
} else {
if enable_dump() {
use std::time::{SystemTime, UNIX_EPOCH};
// Dump req.input to a temporary file
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let filename = format!("/tmp/task_{}_{}.json", fork_name_str, timestamp);
if let Err(e) = std::fs::write(&filename, task_json.as_bytes()) {
eprintln!("Failed to write task to file {}: {}", filename, e);
} else {
println!("Dumped failed task to {}", filename);
}
}

Comment on lines +202 to +216
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Apply same improvements as verification dump logic.

The task dumping logic has the same race condition and security concerns as the proof dumping logic.

Apply similar improvements:

-            let filename = format!("/tmp/task_{}_{}.json", fork_name_str, timestamp);
+            let temp_dir = std::env::temp_dir();
+            let filename = temp_dir.join(format!("task_{}_{}_{}.json", fork_name_str, std::process::id(), timestamp));

This addresses:

  • Race conditions by including process ID
  • Portability by using std::env::temp_dir()
  • Better organization by including fork name in filename
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if enable_dump() {
use std::time::{SystemTime, UNIX_EPOCH};
// Dump req.input to a temporary file
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let filename = format!("/tmp/task_{}_{}.json", fork_name_str, timestamp);
if let Err(e) = std::fs::write(&filename, task_json.as_bytes()) {
eprintln!("Failed to write task to file {}: {}", filename, e);
} else {
println!("Dumped failed task to {}", filename);
}
}
if enable_dump() {
use std::time::{SystemTime, UNIX_EPOCH};
// Dump req.input to a temporary file
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let temp_dir = std::env::temp_dir();
let filename = temp_dir.join(format!(
"task_{}_{}_{}.json",
fork_name_str,
std::process::id(),
timestamp
));
if let Err(e) = std::fs::write(&filename, task_json.as_bytes()) {
eprintln!("Failed to write task to file {}: {}", filename, e);
} else {
println!("Dumped failed task to {}", filename);
}
}
🤖 Prompt for AI Agents
In crates/libzkp_c/src/lib.rs around lines 202 to 216, the task dumping logic
has race conditions and security issues similar to the proof dumping logic. Fix
this by generating the dump filename using std::env::temp_dir() for portability,
include the process ID to avoid race conditions, and ensure the fork name is
part of the filename for better organization. Update the filename construction
accordingly and handle errors as before.

tracing::error!("gen_universal_task failed, error: {:#}", ret.unwrap_err());
failed_handling_result()
}
Expand Down