From 5656f531210a55b0f71aac0d8c6efc8a793e291a Mon Sep 17 00:00:00 2001 From: Zhang Junyu Date: Wed, 26 Jun 2024 05:37:01 +0000 Subject: [PATCH] chore: fix clippy warnings --- .github/workflows/build.yml | 2 + crates/cli/src/app_builder.rs | 64 +++++------ crates/cli/src/args.rs | 4 +- crates/cli/src/command.rs | 9 +- crates/cli/src/config.rs | 47 ++++---- crates/cli/src/main.rs | 35 +++--- crates/host/src/host/ecc_helper/bls381/mod.rs | 12 +- .../src/host/ecc_helper/bls381/pair/mod.rs | 6 +- .../src/host/ecc_helper/bls381/sum/mod.rs | 16 +-- crates/host/src/host/ecc_helper/bn254/mod.rs | 18 +-- .../src/host/ecc_helper/bn254/pair/mod.rs | 4 +- .../host/src/host/ecc_helper/bn254/sum/mod.rs | 2 +- crates/host/src/host/ecc_helper/jubjub/mod.rs | 12 +- .../src/host/ecc_helper/jubjub/sum/mod.rs | 44 ++++---- crates/host/src/host/hash_helper/keccak256.rs | 8 +- crates/host/src/host/hash_helper/poseidon.rs | 8 +- crates/host/src/host/hash_helper/sha256.rs | 16 +-- .../host/src/host/merkle_helper/datacache.rs | 13 +-- crates/host/src/host/merkle_helper/merkle.rs | 9 +- crates/host/src/host/witness_helper/mod.rs | 10 +- crates/specs/src/args.rs | 12 +- crates/specs/src/configure_table.rs | 2 +- crates/specs/src/etable.rs | 16 +-- .../specs/src/external_host_call_table/mod.rs | 6 +- crates/specs/src/imtable.rs | 4 - crates/specs/src/itable.rs | 50 +++++---- crates/specs/src/jtable.rs | 8 +- crates/specs/src/lib.rs | 15 ++- crates/specs/src/mtable.rs | 31 +++-- crates/specs/src/slice.rs | 5 +- crates/specs/src/state.rs | 30 +++-- crates/specs/src/types.rs | 6 +- .../zkwasm/src/circuits/etable/allocator.rs | 20 ++-- crates/zkwasm/src/circuits/etable/assign.rs | 8 +- .../src/circuits/etable/constraint_builder.rs | 2 +- .../circuits/etable/op_configure/op_bin.rs | 17 +-- .../etable/op_configure/op_bin_shift.rs | 2 +- .../src/circuits/etable/op_configure/op_br.rs | 2 +- .../circuits/etable/op_configure/op_br_if.rs | 2 +- .../etable/op_configure/op_br_if_eqz.rs | 2 +- .../etable/op_configure/op_br_table.rs | 5 +- .../etable/op_configure/op_conversion.rs | 8 +- .../circuits/etable/op_configure/op_load.rs | 12 +- .../etable/op_configure/op_memory_size.rs | 2 +- .../circuits/etable/op_configure/op_rel.rs | 6 +- .../circuits/etable/op_configure/op_return.rs | 4 +- .../circuits/etable/op_configure/op_store.rs | 14 +-- .../circuits/etable/op_configure/op_unary.rs | 5 +- .../zkwasm/src/circuits/image_table/assign.rs | 21 ++-- crates/zkwasm/src/circuits/jtable/assign.rs | 12 +- crates/zkwasm/src/circuits/mod.rs | 8 +- .../zkwasm/src/circuits/mtable/allocator.rs | 13 +-- crates/zkwasm/src/circuits/mtable/assign.rs | 4 +- .../circuits/post_image_table/continuation.rs | 2 +- crates/zkwasm/src/circuits/rtable.rs | 16 +-- crates/zkwasm/src/circuits/utils/bit.rs | 6 +- .../zkwasm/src/circuits/utils/image_table.rs | 10 +- crates/zkwasm/src/circuits/utils/row_diff.rs | 6 +- .../zkwasm/src/circuits/utils/table_entry.rs | 54 ++------- .../zkwasm/src/circuits/zkwasm_circuit/mod.rs | 6 +- .../src/foreign/context/circuits/assign.rs | 4 +- .../src/foreign/context/circuits/mod.rs | 2 +- .../foreign/context/etable_op_configure.rs | 4 +- crates/zkwasm/src/foreign/context/mod.rs | 2 +- crates/zkwasm/src/foreign/context/runtime.rs | 2 +- .../foreign/wasm_input_helper/circuits/mod.rs | 2 +- .../wasm_input_helper/etable_op_configure.rs | 4 +- .../src/foreign/wasm_input_helper/runtime.rs | 6 +- .../src/foreign/wasm_input_helper/test.rs | 4 +- crates/zkwasm/src/lib.rs | 2 + crates/zkwasm/src/loader/mod.rs | 2 +- crates/zkwasm/src/loader/slice.rs | 8 +- .../runtime/host/external_circuit_plugin.rs | 2 +- crates/zkwasm/src/runtime/host/host_env.rs | 18 ++- .../runtime/host/internal_circuit_plugin.rs | 4 +- crates/zkwasm/src/runtime/host/mod.rs | 4 +- crates/zkwasm/src/runtime/mod.rs | 48 ++++---- .../src/runtime/monitor/plugins/phantom.rs | 4 +- .../src/runtime/monitor/plugins/statistic.rs | 2 +- .../monitor/plugins/table/frame_table.rs | 36 +++--- .../monitor/plugins/table/instruction.rs | 106 +++++++++--------- .../src/runtime/monitor/plugins/table/mod.rs | 33 +++--- .../src/runtime/monitor/statistic_monitor.rs | 2 +- .../src/runtime/monitor/table_monitor.rs | 2 +- crates/zkwasm/src/runtime/state.rs | 40 ++++--- .../zkwasm/src/runtime/wasmi_interpreter.rs | 6 +- crates/zkwasm/src/test/mod.rs | 2 +- crates/zkwasm/src/test/test_start.rs | 2 +- .../test_wasm_instructions/op_call_host.rs | 4 +- 89 files changed, 527 insertions(+), 623 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index d95236d5f..560f4a3ea 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -19,6 +19,8 @@ jobs: components: rustfmt, clippy - name: Code Style Check run: cargo fmt --check + - name: Cargo clippy + run: cargo clippy && cargo clippy --features continuation - name: Build run: cargo build && cargo clean - name: Build Playground diff --git a/crates/cli/src/app_builder.rs b/crates/cli/src/app_builder.rs index 30267ed1b..bc21fc0d7 100644 --- a/crates/cli/src/app_builder.rs +++ b/crates/cli/src/app_builder.rs @@ -215,65 +215,65 @@ pub(crate) fn app() -> App<'static> { .subcommand_required(true) } -impl Into for &ArgMatches { - fn into(self) -> SetupArg { +impl From<&ArgMatches> for SetupArg { + fn from(val: &ArgMatches) -> Self { SetupArg { - k: *self.get_one::("K").unwrap(), - host_mode: *self.get_one::("host").unwrap(), - phantom_functions: self + k: *val.get_one::("K").unwrap(), + host_mode: *val.get_one::("host").unwrap(), + phantom_functions: val .get_many::("phantom") .unwrap_or_default() .map(|v| v.to_string()) .collect::>(), - wasm_image: WasmImageArg::parse(self), + wasm_image: WasmImageArg::parse(val), } } } -impl Into for &ArgMatches { - fn into(self) -> RunningArg { +impl From<&ArgMatches> for RunningArg { + fn from(val: &ArgMatches) -> Self { RunningArg { - output_dir: OutputDirArg::parse(self), - public_inputs: PublicInputsArg::parse(self), - private_inputs: PrivateInputsArg::parse(self), - context_inputs: ContextInputsArg::parse(self), - context_output: ContextOutputArg::parse(self), + output_dir: OutputDirArg::parse(val), + public_inputs: PublicInputsArg::parse(val), + private_inputs: PrivateInputsArg::parse(val), + context_inputs: ContextInputsArg::parse(val), + context_output: ContextOutputArg::parse(val), } } } -impl Into for &ArgMatches { - fn into(self) -> DryRunArg { +impl From<&ArgMatches> for DryRunArg { + fn from(val: &ArgMatches) -> Self { DryRunArg { - wasm_image: WasmImageArg::parse(self).unwrap(), - running_arg: self.into(), + wasm_image: WasmImageArg::parse(val).unwrap(), + running_arg: val.into(), } } } -impl Into for &ArgMatches { - fn into(self) -> ProveArg { +impl From<&ArgMatches> for ProveArg { + fn from(val: &ArgMatches) -> Self { ProveArg { - wasm_image: WasmImageArg::parse(self).unwrap(), - output_dir: OutputDirArg::parse(self), - running_arg: self.into(), - mock_test: MockTestArg::parse(self), - file_backend: FileBackendArg::parse(self), + wasm_image: WasmImageArg::parse(val).unwrap(), + output_dir: OutputDirArg::parse(val), + running_arg: val.into(), + mock_test: MockTestArg::parse(val), + file_backend: FileBackendArg::parse(val), } } } -impl Into for &ArgMatches { - fn into(self) -> VerifyArg { +impl From<&ArgMatches> for VerifyArg { + fn from(val: &ArgMatches) -> Self { VerifyArg { - output_dir: OutputDirArg::parse(self), + output_dir: OutputDirArg::parse(val), } } } -impl Into for ArgMatches { - fn into(self) -> ZkWasmCli { - let subcommand = match self.subcommand() { +impl From for ZkWasmCli { + fn from(arg: ArgMatches) -> ZkWasmCli { + let subcommand = match arg.subcommand() { Some(("setup", sub_matches)) => Subcommands::Setup(sub_matches.into()), Some(("dry-run", sub_matches)) => Subcommands::DryRun(sub_matches.into()), Some(("prove", sub_matches)) => Subcommands::Prove(sub_matches.into()), @@ -282,8 +282,8 @@ impl Into for ArgMatches { }; ZkWasmCli { - name: self.get_one::("NAME").unwrap().to_owned(), - params_dir: self.get_one::("params").unwrap().to_owned(), + name: arg.get_one::("NAME").unwrap().to_owned(), + params_dir: arg.get_one::("params").unwrap().to_owned(), subcommand, } } diff --git a/crates/cli/src/args.rs b/crates/cli/src/args.rs index d8c889f98..1c47d9d8a 100644 --- a/crates/cli/src/args.rs +++ b/crates/cli/src/args.rs @@ -5,8 +5,8 @@ use serde::Serialize; pub enum HostMode { /// Trivial Wasm Host Environment #[default] - DEFAULT, + Default, /// Wasm Host Environment with more Zk plugins - STANDARD, + Standard, } diff --git a/crates/cli/src/command.rs b/crates/cli/src/command.rs index 09d56c15e..b8cecaeaf 100644 --- a/crates/cli/src/command.rs +++ b/crates/cli/src/command.rs @@ -2,6 +2,7 @@ use std::fs::File; use std::fs::OpenOptions; use std::fs::{self}; use std::io::Read; +use std::path::Path; use std::path::PathBuf; use crate::config::CircuitDataConfig; @@ -80,7 +81,7 @@ impl SetupArg { pub(crate) fn setup_circuit_data( &self, name: &str, - params_dir: &PathBuf, + params_dir: &Path, params: &Params, k: u32, compilation_tables: &CompilationTable, @@ -119,14 +120,14 @@ impl SetupArg { pub(crate) fn setup( &self, - env_builder: &Box, + env_builder: &dyn HostEnvBuilder, name: &str, params_dir: &PathBuf, ) -> anyhow::Result<()> { fs::create_dir_all(params_dir)?; let wasm_image = self.wasm_image.as_ref().map_or( - wabt::wat2wasm(&TRIVIAL_WASM).map_err(|err| anyhow::anyhow!(err)), + wabt::wat2wasm(TRIVIAL_WASM).map_err(|err| anyhow::anyhow!(err)), |file| fs::read(file).map_err(|err| anyhow::anyhow!(err)), )?; let module = ZkWasmLoader::parse_module(&wasm_image)?; @@ -189,7 +190,7 @@ impl SetupArg { format!("{:x}", md5) }; - let config_path = params_dir.join(&name_of_config(name)); + let config_path = params_dir.join(name_of_config(name)); let config = Config { name: name.to_string(), diff --git a/crates/cli/src/config.rs b/crates/cli/src/config.rs index 06facb22d..b9ecd5da0 100644 --- a/crates/cli/src/config.rs +++ b/crates/cli/src/config.rs @@ -2,6 +2,7 @@ use std::fs::File; use std::io::Cursor; use std::io::Read; use std::io::Write; +use std::path::Path; use std::path::PathBuf; use anyhow::Result; @@ -108,7 +109,7 @@ impl Config { verifying_key: &[u8], expected_md5: &str, ) -> anyhow::Result<()> { - let verifying_key_md5 = format!("{:x}", md5::compute(&verifying_key)); + let verifying_key_md5 = format!("{:x}", md5::compute(verifying_key)); if verifying_key_md5 != expected_md5 { anyhow::bail!( @@ -123,7 +124,7 @@ impl Config { impl Config { pub(crate) fn write(&self, fd: &mut File) -> anyhow::Result<()> { - fd.write(&bincode::serialize(self)?)?; + fd.write_all(&bincode::serialize(self)?)?; Ok(()) } @@ -131,27 +132,27 @@ impl Config { pub(crate) fn read(fd: &mut File) -> anyhow::Result { let mut buf = Vec::new(); fd.read_to_end(&mut buf)?; - let config = bincode::deserialize(&mut buf)?; + let config = bincode::deserialize(&buf)?; Ok(config) } } impl Config { - fn read_wasm_image(&self, wasm_image: &PathBuf) -> anyhow::Result { + fn read_wasm_image(&self, wasm_image: &Path) -> anyhow::Result { let mut buf = Vec::new(); - File::open(&wasm_image)?.read_to_end(&mut buf)?; + File::open(wasm_image)?.read_to_end(&mut buf)?; self.image_consistent_check(&buf)?; ZkWasmLoader::parse_module(&buf) } - fn read_params(&self, params_dir: &PathBuf) -> anyhow::Result> { + fn read_params(&self, params_dir: &Path) -> anyhow::Result> { let path = params_dir.join(name_of_params(self.k)); let mut buf = Vec::new(); - File::open(&path)?.read_to_end(&mut buf)?; + File::open(path)?.read_to_end(&mut buf)?; self.params_consistent_check(&buf)?; @@ -166,7 +167,7 @@ impl Config { expected_md5: &str, ) -> anyhow::Result> { let mut buf = Vec::new(); - File::open(&path)?.read_to_end(&mut buf)?; + File::open(path)?.read_to_end(&mut buf)?; let circuit_data_md5 = format!("{:x}", md5::compute(&buf)); @@ -177,16 +178,16 @@ impl Config { ); } - let circuit_data = CircuitData::::read(&mut File::open(&path)?)?; + let circuit_data = CircuitData::::read(&mut File::open(path)?)?; Ok(circuit_data) } pub(crate) fn dry_run( self, - env_builder: &Box, - wasm_image: &PathBuf, - output_dir: &PathBuf, + env_builder: &dyn HostEnvBuilder, + wasm_image: &Path, + output_dir: &Path, arg: ExecutionArg, context_output_filename: Option, ) -> Result<()> { @@ -236,10 +237,10 @@ impl Config { pub(crate) fn prove( self, - env_builder: &Box, - wasm_image: &PathBuf, - params_dir: &PathBuf, - output_dir: &PathBuf, + env_builder: &dyn HostEnvBuilder, + wasm_image: &Path, + params_dir: &Path, + output_dir: &Path, arg: ExecutionArg, context_output_filename: Option, mock_test: bool, @@ -309,7 +310,6 @@ impl Config { println!("{} Build circuit(s)...", style("[6/8]").bold().dim(),); let instances = result .public_inputs_and_outputs - .clone() .iter() .map(|v| (*v).into()) .collect::>(); @@ -321,10 +321,7 @@ impl Config { let progress_bar = ProgressBar::new(tables.execution_tables.etable.len() as u64); - let mut slices = Slices::new(self.k, tables)? - .into_iter() - .enumerate() - .peekable(); + let mut slices = Slices::new(self.k, tables)?.enumerate().peekable(); while let Some((index, circuit)) = slices.next() { let circuit = circuit?; @@ -407,7 +404,7 @@ impl Config { ), }; - proof_piece_info.save_proof_data(&vec![instances.clone()], &proof, &output_dir); + proof_piece_info.save_proof_data(&vec![instances.clone()], &proof, output_dir); proof_load_info.append_single_proof(proof_piece_info); @@ -416,7 +413,7 @@ impl Config { progress_bar.finish_and_clear(); { - let proof_load_info_path = output_dir.join(&name_of_loadinfo(&self.name)); + let proof_load_info_path = output_dir.join(name_of_loadinfo(&self.name)); println!( "{} Saving proof load info to {:?}...", style("[8/8]").bold().dim(), @@ -428,7 +425,7 @@ impl Config { Ok(()) } - pub(crate) fn verify(self, params_dir: &PathBuf, output_dir: &PathBuf) -> anyhow::Result<()> { + pub(crate) fn verify(self, params_dir: &Path, output_dir: &PathBuf) -> anyhow::Result<()> { let mut proofs = { println!( "{} Reading proofs from {:?}", @@ -440,7 +437,7 @@ impl Config { ProofGenerationInfo::load(&output_dir.join(&name_of_loadinfo(&self.name))); let proofs: Vec> = - ProofInfo::load_proof(&output_dir, ¶ms_dir, &proof_load_info); + ProofInfo::load_proof(output_dir, params_dir, &proof_load_info); proofs } diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 0177e161c..ecc5442d4 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -1,4 +1,5 @@ #![deny(warnings)] +#![allow(clippy::too_many_arguments, clippy::while_let_on_iterator)] use std::fs; use std::path::PathBuf; @@ -27,7 +28,7 @@ mod command; mod config; mod names; -const TRIVIAL_WASM: &'static str = r#" +const TRIVIAL_WASM: &str = r#" (module (func (export "zkmain")) ) @@ -53,15 +54,15 @@ fn main() -> Result<()> { match cli.subcommand { Subcommands::Setup(arg) => { let env_builder: Box = match arg.host_mode { - HostMode::DEFAULT => Box::new(DefaultHostEnvBuilder), - HostMode::STANDARD => Box::new(StandardHostEnvBuilder::default()), + HostMode::Default => Box::new(DefaultHostEnvBuilder), + HostMode::Standard => Box::::default(), }; - arg.setup(&env_builder, &cli.name, &cli.params_dir)?; + arg.setup(&*env_builder, &cli.name, &cli.params_dir)?; } Subcommands::DryRun(arg) => { let config = Config::read(&mut fs::File::open( - cli.params_dir.join(&name_of_config(&cli.name)), + cli.params_dir.join(name_of_config(&cli.name)), )?)?; let public_inputs = parse_args(&arg.running_arg.public_inputs); @@ -69,12 +70,12 @@ fn main() -> Result<()> { let context_inputs = parse_args(&arg.running_arg.context_inputs); let env_builder: Box = match config.host_mode { - HostMode::DEFAULT => Box::new(DefaultHostEnvBuilder), - HostMode::STANDARD => Box::new(StandardHostEnvBuilder::default()), + HostMode::Default => Box::new(DefaultHostEnvBuilder), + HostMode::Standard => Box::::default(), }; config.dry_run( - &env_builder, + &*env_builder, &arg.wasm_image, &arg.running_arg.output_dir, ExecutionArg { @@ -86,11 +87,11 @@ fn main() -> Result<()> { )?; } Subcommands::Prove(arg) => { - let trace_dir = arg.output_dir.clone().join("traces"); + let trace_dir = arg.output_dir.join("traces"); fs::create_dir_all(&trace_dir)?; let config = Config::read(&mut fs::File::open( - cli.params_dir.join(&name_of_config(&cli.name)), + cli.params_dir.join(name_of_config(&cli.name)), )?)?; let public_inputs = parse_args(&arg.running_arg.public_inputs); @@ -105,7 +106,7 @@ fn main() -> Result<()> { Box::new(move |slice, etable: &EventTable| { let filename_of_etable_slice = PathBuf::from(name_of_etable_slice(&name, slice)); - let path = trace_dir.join(&filename_of_etable_slice); + let path = trace_dir.join(filename_of_etable_slice); etable.write(&path).unwrap(); @@ -115,12 +116,12 @@ fn main() -> Result<()> { let frame_table_writer = { let name = cli.name.clone(); - let trace_dir = trace_dir.clone(); + let trace_dir = trace_dir; Box::new(move |slice, frame_table: &FrameTable| { let filename_of_frame_table_slice = PathBuf::from(name_of_frame_table_slice(&name, slice)); - let path = trace_dir.join(&filename_of_frame_table_slice); + let path = trace_dir.join(filename_of_frame_table_slice); frame_table.write(&path).unwrap(); @@ -137,12 +138,12 @@ fn main() -> Result<()> { }; let env_builder: Box = match config.host_mode { - HostMode::DEFAULT => Box::new(DefaultHostEnvBuilder), - HostMode::STANDARD => Box::new(StandardHostEnvBuilder::default()), + HostMode::Default => Box::new(DefaultHostEnvBuilder), + HostMode::Standard => Box::::default(), }; config.prove( - &env_builder, + &*env_builder, &arg.wasm_image, &cli.params_dir, &arg.output_dir, @@ -158,7 +159,7 @@ fn main() -> Result<()> { } Subcommands::Verify(arg) => { let config = Config::read(&mut fs::File::open( - cli.params_dir.join(&name_of_config(&cli.name)), + cli.params_dir.join(name_of_config(&cli.name)), )?)?; config.verify(&cli.params_dir, &arg.output_dir)?; diff --git a/crates/host/src/host/ecc_helper/bls381/mod.rs b/crates/host/src/host/ecc_helper/bls381/mod.rs index badfe5699..b6a1a47e9 100644 --- a/crates/host/src/host/ecc_helper/bls381/mod.rs +++ b/crates/host/src/host/ecc_helper/bls381/mod.rs @@ -12,7 +12,7 @@ use std::ops::AddAssign; use super::bn_to_field; use super::field_to_bn; -fn fetch_fq(limbs: &Vec, index: usize) -> Bls381Fq { +fn fetch_fq(limbs: &[u64], index: usize) -> Bls381Fq { let mut bn = BigUint::zero(); for i in 0..8 { bn.add_assign(BigUint::from_u64(limbs[index * 8 + i]).unwrap() << (i * 54)) @@ -20,14 +20,14 @@ fn fetch_fq(limbs: &Vec, index: usize) -> Bls381Fq { bn_to_field(&bn) } -fn fetch_fq2(limbs: &Vec, index: usize) -> Bls381Fq2 { +fn fetch_fq2(limbs: &[u64], index: usize) -> Bls381Fq2 { Bls381Fq2 { c0: fetch_fq(limbs, index), c1: fetch_fq(limbs, index + 1), } } -fn fetch_g1(limbs: &Vec, g1_identity: bool) -> G1Affine { +fn fetch_g1(limbs: &[u64], g1_identity: bool) -> G1Affine { if g1_identity { G1Affine::identity() } else { @@ -41,12 +41,12 @@ fn bls381_fq_to_limbs(result_limbs: &mut Vec, f: Bls381Fq) { for _ in 0..8 { let d: BigUint = BigUint::from(1u64 << 54); let r = bn.clone() % d.clone(); - let value = if r == BigUint::from(0 as u32) { - 0 as u64 + let value = if r == BigUint::from(0_u32) { + 0_u64 } else { r.to_u64_digits()[0] }; - bn = bn / d; + bn /= d; result_limbs.append(&mut vec![value]); } } diff --git a/crates/host/src/host/ecc_helper/bls381/pair/mod.rs b/crates/host/src/host/ecc_helper/bls381/pair/mod.rs index 01cc63e0c..9a07e2a7b 100644 --- a/crates/host/src/host/ecc_helper/bls381/pair/mod.rs +++ b/crates/host/src/host/ecc_helper/bls381/pair/mod.rs @@ -68,7 +68,7 @@ use specs::external_host_call_table::ExternalHostCallSignature; pub fn register_blspair_foreign(env: &mut HostEnv) { let foreign_blspair_plugin = env .external_env - .register_plugin("foreign_blspair", Box::new(BlsPairContext::default())); + .register_plugin("foreign_blspair", Box::::default()); env.external_env.register_function( "blspair_g1", @@ -113,7 +113,7 @@ pub fn register_blspair_foreign(env: &mut HostEnv) { G2Affine { x: fetch_fq2(&context.limbs, 2), y: fetch_fq2(&context.limbs, 4), - infinity: (0 as u8).into(), + infinity: 0_u8.into(), } }; let ab = pairing(&g1, &g2); @@ -133,7 +133,7 @@ pub fn register_blspair_foreign(env: &mut HostEnv) { "blspair_pop", ForeignInst::BlsPairG3 as usize, ExternalHostCallSignature::Return, - foreign_blspair_plugin.clone(), + foreign_blspair_plugin, Rc::new( |_obs, context: &mut dyn ForeignContext, _args: wasmi::RuntimeArgs| { let context = context.downcast_mut::().unwrap(); diff --git a/crates/host/src/host/ecc_helper/bls381/sum/mod.rs b/crates/host/src/host/ecc_helper/bls381/sum/mod.rs index 2c316a951..89abbca14 100644 --- a/crates/host/src/host/ecc_helper/bls381/sum/mod.rs +++ b/crates/host/src/host/ecc_helper/bls381/sum/mod.rs @@ -50,7 +50,7 @@ use specs::external_host_call_table::ExternalHostCallSignature; pub fn register_blssum_foreign(env: &mut HostEnv) { let foreign_blssum_plugin = env .external_env - .register_plugin("foreign_blssum", Box::new(BlsSumContext::default())); + .register_plugin("foreign_blssum", Box::::default()); env.external_env.register_function( "blssum_g1", @@ -77,7 +77,7 @@ pub fn register_blssum_foreign(env: &mut HostEnv) { "blssum_pop", ForeignInst::BlsSumResult as usize, ExternalHostCallSignature::Return, - foreign_blssum_plugin.clone(), + foreign_blssum_plugin, Rc::new( |_obs, context: &mut dyn ForeignContext, _args: wasmi::RuntimeArgs| { let context = context.downcast_mut::().unwrap(); @@ -87,15 +87,11 @@ pub fn register_blssum_foreign(env: &mut HostEnv) { .limbs .chunks(16) .zip(context.g1_identity.clone()) - .map(|(limbs, identity)| fetch_g1(&limbs.to_vec(), identity)) + .map(|(limbs, identity)| fetch_g1(limbs, identity)) .collect::>(); - let g1result = - fqs[1..fqs.len()] - .into_iter() - .fold(fqs[0], |acc: G1Affine, x| { - let acc = acc.add(x.clone()).into(); - acc - }); + let g1result = fqs[1..fqs.len()] + .iter() + .fold(fqs[0], |acc: G1Affine, x| acc.add(*x).into()); context.bls381_result_to_limbs(g1result); }, |_| (), diff --git a/crates/host/src/host/ecc_helper/bn254/mod.rs b/crates/host/src/host/ecc_helper/bn254/mod.rs index d2514e3c1..bb7d825a8 100644 --- a/crates/host/src/host/ecc_helper/bn254/mod.rs +++ b/crates/host/src/host/ecc_helper/bn254/mod.rs @@ -17,15 +17,15 @@ const LIMBNB: usize = 5; use super::bn_to_field; use super::field_to_bn; -fn fetch_fr(limbs: &Vec) -> Fr { +fn fetch_fr(limbs: &[u64]) -> Fr { let mut bn = BigUint::zero(); - for i in 0..4 { - bn.add_assign(BigUint::from_u64(limbs[i]).unwrap() << (i * 64)) + for (i, limb) in limbs.iter().enumerate().take(4) { + bn.add_assign(BigUint::from_u64(*limb).unwrap() << (i * 64)) } bn_to_field(&bn) } -pub fn fetch_fq(limbs: &Vec, index: usize) -> BN254Fq { +pub fn fetch_fq(limbs: &[u64], index: usize) -> BN254Fq { let mut bn = BigUint::zero(); for i in 0..LIMBNB { bn.add_assign(BigUint::from_u64(limbs[index * LIMBNB + i]).unwrap() << (i * LIMBSZ)) @@ -33,7 +33,7 @@ pub fn fetch_fq(limbs: &Vec, index: usize) -> BN254Fq { bn_to_field(&bn) } -pub fn fetch_fq2(limbs: &Vec, index: usize) -> BN254Fq2 { +pub fn fetch_fq2(limbs: &[u64], index: usize) -> BN254Fq2 { BN254Fq2 { c0: fetch_fq(limbs, index), c1: fetch_fq(limbs, index + 1), @@ -55,14 +55,14 @@ fn fetch_g1(limbs: &Vec) -> G1Affine { pub fn bn254_fq_to_limbs(result_limbs: &mut Vec, f: BN254Fq) { let mut bn = field_to_bn(&f); for _ in 0..LIMBNB { - let d: BigUint = BigUint::from(1 as u64).shl(LIMBSZ); + let d: BigUint = BigUint::from(1_u64).shl(LIMBSZ); let r = bn.clone() % d.clone(); - let value = if r == BigUint::from(0 as u32) { - 0 as u64 + let value = if r == BigUint::from(0_u32) { + 0_u64 } else { r.to_u64_digits()[0] }; - bn = bn / d; + bn /= d; result_limbs.append(&mut vec![value]); } } diff --git a/crates/host/src/host/ecc_helper/bn254/pair/mod.rs b/crates/host/src/host/ecc_helper/bn254/pair/mod.rs index a0fc89741..c341bb3e1 100644 --- a/crates/host/src/host/ecc_helper/bn254/pair/mod.rs +++ b/crates/host/src/host/ecc_helper/bn254/pair/mod.rs @@ -75,7 +75,7 @@ use specs::external_host_call_table::ExternalHostCallSignature; pub fn register_bn254pair_foreign(env: &mut HostEnv) { let foreign_blspair_plugin = env .external_env - .register_plugin("foreign_blspair", Box::new(BN254PairContext::default())); + .register_plugin("foreign_blspair", Box::::default()); env.external_env.register_function( "bn254pair_g1", @@ -146,7 +146,7 @@ pub fn register_bn254pair_foreign(env: &mut HostEnv) { "bn254pair_pop", Bn254PairG3 as usize, ExternalHostCallSignature::Return, - foreign_blspair_plugin.clone(), + foreign_blspair_plugin, Rc::new( |_obs, context: &mut dyn ForeignContext, _args: wasmi::RuntimeArgs| { let context = context.downcast_mut::().unwrap(); diff --git a/crates/host/src/host/ecc_helper/bn254/sum/mod.rs b/crates/host/src/host/ecc_helper/bn254/sum/mod.rs index 29daf2a45..d0b7a6876 100644 --- a/crates/host/src/host/ecc_helper/bn254/sum/mod.rs +++ b/crates/host/src/host/ecc_helper/bn254/sum/mod.rs @@ -143,7 +143,7 @@ pub fn register_bn254sum_foreign(env: &mut HostEnv) { "bn254_sum_finalize", Bn254SumResult as usize, ExternalHostCallSignature::Return, - foreign_bn254sum_plugin.clone(), + foreign_bn254sum_plugin, Rc::new( |_obs, context: &mut dyn ForeignContext, _args: wasmi::RuntimeArgs| { let context = context.downcast_mut::().unwrap(); diff --git a/crates/host/src/host/ecc_helper/jubjub/mod.rs b/crates/host/src/host/ecc_helper/jubjub/mod.rs index a9993ed46..2f9e95176 100644 --- a/crates/host/src/host/ecc_helper/jubjub/mod.rs +++ b/crates/host/src/host/ecc_helper/jubjub/mod.rs @@ -13,7 +13,7 @@ const LIMBNB: usize = 4; use super::bn_to_field; use super::field_to_bn; -pub fn fetch_fq(limbs: &Vec, index: usize) -> BabyJubjubFq { +pub fn fetch_fq(limbs: &[u64], index: usize) -> BabyJubjubFq { let mut bn = BigUint::zero(); for i in 0..LIMBNB { bn.add_assign(BigUint::from_u64(limbs[index * LIMBNB + i]).unwrap() << (i * LIMBSZ)) @@ -21,7 +21,7 @@ pub fn fetch_fq(limbs: &Vec, index: usize) -> BabyJubjubFq { bn_to_field(&bn) } -fn fetch_g1(limbs: &Vec) -> jubjub::Point { +fn fetch_g1(limbs: &[u64]) -> jubjub::Point { jubjub::Point { x: fetch_fq(limbs, 0), y: fetch_fq(limbs, 1), @@ -31,14 +31,14 @@ fn fetch_g1(limbs: &Vec) -> jubjub::Point { pub fn babyjubjub_fq_to_limbs(result_limbs: &mut Vec, f: BabyJubjubFq) { let mut bn = field_to_bn(&f); for _ in 0..LIMBNB { - let d: BigUint = BigUint::from(1 as u64).shl(LIMBSZ); + let d: BigUint = BigUint::from(1_u64).shl(LIMBSZ); let r = bn.clone() % d.clone(); - let value = if r == BigUint::from(0 as u32) { - 0 as u64 + let value = if r == BigUint::from(0_u32) { + 0_u64 } else { r.to_u64_digits()[0] }; - bn = bn / d; + bn /= d; result_limbs.append(&mut vec![value]); } } diff --git a/crates/host/src/host/ecc_helper/jubjub/sum/mod.rs b/crates/host/src/host/ecc_helper/jubjub/sum/mod.rs index 648d033c6..ca94914e8 100644 --- a/crates/host/src/host/ecc_helper/jubjub/sum/mod.rs +++ b/crates/host/src/host/ecc_helper/jubjub/sum/mod.rs @@ -16,12 +16,11 @@ use super::babyjubjub_fq_to_limbs; use super::fetch_g1; use super::LIMBNB; -fn fetch_biguint(_limbs: &Vec) -> BigUint { +fn fetch_biguint(_limbs: &[u64]) -> BigUint { BigUint::from_bytes_le( _limbs .iter() - .map(|x| x.to_le_bytes()) - .flatten() + .flat_map(|x| x.to_le_bytes()) .collect::>() .as_slice(), ) @@ -79,23 +78,20 @@ impl BabyJubjubSumContext { pub fn babyjubjub_sum_finalize(&mut self) -> u64 { let limbs = self.result_limbs.clone(); - match limbs { - None => { - assert!(self.limbs.len() == LIMBNB * 2); - let coeff = fetch_biguint(&self.coeffs.to_vec()); - let g1 = fetch_g1(&self.limbs.to_vec()); - log::debug!("acc is {:?}", self.acc); - log::debug!("g1 is {:?}", g1); - log::debug!("coeff is {:?} {}", coeff, self.coeffs.len()); - self.acc = self - .acc - .projective() - .add(&g1.mul_scalar(&coeff).projective()) - .affine(); - log::debug!("msm result: {:?}", self.acc); - self.babyjubjub_result_to_limbs(self.acc.clone()); - } - _ => (), + if limbs.is_none() { + assert!(self.limbs.len() == LIMBNB * 2); + let coeff = fetch_biguint(&self.coeffs.to_vec()); + let g1 = fetch_g1(&self.limbs.to_vec()); + log::debug!("acc is {:?}", self.acc); + log::debug!("g1 is {:?}", g1); + log::debug!("coeff is {:?} {}", coeff, self.coeffs.len()); + self.acc = self + .acc + .projective() + .add(&g1.mul_scalar(&coeff).projective()) + .affine(); + log::debug!("msm result: {:?}", self.acc); + self.babyjubjub_result_to_limbs(self.acc.clone()); }; let ret = self.result_limbs.as_ref().unwrap()[self.result_cursor]; self.result_cursor += 1; @@ -161,14 +157,14 @@ pub fn register_babyjubjubsum_foreign(env: &mut HostEnv) { "babyjubjub_sum_finalize", JubjubSumResult as usize, ExternalHostCallSignature::Return, - foreign_babyjubjubsum_plugin.clone(), + foreign_babyjubjubsum_plugin, Rc::new( |_obs, context: &mut dyn ForeignContext, _args: wasmi::RuntimeArgs| { let context = context.downcast_mut::().unwrap(); - let ret = Some(wasmi::RuntimeValue::I64( + + Some(wasmi::RuntimeValue::I64( context.babyjubjub_sum_finalize() as i64 - )); - ret + )) }, ), ); diff --git a/crates/host/src/host/hash_helper/keccak256.rs b/crates/host/src/host/hash_helper/keccak256.rs index abec7d92b..a5f2fb3c9 100644 --- a/crates/host/src/host/hash_helper/keccak256.rs +++ b/crates/host/src/host/hash_helper/keccak256.rs @@ -62,11 +62,11 @@ impl Keccak256Context { pub fn keccak_finalize(&mut self) -> u64 { assert!(self.buf.len() == 17); if self.generator.cursor == 0 { - self.hasher.as_mut().map(|s| { + if let Some(s) = self.hasher.as_mut() { log::debug!("perform hash with {:?}", self.buf); let r = s.update_exact(&self.buf.clone().try_into().unwrap()); self.generator.values = r.to_vec(); - }); + }; } self.generator.gen() } @@ -110,7 +110,7 @@ pub fn register_keccak_foreign(env: &mut HostEnv) { Rc::new( |_obs, context: &mut dyn ForeignContext, args: wasmi::RuntimeArgs| { let context = context.downcast_mut::().unwrap(); - context.keccak_push(args.nth::(0) as u64); + context.keccak_push(args.nth::(0)); None }, ), @@ -120,7 +120,7 @@ pub fn register_keccak_foreign(env: &mut HostEnv) { "keccak_finalize", Keccak256Finalize as usize, ExternalHostCallSignature::Return, - foreign_keccak_plugin.clone(), + foreign_keccak_plugin, Rc::new( |_obs, context: &mut dyn ForeignContext, _args: wasmi::RuntimeArgs| { let context = context.downcast_mut::().unwrap(); diff --git a/crates/host/src/host/hash_helper/poseidon.rs b/crates/host/src/host/hash_helper/poseidon.rs index 953fa3748..c6dfc1876 100644 --- a/crates/host/src/host/hash_helper/poseidon.rs +++ b/crates/host/src/host/hash_helper/poseidon.rs @@ -99,7 +99,7 @@ impl PoseidonContext { pub fn poseidon_finalize(&mut self) -> u64 { assert!(self.buf.len() == 8); if self.generator.cursor == 0 { - self.hasher.as_mut().map(|s| { + if let Some(s) = self.hasher.as_mut() { log::debug!("perform hash with {:?}", self.buf); let r = s.update_exact(&self.buf.clone().try_into().unwrap()); let dwords: Vec = r.to_repr().to_vec(); @@ -107,7 +107,7 @@ impl PoseidonContext { .chunks(8) .map(|x| u64::from_le_bytes(x.to_vec().try_into().unwrap())) .collect::>(); - }); + }; } self.generator.gen() } @@ -152,7 +152,7 @@ pub fn register_poseidon_foreign(env: &mut HostEnv) { Rc::new( |_obs, context: &mut dyn ForeignContext, args: wasmi::RuntimeArgs| { let context = context.downcast_mut::().unwrap(); - context.poseidon_push(args.nth::(0) as u64); + context.poseidon_push(args.nth::(0)); None }, ), @@ -162,7 +162,7 @@ pub fn register_poseidon_foreign(env: &mut HostEnv) { "poseidon_finalize", PoseidonFinalize as usize, ExternalHostCallSignature::Return, - foreign_poseidon_plugin.clone(), + foreign_poseidon_plugin, Rc::new( |_obs, context: &mut dyn ForeignContext, _args: wasmi::RuntimeArgs| { let context = context.downcast_mut::().unwrap(); diff --git a/crates/host/src/host/hash_helper/sha256.rs b/crates/host/src/host/hash_helper/sha256.rs index 4b1784c94..d4ddc8a41 100644 --- a/crates/host/src/host/hash_helper/sha256.rs +++ b/crates/host/src/host/hash_helper/sha256.rs @@ -92,10 +92,10 @@ pub fn register_sha256_foreign(env: &mut HostEnv) { .hasher .as_mut() .map_or(Some(Sha256::new()), |_| None); - hasher.map(|s| { + if let Some(s) = hasher { context.hasher = Some(s); context.size = args.nth::(0) as usize; - }); + }; None }, ), @@ -109,7 +109,7 @@ pub fn register_sha256_foreign(env: &mut HostEnv) { Rc::new( |_obs, context: &mut dyn ForeignContext, args: wasmi::RuntimeArgs| { let context = context.downcast_mut::().unwrap(); - context.hasher.as_mut().map(|s| { + if let Some(s) = context.hasher.as_mut() { let sz = if context.size > 8 { context.size -= 8; 8 @@ -118,10 +118,10 @@ pub fn register_sha256_foreign(env: &mut HostEnv) { context.size = 0; s }; - let mut r = (args.nth::(0) as u64).to_le_bytes().to_vec(); + let mut r = args.nth::(0).to_le_bytes().to_vec(); r.truncate(sz); s.update(r); - }); + }; None }, ), @@ -131,17 +131,17 @@ pub fn register_sha256_foreign(env: &mut HostEnv) { "sha256_finalize", SHA256Finalize as usize, ExternalHostCallSignature::Return, - foreign_sha256_plugin.clone(), + foreign_sha256_plugin, Rc::new( |_obs, context: &mut dyn ForeignContext, _args: wasmi::RuntimeArgs| { let context = context.downcast_mut::().unwrap(); - context.hasher.as_ref().map(|s| { + if let Some(s) = context.hasher.as_ref() { let dwords: Vec = s.clone().finalize()[..].to_vec(); context.generator.values = dwords .chunks(8) .map(|x| u64::from_le_bytes(x.to_vec().try_into().unwrap())) .collect::>(); - }); + }; context.hasher = None; Some(wasmi::RuntimeValue::I64(context.generator.gen() as i64)) }, diff --git a/crates/host/src/host/merkle_helper/datacache.rs b/crates/host/src/host/merkle_helper/datacache.rs index fe6079272..c5d1c8ea0 100644 --- a/crates/host/src/host/merkle_helper/datacache.rs +++ b/crates/host/src/host/merkle_helper/datacache.rs @@ -60,8 +60,6 @@ impl CacheContext { self.data = datahashrecord.map_or(vec![], |r| { r.data .chunks_exact(8) - .into_iter() - .into_iter() .map(|x| u64::from_le_bytes(x.try_into().unwrap())) .collect::>() }); @@ -76,8 +74,7 @@ impl CacheContext { data: self .data .iter() - .map(|x| x.to_le_bytes()) - .flatten() + .flat_map(|x| x.to_le_bytes()) .collect::>(), } }) @@ -88,7 +85,7 @@ impl CacheContext { } pub fn fetch_data(&mut self) -> u64 { - if self.fetch == false { + if !self.fetch { self.fetch = true; self.data.reverse(); self.data.len() as u64 @@ -163,12 +160,12 @@ pub fn register_datacache_foreign(env: &mut HostEnv, tree_db: Option().unwrap(); - let ret = Some(wasmi::RuntimeValue::I64(context.fetch_data() as i64)); - ret + + Some(wasmi::RuntimeValue::I64(context.fetch_data() as i64)) }, ), ); diff --git a/crates/host/src/host/merkle_helper/merkle.rs b/crates/host/src/host/merkle_helper/merkle.rs index 2bb187748..b27e4111d 100644 --- a/crates/host/src/host/merkle_helper/merkle.rs +++ b/crates/host/src/host/merkle_helper/merkle.rs @@ -81,7 +81,6 @@ impl MerkleContext { let hash = mt.get_root_hash(); let values = hash .chunks(8) - .into_iter() .map(|x| u64::from_le_bytes(x.to_vec().try_into().unwrap())) .collect::>(); let cursor = self.get_root.cursor; @@ -131,7 +130,7 @@ impl MerkleContext { } let v = values[self.data_cursor]; self.data_cursor += 1; - return v; + v } } @@ -212,12 +211,12 @@ pub fn register_merkle_foreign(env: &mut HostEnv, tree_db: Option().unwrap(); - let ret = Some(wasmi::RuntimeValue::I64(context.merkle_get() as i64)); - ret + + Some(wasmi::RuntimeValue::I64(context.merkle_get() as i64)) }, ), ); diff --git a/crates/host/src/host/witness_helper/mod.rs b/crates/host/src/host/witness_helper/mod.rs index f354ee9fd..ce89e2ea3 100644 --- a/crates/host/src/host/witness_helper/mod.rs +++ b/crates/host/src/host/witness_helper/mod.rs @@ -85,7 +85,7 @@ pub fn register_witness_foreign(env: &mut HostEnv, index_map: Rc().unwrap(); - context.witness_insert(args.nth::(0) as u64); + context.witness_insert(args.nth::(0)); None }, ), @@ -99,7 +99,7 @@ pub fn register_witness_foreign(env: &mut HostEnv, index_map: Rc().unwrap(); - context.witness_set_index(args.nth::(0) as u64); + context.witness_set_index(args.nth::(0)); None }, ), @@ -113,7 +113,7 @@ pub fn register_witness_foreign(env: &mut HostEnv, index_map: Rc().unwrap(); - context.witness_indexed_insert(args.nth::(0) as u64); + context.witness_indexed_insert(args.nth::(0)); None }, ), @@ -127,7 +127,7 @@ pub fn register_witness_foreign(env: &mut HostEnv, index_map: Rc().unwrap(); - context.witness_indexed_push(args.nth::(0) as u64); + context.witness_indexed_push(args.nth::(0)); None }, ), @@ -165,7 +165,7 @@ pub fn register_witness_foreign(env: &mut HostEnv, index_map: Rc>(values: &[T]) -> Vec { values - .into_iter() - .map(|v| { - let [v, t] = v.as_ref().split(":").collect::>()[..] else { todo!() }; + .iter() + .flat_map(|v| { + let [v, t] = v.as_ref().split(':').collect::>()[..] else { todo!() }; match t { "i64" => { if v.starts_with("0x") { @@ -19,10 +19,7 @@ pub fn parse_args>(values: &[T]) -> Vec { panic!("bytes input need start with 0x"); } let bytes = hex::decode(String::from(v).trim_start_matches("0x")).unwrap(); - bytes - .into_iter() - .map(|x| u64::from(x)) - .collect::>() + bytes.into_iter().map(u64::from).collect::>() } "bytes-packed" => { if !v.starts_with("0x") { @@ -58,6 +55,5 @@ pub fn parse_args>(values: &[T]) -> Vec { } } }) - .flatten() .collect() } diff --git a/crates/specs/src/configure_table.rs b/crates/specs/src/configure_table.rs index b2484fb18..a62c0a88f 100644 --- a/crates/specs/src/configure_table.rs +++ b/crates/specs/src/configure_table.rs @@ -2,7 +2,7 @@ use serde::Deserialize; use serde::Serialize; // A wasm page size is 64KB -pub const WASM_BYTES_PER_PAGE: u64 = 64 * 1024 as u64; +pub const WASM_BYTES_PER_PAGE: u64 = 64 * 1024_u64; const WASM_32_MAXIMAL_PAGES_DEFAULT: u32 = 65536; diff --git a/crates/specs/src/etable.rs b/crates/specs/src/etable.rs index aa5dd5c2d..6b2c14d11 100644 --- a/crates/specs/src/etable.rs +++ b/crates/specs/src/etable.rs @@ -5,7 +5,6 @@ use std::path::PathBuf; use serde::Deserialize; use serde::Serialize; -use crate::host_function::HostPlugin; use crate::itable::InstructionTable; use crate::itable::InstructionTableEntry; use crate::step::StepInfo; @@ -65,7 +64,7 @@ impl EventTable { let mut fd = std::fs::File::create(path)?; if JSON { - fd.write_all(&serde_json::to_string_pretty(self).unwrap().as_bytes())?; + fd.write_all(serde_json::to_string_pretty(self).unwrap().as_bytes())?; } else { fd.write_all(&bincode::serialize(self).unwrap())?; } @@ -80,7 +79,7 @@ impl EventTable { if JSON { Ok(serde_json::from_slice(&buf).unwrap()) } else { - Ok(bincode::deserialize(&mut buf).unwrap()) + Ok(bincode::deserialize(&buf).unwrap()) } } @@ -95,15 +94,4 @@ impl EventTable { pub fn entries_mut(&mut self) -> &mut Vec { &mut self.0 } - - pub fn filter_foreign_entries(&self, foreign: HostPlugin) -> Vec { - self.0 - .clone() - .into_iter() - .filter(|entry| match entry.step_info { - StepInfo::CallHost { plugin, .. } => plugin == foreign, - _ => false, - }) - .collect::>() - } } diff --git a/crates/specs/src/external_host_call_table/mod.rs b/crates/specs/src/external_host_call_table/mod.rs index 0eb843cf3..3e4b55d74 100644 --- a/crates/specs/src/external_host_call_table/mod.rs +++ b/crates/specs/src/external_host_call_table/mod.rs @@ -20,9 +20,9 @@ impl ExternalHostCallSignature { } } -impl Into for ExternalHostCallSignature { - fn into(self) -> Signature { - match self { +impl From for Signature { + fn from(sig: ExternalHostCallSignature) -> Signature { + match sig { ExternalHostCallSignature::Argument => Signature { params: vec![ValueType::I64], return_type: None, diff --git a/crates/specs/src/imtable.rs b/crates/specs/src/imtable.rs index b66e9f6db..dd075ff2a 100644 --- a/crates/specs/src/imtable.rs +++ b/crates/specs/src/imtable.rs @@ -30,10 +30,6 @@ impl InitMemoryTable { Self(map) } - pub fn to_string(&self) -> String { - serde_json::to_string(&self.0).unwrap() - } - pub fn try_find(&self, ltype: LocationType, offset: u32) -> Option<&InitMemoryTableEntry> { self.0.get(&(ltype, offset)) } diff --git a/crates/specs/src/itable.rs b/crates/specs/src/itable.rs index ded2c9e4d..a4ae73e8d 100644 --- a/crates/specs/src/itable.rs +++ b/crates/specs/src/itable.rs @@ -18,7 +18,9 @@ use crate::types::ValueType; use num_bigint::BigUint; use serde::Deserialize; use serde::Serialize; +use std::fmt; use std::fmt::Debug; +use std::fmt::Display; use std::sync::Arc; use strum_macros::EnumIter; @@ -323,9 +325,9 @@ pub const OPCODE_ARG0_SHIFT: u32 = OPCODE_ARG1_SHIFT + COMMON_RANGE_OFFSET; pub const OPCODE_ARG1_SHIFT: u32 = 64; pub const OPCODE_CELL: usize = 4; -impl Into for &Opcode { - fn into(self) -> BigUint { - let bn = match self { +impl From<&Opcode> for BigUint { + fn from(opcode: &Opcode) -> BigUint { + let bn = match opcode { Opcode::LocalGet { vtype, offset } => { (BigUint::from(OpcodeClass::LocalGet as u64) << OPCODE_CLASS_SHIFT) + (BigUint::from(*vtype as u64) << OPCODE_ARG0_SHIFT) @@ -354,7 +356,7 @@ impl Into for &Opcode { (BigUint::from(OpcodeClass::Return as u64) << OPCODE_CLASS_SHIFT) + (BigUint::from(*drop as u64) << OPCODE_ARG0_SHIFT) + (BigUint::from(keep.len() as u64) << OPCODE_ARG1_SHIFT) - + keep.first().map_or(0u64, |x| VarType::from(*x) as u64) + + keep.first().map_or(0u64, |x| VarType::from(x) as u64) } Opcode::Bin { class, vtype } => { (BigUint::from(OpcodeClass::Bin as u64) << OPCODE_CLASS_SHIFT) @@ -416,7 +418,7 @@ impl Into for &Opcode { Opcode::InternalHostCall { op_index_in_plugin, .. } => { - let opcode_class_plain: OpcodeClassPlain = self.into(); + let opcode_class_plain: OpcodeClassPlain = opcode.into(); (BigUint::from(opcode_class_plain.0) << OPCODE_CLASS_SHIFT) + (BigUint::from(*op_index_in_plugin as u64)) @@ -540,9 +542,9 @@ impl Into for &Opcode { } } -impl Into for &Opcode { - fn into(self) -> OpcodeClass { - match self { +impl From<&Opcode> for OpcodeClass { + fn from(val: &Opcode) -> Self { + match val { Opcode::LocalGet { .. } => OpcodeClass::LocalGet, Opcode::LocalSet { .. } => OpcodeClass::LocalSet, Opcode::LocalTee { .. } => OpcodeClass::LocalTee, @@ -576,11 +578,11 @@ impl Into for &Opcode { } } -impl Into for &Opcode { - fn into(self) -> OpcodeClassPlain { - let class: OpcodeClass = self.into(); +impl From<&Opcode> for OpcodeClassPlain { + fn from(val: &Opcode) -> Self { + let class: OpcodeClass = val.into(); - if let Opcode::InternalHostCall { plugin, .. } = self { + if let Opcode::InternalHostCall { plugin, .. } = val { OpcodeClassPlain(class as usize + (*plugin) as usize) } else { OpcodeClassPlain(class as usize) @@ -597,6 +599,12 @@ pub struct InstructionTableEntry { pub encode: BigUint, } +impl Display for InstructionTableEntry { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", serde_json::to_string(self).unwrap()) + } +} + impl InstructionTableEntry { pub fn new( fid: u32, @@ -614,10 +622,6 @@ impl InstructionTableEntry { encode, } } - - pub fn to_string(&self) -> String { - serde_json::to_string(self).unwrap() - } } // br_table instructions make itable entry discontinuous @@ -653,11 +657,11 @@ impl InstructionTable { } pub fn get(&self, fid: u32, iid: u32) -> &InstructionTableEntry { - &self.0[fid as usize][iid as usize].as_ref().unwrap() + self.0[fid as usize][iid as usize].as_ref().unwrap() } pub fn iter(&self) -> impl Iterator { - self.0.iter().flatten().flatten().filter_map(|x| Some(x)) + self.0.iter().flatten().flatten().filter_map(Some) } pub fn create_brtable(&self) -> BrTable { @@ -686,10 +690,14 @@ impl InstructionTable { pub fn len(&self) -> usize { self.iter().count() } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } } -impl Into for InstructionTableInternal { - fn into(self) -> InstructionTable { - InstructionTable::new(self) +impl From for InstructionTable { + fn from(val: InstructionTableInternal) -> Self { + InstructionTable::new(val) } } diff --git a/crates/specs/src/jtable.rs b/crates/specs/src/jtable.rs index 5c654a6fd..71471c878 100644 --- a/crates/specs/src/jtable.rs +++ b/crates/specs/src/jtable.rs @@ -103,6 +103,10 @@ impl CalledFrameTable { pub fn len(&self) -> usize { self.0.len() } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } } #[derive(Serialize, Deserialize)] @@ -120,7 +124,7 @@ impl FrameTable { if JSON { Ok(serde_json::from_slice(&buf).unwrap()) } else { - Ok(bincode::deserialize(&mut buf).unwrap()) + Ok(bincode::deserialize(&buf).unwrap()) } } @@ -128,7 +132,7 @@ impl FrameTable { let mut fd = std::fs::File::create(path)?; if JSON { - fd.write_all(&serde_json::to_string_pretty(self).unwrap().as_bytes())?; + fd.write_all(serde_json::to_string_pretty(self).unwrap().as_bytes())?; } else { fd.write_all(&bincode::serialize(self).unwrap())?; } diff --git a/crates/specs/src/lib.rs b/crates/specs/src/lib.rs index b7b41ccdf..0314c4b5c 100644 --- a/crates/specs/src/lib.rs +++ b/crates/specs/src/lib.rs @@ -1,9 +1,14 @@ #![feature(trait_alias)] -#![deny(unused_imports)] -#![deny(dead_code)] +#![deny(warnings)] +#![allow( + clippy::assertions_on_constants, + clippy::too_many_arguments, + clippy::type_complexity +)] use std::fs::File; use std::io::Write; +use std::path::Path; use std::path::PathBuf; use std::sync::Arc; @@ -76,11 +81,11 @@ pub struct Tables { impl Tables { pub fn write( &self, - dir: &PathBuf, + dir: &Path, name_of_etable_slice: impl Fn(usize) -> String, name_of_frame_table_slice: impl Fn(usize) -> String, ) { - fn write_file(folder: &PathBuf, filename: &str, buf: &String) { + fn write_file(folder: &Path, filename: &str, buf: &String) { let folder = folder.join(filename); let mut fd = File::create(folder.as_path()).unwrap(); @@ -101,7 +106,7 @@ impl Tables { etable.write(&path).unwrap(); } TableBackend::Json(path) => { - let etable = EventTable::read(&path).unwrap(); + let etable = EventTable::read(path).unwrap(); external_host_call_table.extend(etable.filter_external_host_call_table().0); } }); diff --git a/crates/specs/src/mtable.rs b/crates/specs/src/mtable.rs index 7ece50ce0..11a1d970d 100644 --- a/crates/specs/src/mtable.rs +++ b/crates/specs/src/mtable.rs @@ -92,6 +92,15 @@ impl From for VarType { } } +impl From<&crate::types::ValueType> for VarType { + fn from(v: &crate::types::ValueType) -> Self { + match v { + crate::types::ValueType::I32 => Self::I32, + crate::types::ValueType::I64 => Self::I64, + } + } +} + impl MemoryReadSize { pub fn byte_size(&self) -> u32 { match self { @@ -106,17 +115,14 @@ impl MemoryReadSize { } pub fn is_sign(&self) -> bool { - match self { - MemoryReadSize::U8 - | MemoryReadSize::U16 - | MemoryReadSize::U32 - | MemoryReadSize::I64 => false, - _ => true, - } + !matches!( + self, + MemoryReadSize::U8 | MemoryReadSize::U16 | MemoryReadSize::U32 | MemoryReadSize::I64 + ) } } -#[derive(Clone, Debug, Serialize, Deserialize, Hash, Eq, PartialEq)] +#[derive(Clone, Hash, Eq, PartialEq)] pub struct MemoryTableEntry { pub eid: u32, pub offset: u32, @@ -128,23 +134,14 @@ pub struct MemoryTableEntry { } impl MemoryTableEntry { - pub fn to_string(&self) -> String { - serde_json::to_string(self).unwrap() - } - pub fn is_same_location(&self, other: &MemoryTableEntry) -> bool { self.offset == other.offset && self.ltype == other.ltype } } -#[derive(Default, Debug, Serialize, Deserialize, Clone)] pub struct MTable(Vec); impl MTable { - pub fn to_string(&self) -> String { - serde_json::to_string(self).unwrap() - } - pub fn entries(&self) -> &Vec { &self.0 } diff --git a/crates/specs/src/slice.rs b/crates/specs/src/slice.rs index b6232c40b..704a4d37a 100644 --- a/crates/specs/src/slice.rs +++ b/crates/specs/src/slice.rs @@ -111,9 +111,8 @@ impl Slice { .etable .entries() .par_iter() - .map(|entry| memory_event_of_step(entry)) - .collect::>>() - .concat(); + .flat_map(memory_event_of_step) + .collect::>(); // Use a set to deduplicate let mut set = HashSet::::default(); diff --git a/crates/specs/src/state.rs b/crates/specs/src/state.rs index ee7be588a..927391e07 100644 --- a/crates/specs/src/state.rs +++ b/crates/specs/src/state.rs @@ -94,23 +94,19 @@ impl Default for InitializationState { impl InitializationState { pub fn plain(&self) -> Vec { - let mut v = vec![]; - - v.push(self.eid.clone()); - v.push(self.fid.clone()); - v.push(self.iid.clone()); - v.push(self.frame_id.clone()); - v.push(self.sp.clone()); - - v.push(self.host_public_inputs.clone()); - v.push(self.context_in_index.clone()); - v.push(self.context_out_index.clone()); - v.push(self.external_host_call_call_index.clone()); - - v.push(self.initial_memory_pages.clone()); - v.push(self.maximal_memory_pages.clone()); - - v + vec![ + self.eid.clone(), + self.fid.clone(), + self.iid.clone(), + self.frame_id.clone(), + self.sp.clone(), + self.host_public_inputs.clone(), + self.context_in_index.clone(), + self.context_out_index.clone(), + self.external_host_call_call_index.clone(), + self.initial_memory_pages.clone(), + self.maximal_memory_pages.clone(), + ] } } diff --git a/crates/specs/src/types.rs b/crates/specs/src/types.rs index f7d3427c8..045110c27 100644 --- a/crates/specs/src/types.rs +++ b/crates/specs/src/types.rs @@ -28,9 +28,9 @@ pub enum Value { I64(i64), } -impl Into for Value { - fn into(self) -> VarType { - match self { +impl From for VarType { + fn from(val: Value) -> Self { + match val { Value::I32(_) => VarType::I32, Value::I64(_) => VarType::I64, } diff --git a/crates/zkwasm/src/circuits/etable/allocator.rs b/crates/zkwasm/src/circuits/etable/allocator.rs index c093c0e54..5a70ac6eb 100644 --- a/crates/zkwasm/src/circuits/etable/allocator.rs +++ b/crates/zkwasm/src/circuits/etable/allocator.rs @@ -24,6 +24,7 @@ use halo2_proofs::plonk::Fixed; use halo2_proofs::plonk::VirtualCells; use specs::encode::memory_table::encode_memory_table_entry; use specs::mtable::LocationType; +use std::cmp::Ordering; use std::collections::BTreeMap; use std::marker::PhantomData; @@ -34,11 +35,11 @@ pub(super) trait EventTableCellExpression { impl EventTableCellExpression for AllocatedCell { fn next_expr(&self, meta: &mut VirtualCells<'_, F>) -> Expression { - nextn!(meta, self.col, self.rot + EVENT_TABLE_ENTRY_ROWS as i32) + nextn!(meta, self.col, self.rot + EVENT_TABLE_ENTRY_ROWS) } fn prev_expr(&self, meta: &mut VirtualCells<'_, F>) -> Expression { - nextn!(meta, self.col, self.rot - EVENT_TABLE_ENTRY_ROWS as i32) + nextn!(meta, self.col, self.rot - EVENT_TABLE_ENTRY_ROWS) } } @@ -220,11 +221,13 @@ impl AllocatorFreeCellsProfiler { for (t, (i, j)) in allocator.free_cells.iter() { let v = self.free_cells.get_mut(t).unwrap(); - if *i > v.0 { - v.0 = *i; - v.1 = *j; - } else if *i == v.0 { - v.1 = u32::max(v.1, *j); + match i.cmp(&v.0) { + Ordering::Greater => { + v.0 = *i; + v.1 = *j; + } + Ordering::Equal => v.1 = u32::max(v.1, *j), + Ordering::Less => (), } } @@ -307,7 +310,6 @@ impl EventTableCellAllocator { let init = u32_cell.curr_expr(meta); vec![ (0..2) - .into_iter() .map(|x| u16_cells_le[x].curr_expr(meta) * constant_from!(1u64 << (16 * x))) .fold(init, |acc, x| acc - x) * enable(meta), @@ -332,7 +334,6 @@ impl EventTableCellAllocator { let init = u64_cell.curr_expr(meta); vec![ (0..4) - .into_iter() .map(|x| u16_cells_le[x].curr_expr(meta) * constant_from!(1u64 << (16 * x))) .fold(init, |acc, x| acc - x) * enable(meta), @@ -364,6 +365,7 @@ impl EventTableCellAllocator { let cell = allocator.prepare_alloc_u32_cell(); allocator.free_u32_cells.push(cell); } + #[allow(clippy::reversed_empty_ranges)] for _ in 0..U32_PERMUTATION_CELLS { let cell = allocator.prepare_alloc_u32_permutation_cell(meta, |meta| fixed_curr!(meta, sel)); diff --git a/crates/zkwasm/src/circuits/etable/assign.rs b/crates/zkwasm/src/circuits/etable/assign.rs index 45c278ba1..11d2aa4ed 100644 --- a/crates/zkwasm/src/circuits/etable/assign.rs +++ b/crates/zkwasm/src/circuits/etable/assign.rs @@ -279,7 +279,7 @@ impl EventTableChip { /* * The length of event_table equals 0: without_witness */ - if event_table.0.len() == 0 { + if event_table.0.is_empty() { return Ok(()); } @@ -444,7 +444,7 @@ impl EventTableChip { let op_config = op_configs.get(&((&instruction.opcode).into())).unwrap(); op_config .0 - .assign(&mut ctx, &mut step_status, &entry) + .assign(&mut ctx, &mut step_status, entry) .unwrap(); } @@ -518,7 +518,7 @@ impl EventTableChip { event_table, configure_table, frame_table, - &initialization_state, + initialization_state, post_initialization_state, rest_mops, rest_call_ops, @@ -529,7 +529,7 @@ impl EventTableChip { let post_initialization_state_cells = self .assign_padding_and_post_initialization_state( &mut ctx, - &post_initialization_state, + post_initialization_state, )?; Ok(EventTablePermutationCells { diff --git a/crates/zkwasm/src/circuits/etable/constraint_builder.rs b/crates/zkwasm/src/circuits/etable/constraint_builder.rs index 7822115c0..8d35e15bf 100644 --- a/crates/zkwasm/src/circuits/etable/constraint_builder.rs +++ b/crates/zkwasm/src/circuits/etable/constraint_builder.rs @@ -63,7 +63,7 @@ impl<'a, 'b, F: FieldExt> ConstraintBuilder<'a, 'b, F> { selector: impl Fn(&mut VirtualCells) -> (Expression, Expression), ) { for (name, builder) in self.constraints { - self.meta.create_gate(&name, |meta| { + self.meta.create_gate(name, |meta| { builder(meta) .into_iter() .map(|constraint| { diff --git a/crates/zkwasm/src/circuits/etable/op_configure/op_bin.rs b/crates/zkwasm/src/circuits/etable/op_configure/op_bin.rs index b4f82c712..c7fd43aee 100644 --- a/crates/zkwasm/src/circuits/etable/op_configure/op_bin.rs +++ b/crates/zkwasm/src/circuits/etable/op_configure/op_bin.rs @@ -415,10 +415,8 @@ impl EventTableOpcodeConfig for BinConfig { _ => unreachable!(), }; - self.lhs - .assign(ctx, left.into(), var_type == VarType::I32)?; - self.rhs - .assign(ctx, right.into(), var_type == VarType::I32)?; + self.lhs.assign(ctx, left, var_type == VarType::I32)?; + self.rhs.assign(ctx, right, var_type == VarType::I32)?; let (normalized_lhs, normalized_rhs) = if var_type == VarType::I32 { let normalized_lhs = if left >> 31 == 1 { @@ -434,12 +432,12 @@ impl EventTableOpcodeConfig for BinConfig { (normalized_lhs, normalized_rhs) } else { let normalized_lhs = if left >> 63 == 1 { - u64::MAX as u64 - left + 1 + u64::MAX - left + 1 } else { left }; let normalized_rhs = if right >> 63 == 1 { - u64::MAX as u64 - right + 1 + u64::MAX - right + 1 } else { right }; @@ -545,11 +543,8 @@ impl EventTableOpcodeConfig for BinConfig { _ => {} } - match var_type { - VarType::I32 => { - self.is_i32.assign(ctx, F::one())?; - } - _ => {} + if var_type == VarType::I32 { + self.is_i32.assign(ctx, F::one())?; }; self.memory_table_lookup_stack_read_rhs.assign( diff --git a/crates/zkwasm/src/circuits/etable/op_configure/op_bin_shift.rs b/crates/zkwasm/src/circuits/etable/op_configure/op_bin_shift.rs index afca4c7e7..85a8c485f 100644 --- a/crates/zkwasm/src/circuits/etable/op_configure/op_bin_shift.rs +++ b/crates/zkwasm/src/circuits/etable/op_configure/op_bin_shift.rs @@ -398,7 +398,7 @@ impl EventTableOpcodeConfig for BinShiftConfig { BigUint::from(1u64) << 32usize }; - self.lhs.assign(ctx, left.into(), !is_eight_bytes)?; + self.lhs.assign(ctx, left, !is_eight_bytes)?; self.rhs.assign(ctx, right)?; self.rhs_round .assign(ctx, F::from((right & 0xffff) / size))?; diff --git a/crates/zkwasm/src/circuits/etable/op_configure/op_br.rs b/crates/zkwasm/src/circuits/etable/op_configure/op_br.rs index 4bf8ec6b8..83b15c085 100644 --- a/crates/zkwasm/src/circuits/etable/op_configure/op_br.rs +++ b/crates/zkwasm/src/circuits/etable/op_configure/op_br.rs @@ -105,7 +105,7 @@ impl EventTableOpcodeConfig for BrConfig { self.drop_cell.assign(ctx, F::from(*drop as u64))?; - if keep.len() > 0 { + if !keep.is_empty() { let keep_type: VarType = keep[0].into(); self.keep_cell.assign(ctx, F::one())?; diff --git a/crates/zkwasm/src/circuits/etable/op_configure/op_br_if.rs b/crates/zkwasm/src/circuits/etable/op_configure/op_br_if.rs index 72f926444..fa8ce289a 100644 --- a/crates/zkwasm/src/circuits/etable/op_configure/op_br_if.rs +++ b/crates/zkwasm/src/circuits/etable/op_configure/op_br_if.rs @@ -168,7 +168,7 @@ impl EventTableOpcodeConfig for BrIfConfig { self.drop_cell.assign(ctx, F::from(*drop as u64))?; - if keep.len() > 0 { + if !keep.is_empty() { let keep_type: VarType = keep[0].into(); self.keep_cell.assign(ctx, F::one())?; diff --git a/crates/zkwasm/src/circuits/etable/op_configure/op_br_if_eqz.rs b/crates/zkwasm/src/circuits/etable/op_configure/op_br_if_eqz.rs index 12cfd4202..75166f8a9 100644 --- a/crates/zkwasm/src/circuits/etable/op_configure/op_br_if_eqz.rs +++ b/crates/zkwasm/src/circuits/etable/op_configure/op_br_if_eqz.rs @@ -164,7 +164,7 @@ impl EventTableOpcodeConfig for BrIfEqzConfig { self.drop_cell.assign(ctx, F::from(*drop as u64))?; - if keep.len() > 0 { + if !keep.is_empty() { let keep_type: VarType = keep[0].into(); self.keep_cell.assign(ctx, F::one())?; diff --git a/crates/zkwasm/src/circuits/etable/op_configure/op_br_table.rs b/crates/zkwasm/src/circuits/etable/op_configure/op_br_table.rs index 413264908..a1808977e 100644 --- a/crates/zkwasm/src/circuits/etable/op_configure/op_br_table.rs +++ b/crates/zkwasm/src/circuits/etable/op_configure/op_br_table.rs @@ -211,7 +211,7 @@ impl EventTableOpcodeConfig for BrTableConfig { index, )?; - if keep.len() > 0 { + if !keep.is_empty() { let keep_type: VarType = keep[0].into(); self.keep.assign(ctx, F::one())?; @@ -260,8 +260,7 @@ impl EventTableOpcodeConfig for BrTableConfig { targets_len - index - 1 } else { index - targets_len - } - .into(), + }, )?; self.br_table_lookup.assign_bn( diff --git a/crates/zkwasm/src/circuits/etable/op_configure/op_conversion.rs b/crates/zkwasm/src/circuits/etable/op_configure/op_conversion.rs index 6be6ea66f..0cebbd0b3 100644 --- a/crates/zkwasm/src/circuits/etable/op_configure/op_conversion.rs +++ b/crates/zkwasm/src/circuits/etable/op_configure/op_conversion.rs @@ -253,7 +253,7 @@ impl EventTableOpcodeConfig for ConversionConfig { VarType::I32, *result as u64, VarType::I64, - (u64::MAX << 32) as u64, + u64::MAX << 32, 1 << 31, ) } @@ -295,7 +295,7 @@ impl EventTableOpcodeConfig for ConversionConfig { VarType::I64, *result as u64, VarType::I64, - (u64::MAX << 8) as u64, + u64::MAX << 8, 1 << 7, ) } @@ -309,7 +309,7 @@ impl EventTableOpcodeConfig for ConversionConfig { VarType::I64, *result as u64, VarType::I64, - (u64::MAX << 16) as u64, + u64::MAX << 16, 1 << 15, ) } @@ -323,7 +323,7 @@ impl EventTableOpcodeConfig for ConversionConfig { VarType::I64, *result as u64, VarType::I64, - (u64::MAX << 32) as u64, + u64::MAX << 32, 1 << 31, ) } diff --git a/crates/zkwasm/src/circuits/etable/op_configure/op_load.rs b/crates/zkwasm/src/circuits/etable/op_configure/op_load.rs index cbb25abdf..5679f2ba1 100644 --- a/crates/zkwasm/src/circuits/etable/op_configure/op_load.rs +++ b/crates/zkwasm/src/circuits/etable/op_configure/op_load.rs @@ -469,19 +469,17 @@ impl EventTableOpcodeConfig for LoadConfig { let tailing_bits = inner_byte_index * 8; let picked_bits = len * 8; let load_value: BigUint = (BigUint::from(block_value2) << 64) + block_value1; - let tailing: u64 = load_value.to_u64_digits().first().unwrap_or(&0u64).clone() + let tailing: u64 = *load_value.to_u64_digits().first().unwrap_or(&0u64) & ((1 << tailing_bits) - 1); - let picked: u64 = ((&load_value >> tailing_bits) + let picked: u64 = *((&load_value >> tailing_bits) & ((BigUint::from(1u64) << picked_bits) - 1u64)) .to_u64_digits() .first() - .unwrap_or(&0u64) - .clone(); - let leading: u64 = (load_value >> (picked_bits + tailing_bits)) + .unwrap_or(&0u64); + let leading: u64 = *(load_value >> (picked_bits + tailing_bits)) .to_u64_digits() .first() - .unwrap_or(&0u64) - .clone(); + .unwrap_or(&0u64); self.load_tailing.assign(ctx, tailing)?; self.load_tailing_diff diff --git a/crates/zkwasm/src/circuits/etable/op_configure/op_memory_size.rs b/crates/zkwasm/src/circuits/etable/op_configure/op_memory_size.rs index e6c9085b8..2e4abc09f 100644 --- a/crates/zkwasm/src/circuits/etable/op_configure/op_memory_size.rs +++ b/crates/zkwasm/src/circuits/etable/op_configure/op_memory_size.rs @@ -76,7 +76,7 @@ impl EventTableOpcodeConfig for MemorySizeConfig { step.current.sp, LocationType::Stack, true, - step.current.allocated_memory_pages as u32 as u64, + step.current.allocated_memory_pages as u64, )?; Ok(()) diff --git a/crates/zkwasm/src/circuits/etable/op_configure/op_rel.rs b/crates/zkwasm/src/circuits/etable/op_configure/op_rel.rs index a43edc6c2..9702d8aa1 100644 --- a/crates/zkwasm/src/circuits/etable/op_configure/op_rel.rs +++ b/crates/zkwasm/src/circuits/etable/op_configure/op_rel.rs @@ -408,10 +408,10 @@ impl EventTableOpcodeConfig for RelConfig { } self.lhs - .assign(ctx, lhs.into(), var_type == VarType::I32, op_is_sign)?; + .assign(ctx, lhs, var_type == VarType::I32, op_is_sign)?; self.rhs - .assign(ctx, rhs.into(), var_type == VarType::I32, op_is_sign)?; - self.diff.assign(ctx, diff.into())?; + .assign(ctx, rhs, var_type == VarType::I32, op_is_sign)?; + self.diff.assign(ctx, diff)?; if diff != 0 { self.diff_inv.assign(ctx, step.field_helper.invert(diff))?; diff --git a/crates/zkwasm/src/circuits/etable/op_configure/op_return.rs b/crates/zkwasm/src/circuits/etable/op_configure/op_return.rs index a26896bbb..0a9c6f3e2 100644 --- a/crates/zkwasm/src/circuits/etable/op_configure/op_return.rs +++ b/crates/zkwasm/src/circuits/etable/op_configure/op_return.rs @@ -146,7 +146,7 @@ impl EventTableOpcodeConfig for ReturnConfig { self.drop.assign(ctx, F::from(*drop as u64))?; - if keep_values.len() == 0 { + if keep_values.is_empty() { self.keep.assign(ctx, 0.into())?; } else { self.keep.assign(ctx, 1.into())?; @@ -206,7 +206,7 @@ impl EventTableOpcodeConfig for ReturnConfig { fn memory_writing_ops(&self, entry: &EventTableEntry) -> u32 { match &entry.step_info { StepInfo::Return { keep, .. } => { - if keep.len() > 0 { + if !keep.is_empty() { assert!(keep.len() == 1); 1 } else { diff --git a/crates/zkwasm/src/circuits/etable/op_configure/op_store.rs b/crates/zkwasm/src/circuits/etable/op_configure/op_store.rs index a48ca62a4..b08a7c9c2 100644 --- a/crates/zkwasm/src/circuits/etable/op_configure/op_store.rs +++ b/crates/zkwasm/src/circuits/etable/op_configure/op_store.rs @@ -501,19 +501,17 @@ impl EventTableOpcodeConfig for StoreConfig { let picked_bits = len * 8; let load_value: BigUint = (BigUint::from(pre_block_value2) << 64) + pre_block_value1; - let tailing: u64 = load_value.to_u64_digits().first().unwrap_or(&0u64).clone() + let tailing: u64 = *load_value.to_u64_digits().first().unwrap_or(&0u64) & ((1 << tailing_bits) - 1); - let picked: u64 = ((&load_value >> tailing_bits) + let picked: u64 = *((&load_value >> tailing_bits) & ((BigUint::from(1u64) << picked_bits) - 1u64)) .to_u64_digits() .first() - .unwrap_or(&0u64) - .clone(); - let leading: u64 = (load_value >> (picked_bits + tailing_bits)) + .unwrap_or(&0u64); + let leading: u64 = *(load_value >> (picked_bits + tailing_bits)) .to_u64_digits() .first() - .unwrap_or(&0u64) - .clone(); + .unwrap_or(&0u64); self.load_tailing.assign(ctx, tailing)?; self.load_tailing_diff @@ -562,7 +560,7 @@ impl EventTableOpcodeConfig for StoreConfig { step.current.sp + 1, LocationType::Stack, vtype == VarType::I32, - value as u64, + value, )?; self.memory_table_lookup_stack_read_pos.assign( diff --git a/crates/zkwasm/src/circuits/etable/op_configure/op_unary.rs b/crates/zkwasm/src/circuits/etable/op_configure/op_unary.rs index 2b1a9a001..9874be2eb 100644 --- a/crates/zkwasm/src/circuits/etable/op_configure/op_unary.rs +++ b/crates/zkwasm/src/circuits/etable/op_configure/op_unary.rs @@ -306,12 +306,11 @@ impl EventTableOpcodeConfig for UnaryConfig { let boundary = max.checked_shr(1 + *result as u32).unwrap_or(0) as u64; let tail = *operand ^ boundary; - self.lookup_pow_modulus - .assign(ctx, F::from(boundary as u64))?; + self.lookup_pow_modulus.assign(ctx, F::from(boundary))?; self.aux1.assign(ctx, tail)?; // If `operand = 0``, then `boundary == tail == 0`` and therefore `- 1` will panic in debug mode. // Since `aux2`` is useless when `operand = 0`, we give 0. - let aux2 = (boundary - tail).checked_sub(1).unwrap_or(0); + let aux2 = (boundary - tail).saturating_sub(1); self.aux2.assign(ctx, aux2)?; if boundary != 0 { self.lookup_pow_modulus.assign(ctx, boundary.into())?; diff --git a/crates/zkwasm/src/circuits/image_table/assign.rs b/crates/zkwasm/src/circuits/image_table/assign.rs index 18c20bba5..30afadfed 100644 --- a/crates/zkwasm/src/circuits/image_table/assign.rs +++ b/crates/zkwasm/src/circuits/image_table/assign.rs @@ -5,6 +5,7 @@ use halo2_proofs::plonk::Error; use rayon::iter::IndexedParallelIterator; use rayon::iter::ParallelIterator; use rayon::prelude::ParallelSlice; +use rayon::slice::ParallelSliceMut; use specs::jtable::INHERITED_FRAME_TABLE_ENTRIES; use super::ImageTableChip; @@ -125,23 +126,21 @@ impl ImageTableChip { let init_memory_handler = |base_offset| { const THREAD: usize = 4; - let chunk_size = if image_table.init_memory_entries.len() == 0 { + let chunk_size = if image_table.init_memory_entries.is_empty() { 1 } else { (image_table.init_memory_entries.len() + THREAD - 1) / THREAD }; let mut cells = Vec::with_capacity(image_table.init_memory_entries.len()); - unsafe { - cells.set_len(image_table.init_memory_entries.len()); - } - let cells_ref = &cells; + let remaining = cells.spare_capacity_mut(); image_table .init_memory_entries .par_chunks(chunk_size) + .zip(remaining.par_chunks_mut(chunk_size)) .enumerate() - .for_each(|(chunk_index, entries)| { + .for_each(|(chunk_index, (entries, cells))| { let mut ctx = Context::new(region); // start from 'base_offset" because 'encode_compilation_table_values' have inserted an empty at the beginning. ctx.offset = base_offset + chunk_index * chunk_size; @@ -149,14 +148,14 @@ impl ImageTableChip { entries.iter().enumerate().for_each(|(index, entry)| { let cell = assign!(ctx, self.config.col, *entry).unwrap(); - let cells = cells_ref.as_ptr(); - unsafe { - let cells = cells as *mut AssignedCell; - cells.add(chunk_index * chunk_size + index).write(cell); - } + cells[index].write(cell); }); }); + unsafe { + cells.set_len(image_table.init_memory_entries.len()); + } + Ok(cells) }; diff --git a/crates/zkwasm/src/circuits/jtable/assign.rs b/crates/zkwasm/src/circuits/jtable/assign.rs index 2f2e7588a..d448fcca5 100644 --- a/crates/zkwasm/src/circuits/jtable/assign.rs +++ b/crates/zkwasm/src/circuits/jtable/assign.rs @@ -186,10 +186,12 @@ impl JumpTableChip { ctx.step(FrameTableValueOffset::Max as usize); } - Ok(cells.try_into().expect(&format!( - "The number of inherited frame entries should be {}", - INHERITED_FRAME_TABLE_ENTRIES - ))) + Ok(cells.try_into().unwrap_or_else(|_| { + panic!( + "The number of inherited frame entries should be {}", + INHERITED_FRAME_TABLE_ENTRIES + ) + })) } fn assign_frame_table_entries( @@ -236,7 +238,7 @@ impl JumpTableChip { || Ok(F::one()), )?; - *rest_return_ops -= 1 as u32; + *rest_return_ops -= 1u32; } *rest_call_ops -= 1; diff --git a/crates/zkwasm/src/circuits/mod.rs b/crates/zkwasm/src/circuits/mod.rs index fc836a827..23be57072 100644 --- a/crates/zkwasm/src/circuits/mod.rs +++ b/crates/zkwasm/src/circuits/mod.rs @@ -77,8 +77,8 @@ impl OngoingCircuit { if etable_entires > etable_capacity { return Err(BuildingCircuitError::EtableEntriesExceedLimit( - etable_entires as u32, - etable_capacity as u32, + etable_entires, + etable_capacity, k, )); } @@ -125,8 +125,8 @@ impl LastSliceCircuit { if etable_entires > etable_capacity { return Err(BuildingCircuitError::EtableEntriesExceedLimit( - etable_entires as u32, - etable_capacity as u32, + etable_entires, + etable_capacity, k, )); } diff --git a/crates/zkwasm/src/circuits/mtable/allocator.rs b/crates/zkwasm/src/circuits/mtable/allocator.rs index 7236686eb..8560c725c 100644 --- a/crates/zkwasm/src/circuits/mtable/allocator.rs +++ b/crates/zkwasm/src/circuits/mtable/allocator.rs @@ -27,11 +27,11 @@ pub(super) trait MemoryTableCellExpression { impl MemoryTableCellExpression for AllocatedCell { fn next_expr(&self, meta: &mut VirtualCells<'_, F>) -> Expression { - nextn!(meta, self.col, self.rot + MEMORY_TABLE_ENTRY_ROWS as i32) + nextn!(meta, self.col, self.rot + MEMORY_TABLE_ENTRY_ROWS) } fn prev_expr(&self, meta: &mut VirtualCells<'_, F>) -> Expression { - nextn!(meta, self.col, self.rot - MEMORY_TABLE_ENTRY_ROWS as i32) + nextn!(meta, self.col, self.rot - MEMORY_TABLE_ENTRY_ROWS) } } @@ -137,7 +137,6 @@ impl MemoryTableCellAllocator { let init = u64_cell.curr_expr(meta); vec![ (0..4) - .into_iter() .map(|x| u16_cells_le[x].curr_expr(meta) * constant_from!(1u64 << (16 * x))) .fold(init, |acc, x| acc - x) * enable(meta), @@ -156,13 +155,7 @@ impl MemoryTableCellAllocator { rtable: &RangeTableConfig, cols: &mut impl Iterator>, ) -> Self { - let mut allocator = Self::_new( - meta, - sel.clone(), - (l_0, l_active, l_active_last), - rtable, - cols, - ); + let mut allocator = Self::_new(meta, sel, (l_0, l_active, l_active_last), rtable, cols); for _ in 0..U32_CELLS { let cell = allocator.prepare_alloc_u32_cell(); allocator.free_u32_cells.push(cell); diff --git a/crates/zkwasm/src/circuits/mtable/assign.rs b/crates/zkwasm/src/circuits/mtable/assign.rs index 227762b10..95abaf5c4 100644 --- a/crates/zkwasm/src/circuits/mtable/assign.rs +++ b/crates/zkwasm/src/circuits/mtable/assign.rs @@ -238,7 +238,7 @@ impl MemoryTableChip { }; const THREAD: usize = 8; - let chunk_size = if mtable.0.len() == 0 { + let chunk_size = if mtable.0.is_empty() { 1 } else { (mtable.0.len() + THREAD - 1) / THREAD @@ -384,7 +384,7 @@ impl MemoryTableChip { let rest_mops_cell = self.constrain_rest_mops_permutation(&mut ctx, rest_mops)?; - self.assign_entries(region, &mtable, rest_mops, rest_memory_finalize_ops)?; + self.assign_entries(region, mtable, rest_mops, rest_memory_finalize_ops)?; cfg_if::cfg_if! { if #[cfg(feature="continuation")] { diff --git a/crates/zkwasm/src/circuits/post_image_table/continuation.rs b/crates/zkwasm/src/circuits/post_image_table/continuation.rs index a8c139677..827d5c79f 100644 --- a/crates/zkwasm/src/circuits/post_image_table/continuation.rs +++ b/crates/zkwasm/src/circuits/post_image_table/continuation.rs @@ -348,7 +348,7 @@ impl PostImageTableChip { if memory_finalized_set .contains(&image_table_offset_to_memory_location(offset)) { - rest_memory_writing_ops = rest_memory_writing_ops - F::one(); + rest_memory_writing_ops -= F::one(); } offset += 1; diff --git a/crates/zkwasm/src/circuits/rtable.rs b/crates/zkwasm/src/circuits/rtable.rs index 1cab0a03a..2027e5c19 100644 --- a/crates/zkwasm/src/circuits/rtable.rs +++ b/crates/zkwasm/src/circuits/rtable.rs @@ -162,28 +162,28 @@ impl RangeTableChip { table.assign_cell( || "range table", self.config.op_table.op, - offset as usize, + offset, || Ok(F::from(op as u64)), )?; table.assign_cell( || "range table", self.config.op_table.left, - offset as usize, + offset, || Ok(F::from(left as u64)), )?; table.assign_cell( || "range table", self.config.op_table.right, - offset as usize, + offset, || Ok(F::from(right as u64)), )?; table.assign_cell( || "range table", self.config.op_table.result, - offset as usize, + offset, || Ok(F::from(op.eval(left as u64, right as u64))), )?; @@ -196,28 +196,28 @@ impl RangeTableChip { table.assign_cell( || "range table", self.config.op_table.op, - offset as usize, + offset, || Ok(F::from(BitTableOp::Popcnt.index() as u64)), )?; table.assign_cell( || "range table", self.config.op_table.left, - offset as usize, + offset, || Ok(F::from(left as u64)), )?; table.assign_cell( || "range table", self.config.op_table.right, - offset as usize, + offset, || Ok(F::from(0)), )?; table.assign_cell( || "range table", self.config.op_table.result, - offset as usize, + offset, || Ok(F::from(left.count_ones() as u64)), )?; diff --git a/crates/zkwasm/src/circuits/utils/bit.rs b/crates/zkwasm/src/circuits/utils/bit.rs index 3f4858b01..6de7c95e7 100644 --- a/crates/zkwasm/src/circuits/utils/bit.rs +++ b/crates/zkwasm/src/circuits/utils/bit.rs @@ -25,11 +25,7 @@ impl BitColumn { let col = cols.next().unwrap(); meta.create_gate("bit column", |meta| { - vec![ - curr!(meta, col.clone()) - * (constant_from!(1) - curr!(meta, col.clone())) - * enable(meta), - ] + vec![curr!(meta, col) * (constant_from!(1) - curr!(meta, col)) * enable(meta)] }); Self { diff --git a/crates/zkwasm/src/circuits/utils/image_table.rs b/crates/zkwasm/src/circuits/utils/image_table.rs index 8a4e725a7..f8d64d360 100644 --- a/crates/zkwasm/src/circuits/utils/image_table.rs +++ b/crates/zkwasm/src/circuits/utils/image_table.rs @@ -72,7 +72,7 @@ pub fn image_table_offset_to_memory_location(offset: usize) -> (LocationType, u3 } offset -= GLOBAL_CAPABILITY; - return (LocationType::Heap, offset as u32); + (LocationType::Heap, offset as u32) } /* @@ -359,7 +359,7 @@ pub(crate) fn encode_compilation_table_values( unsafe { let addr = addr as *mut F; - *addr.offset((pos + 1) as isize) = *entry; + *addr.add(pos + 1) = *entry; } } }); @@ -374,7 +374,7 @@ pub(crate) fn encode_compilation_table_values( page_capability, ); - let layouter = assigner + assigner .exec::<_, Error>( initialization_state_handler, inherited_frame_entries_handler, @@ -383,9 +383,7 @@ pub(crate) fn encode_compilation_table_values( padding_handler, init_memory_entries_handler, ) - .unwrap(); - - layouter + .unwrap() } pub(crate) trait EncodeImageTable { diff --git a/crates/zkwasm/src/circuits/utils/row_diff.rs b/crates/zkwasm/src/circuits/utils/row_diff.rs index b5d56d569..f9cef9a67 100644 --- a/crates/zkwasm/src/circuits/utils/row_diff.rs +++ b/crates/zkwasm/src/circuits/utils/row_diff.rs @@ -40,7 +40,7 @@ impl RowDiffConfig { let inv = curr!(meta, inv); let same = curr!(meta, same); vec![ - diff.clone() * inv.clone() + same.clone() - constant_from!(1), + diff.clone() * inv + same.clone() - constant_from!(1), diff * same, ] .into_iter() @@ -64,8 +64,8 @@ impl RowDiffConfig { data: F, diff: F, ) -> Result<(), Error> { - let offset = if offset_force.is_some() { - offset_force.unwrap() + let offset = if let Some(offset_force) = offset_force { + offset_force } else { ctx.offset }; diff --git a/crates/zkwasm/src/circuits/utils/table_entry.rs b/crates/zkwasm/src/circuits/utils/table_entry.rs index d76df95a1..15080481f 100644 --- a/crates/zkwasm/src/circuits/utils/table_entry.rs +++ b/crates/zkwasm/src/circuits/utils/table_entry.rs @@ -1,6 +1,7 @@ +use crate::circuits::config::common_range_max; +use crate::runtime::memory_event_of_step; use rayon::iter::IntoParallelRefIterator; use rayon::iter::ParallelIterator; -use serde::Serialize; use specs::etable::EventTable; use specs::etable::EventTableEntry; use specs::mtable::AccessType; @@ -10,16 +11,8 @@ use specs::mtable::MemoryTableEntry; use std::cmp::Ordering; use std::collections::HashMap; use std::collections::HashSet; -use std::env; -use std::io::Write; -use std::path::PathBuf; - -use crate::circuits::config::common_range_max; -use crate::runtime::memory_event_of_step; -#[derive(Clone, Debug, Serialize)] pub(in crate::circuits) struct MemoryWritingEntry { - index: usize, pub(in crate::circuits) entry: MemoryTableEntry, pub(in crate::circuits) end_eid: u32, } @@ -30,7 +23,6 @@ impl MemoryWritingEntry { } } -#[derive(Debug, Serialize)] pub struct MemoryWritingTable(pub(in crate::circuits) Vec); impl MemoryWritingTable { @@ -60,36 +52,31 @@ impl MemoryWritingTable { } else { common_range_max(k) }; - let mut index = 0; let mut entries: Vec = value .entries() .iter() .filter_map(|entry| { if entry.atype != AccessType::Read { - let entry = Some(MemoryWritingEntry { - index, + Some(MemoryWritingEntry { entry: entry.clone(), end_eid: maximal_eid, - }); - - index += 1; - - entry + }) } else { None } }) .collect(); - let entries_next = entries.clone(); - let next_iter = entries_next.iter().skip(1); + let mut iter = entries.iter_mut().peekable(); - entries.iter_mut().zip(next_iter).for_each(|(curr, next)| { - if curr.is_same_memory_address(next) { - curr.end_eid = next.entry.eid; + while let Some(entry) = iter.next() { + if let Some(next_entry) = iter.peek() { + if entry.is_same_memory_address(next_entry) { + entry.end_eid = next_entry.entry.eid; + } } - }); + } // FIXME: create_memory_table pushed a lot of meaningless Stack init. Fix it elegantly. let entries = entries @@ -120,38 +107,19 @@ impl MemoryWritingTable { mapping } - - pub fn write_json(&self, dir: Option) { - fn write_file(folder: &PathBuf, filename: &str, buf: &String) { - let mut folder = folder.clone(); - folder.push(filename); - let mut fd = std::fs::File::create(folder.as_path()).unwrap(); - folder.pop(); - - fd.write(buf.as_bytes()).unwrap(); - } - - let mtable = serde_json::to_string_pretty(self).unwrap(); - - let dir = dir.unwrap_or(env::current_dir().unwrap()); - write_file(&dir, "memory_writing_table.json", &mtable); - } } -#[derive(Debug)] pub struct MemoryRWEntry { pub entry: MemoryTableEntry, pub start_eid: u32, pub end_eid: u32, } -#[derive(Debug)] pub struct EventTableEntryWithMemoryInfo { pub eentry: EventTableEntry, pub memory_rw_entires: Vec, } -#[derive(Debug)] pub(crate) struct EventTableWithMemoryInfo( pub(in crate::circuits) Vec, ); diff --git a/crates/zkwasm/src/circuits/zkwasm_circuit/mod.rs b/crates/zkwasm/src/circuits/zkwasm_circuit/mod.rs index 9af6e7846..2fc96a627 100644 --- a/crates/zkwasm/src/circuits/zkwasm_circuit/mod.rs +++ b/crates/zkwasm/src/circuits/zkwasm_circuit/mod.rs @@ -62,11 +62,7 @@ use super::post_image_table::PostImageTableConfig; use super::LastSliceCircuit; use super::OngoingCircuit; -pub const VAR_COLUMNS: usize = if cfg!(feature = "continuation") { - 40 -} else { - 40 -}; +pub const VAR_COLUMNS: usize = 40; // Reserve 128 rows(greater than step size of all tables) to keep usable rows away from // blind rows and range checking rows. diff --git a/crates/zkwasm/src/foreign/context/circuits/assign.rs b/crates/zkwasm/src/foreign/context/circuits/assign.rs index a7f36225c..bf02a4712 100644 --- a/crates/zkwasm/src/foreign/context/circuits/assign.rs +++ b/crates/zkwasm/src/foreign/context/circuits/assign.rs @@ -21,8 +21,8 @@ impl ContextContHelperTableChip { pub fn assign( &self, layouter: impl Layouter, - inputs: &Vec, - outputs: &Vec, + inputs: &[u64], + outputs: &[u64], ) -> Result<(), Error> { layouter.assign_region( || "context cont helper assign", diff --git a/crates/zkwasm/src/foreign/context/circuits/mod.rs b/crates/zkwasm/src/foreign/context/circuits/mod.rs index 70f3ca50e..6822f9fd3 100644 --- a/crates/zkwasm/src/foreign/context/circuits/mod.rs +++ b/crates/zkwasm/src/foreign/context/circuits/mod.rs @@ -8,7 +8,7 @@ use halo2_proofs::plonk::Fixed; pub mod assign; pub mod config; -pub const CONTEXT_FOREIGN_TABLE_KEY: &'static str = "wasm-context-helper-table"; +pub const CONTEXT_FOREIGN_TABLE_KEY: &str = "wasm-context-helper-table"; #[derive(Clone)] pub struct ContextContHelperTableConfig { diff --git a/crates/zkwasm/src/foreign/context/etable_op_configure.rs b/crates/zkwasm/src/foreign/context/etable_op_configure.rs index a520576a5..ec021936d 100644 --- a/crates/zkwasm/src/foreign/context/etable_op_configure.rs +++ b/crates/zkwasm/src/foreign/context/etable_op_configure.rs @@ -248,7 +248,7 @@ impl EventTableOpcodeConfig for ETableContextHelperTableConfig { assert_eq!(*plugin, HostPlugin::Context); - return *op_index_in_plugin == Op::ReadContext as usize; + *op_index_in_plugin == Op::ReadContext as usize } _ => unreachable!(), } @@ -271,7 +271,7 @@ impl EventTableOpcodeConfig for ETableContextHelperTableConfig { assert_eq!(*plugin, HostPlugin::Context); - return *op_index_in_plugin == Op::WriteContext as usize; + *op_index_in_plugin == Op::WriteContext as usize } _ => unreachable!(), } diff --git a/crates/zkwasm/src/foreign/context/mod.rs b/crates/zkwasm/src/foreign/context/mod.rs index ba2acfab0..6c590b821 100644 --- a/crates/zkwasm/src/foreign/context/mod.rs +++ b/crates/zkwasm/src/foreign/context/mod.rs @@ -21,7 +21,7 @@ impl ContextOutput { for value in &self.0 { let bytes = value.to_le_bytes(); let s = hex::encode(bytes); - fd.write_all(&s.as_bytes())?; + fd.write_all(s.as_bytes())?; } fd.write_all(":bytes-packed".as_bytes())?; diff --git a/crates/zkwasm/src/foreign/context/runtime.rs b/crates/zkwasm/src/foreign/context/runtime.rs index 308e51bc6..9eddce7c4 100644 --- a/crates/zkwasm/src/foreign/context/runtime.rs +++ b/crates/zkwasm/src/foreign/context/runtime.rs @@ -17,7 +17,7 @@ struct Context { impl Context { fn new(context_input: Vec) -> Self { - let mut inputs = context_input.clone(); + let mut inputs = context_input; inputs.reverse(); Context { diff --git a/crates/zkwasm/src/foreign/wasm_input_helper/circuits/mod.rs b/crates/zkwasm/src/foreign/wasm_input_helper/circuits/mod.rs index daf916763..7839312ad 100644 --- a/crates/zkwasm/src/foreign/wasm_input_helper/circuits/mod.rs +++ b/crates/zkwasm/src/foreign/wasm_input_helper/circuits/mod.rs @@ -7,7 +7,7 @@ use halo2_proofs::plonk::Instance; pub mod config; -pub const WASM_INPUT_FOREIGN_TABLE_KEY: &'static str = "wasm-input-helper-table"; +pub const WASM_INPUT_FOREIGN_TABLE_KEY: &str = "wasm-input-helper-table"; #[derive(Clone)] pub struct WasmInputHelperTableConfig { diff --git a/crates/zkwasm/src/foreign/wasm_input_helper/etable_op_configure.rs b/crates/zkwasm/src/foreign/wasm_input_helper/etable_op_configure.rs index 5c4ea9e22..c9dd5ab14 100644 --- a/crates/zkwasm/src/foreign/wasm_input_helper/etable_op_configure.rs +++ b/crates/zkwasm/src/foreign/wasm_input_helper/etable_op_configure.rs @@ -196,7 +196,7 @@ impl EventTableOpcodeConfig for ETableWasmInputHelperTableConfig assert_eq!(arg_type, VarType::I32); assert_eq!(ret_type, VarType::I64); - let is_public = *args.get(0).unwrap() == 1; + let is_public = *args.first().unwrap() == 1; let value = ret_val.unwrap(); self.is_wasm_input_op.assign_bool(ctx, true)?; @@ -219,7 +219,7 @@ impl EventTableOpcodeConfig for ETableWasmInputHelperTableConfig step.current.sp + 1, LocationType::Stack, true, - *args.get(0).unwrap(), + *args.first().unwrap(), )?; self.lookup_write_stack.assign( diff --git a/crates/zkwasm/src/foreign/wasm_input_helper/runtime.rs b/crates/zkwasm/src/foreign/wasm_input_helper/runtime.rs index 56d7f7dcd..472c8bfb8 100644 --- a/crates/zkwasm/src/foreign/wasm_input_helper/runtime.rs +++ b/crates/zkwasm/src/foreign/wasm_input_helper/runtime.rs @@ -54,15 +54,13 @@ impl Context { pub fn wasm_input(&mut self, arg: i32) -> u64 { assert!(arg == 0 || arg == 1); - let input = if arg == 1 { + if arg == 1 { let value = self.pop_public(); self.push_public(value); value } else { self.pop_private() - }; - - input + } } pub fn wasm_output(&mut self, value: u64) { diff --git a/crates/zkwasm/src/foreign/wasm_input_helper/test.rs b/crates/zkwasm/src/foreign/wasm_input_helper/test.rs index 10577fba6..35036988c 100644 --- a/crates/zkwasm/src/foreign/wasm_input_helper/test.rs +++ b/crates/zkwasm/src/foreign/wasm_input_helper/test.rs @@ -17,7 +17,7 @@ mod tests { let public_inputs = vec![9]; let private_inputs = vec![]; - let wasm = wabt::wat2wasm(&textual_repr).expect("failed to parse wat"); + let wasm = wabt::wat2wasm(textual_repr).expect("failed to parse wat"); test_circuit_with_env( 18, @@ -52,7 +52,7 @@ mod tests { (export "zkwasm" (func 1))) "#; - let wasm = wabt::wat2wasm(&textual_repr).expect("failed to parse wat"); + let wasm = wabt::wat2wasm(textual_repr).expect("failed to parse wat"); let private_inputs = vec![]; let public_inputs = vec![1, 2]; diff --git a/crates/zkwasm/src/lib.rs b/crates/zkwasm/src/lib.rs index e59c66dfb..d4ee01cad 100644 --- a/crates/zkwasm/src/lib.rs +++ b/crates/zkwasm/src/lib.rs @@ -1,4 +1,6 @@ #![deny(warnings)] +#![allow(clippy::too_many_arguments)] +#![allow(clippy::type_complexity)] #![feature(int_roundings)] #![feature(stmt_expr_attributes)] #![feature(trait_upcasting)] diff --git a/crates/zkwasm/src/loader/mod.rs b/crates/zkwasm/src/loader/mod.rs index a072f76a0..518f66042 100644 --- a/crates/zkwasm/src/loader/mod.rs +++ b/crates/zkwasm/src/loader/mod.rs @@ -75,7 +75,7 @@ impl ZkWasmLoader { Ok(()) } - let mut module = Module::from_buffer(&image)?; + let mut module = Module::from_buffer(image)?; if let Ok(parity_module) = module.module().clone().parse_names() { module.module = parity_module; } else { diff --git a/crates/zkwasm/src/loader/slice.rs b/crates/zkwasm/src/loader/slice.rs index 7e18ec243..a54b659ab 100644 --- a/crates/zkwasm/src/loader/slice.rs +++ b/crates/zkwasm/src/loader/slice.rs @@ -70,9 +70,9 @@ impl Slices { use halo2_proofs::dev::MockProver; let k = self.k; - let mut iter = self.into_iter(); + let iter = self; - while let Some(slice) = iter.next() { + for slice in iter { match slice? { ZkWasmCircuit::Ongoing(circuit) => { let prover = MockProver::run(k, &circuit, vec![instances.clone()])?; @@ -108,7 +108,7 @@ impl Iterator for Slices { match next_event_table { TableBackend::Memory(etable) => etable.entries().first().cloned(), TableBackend::Json(path) => { - let etable = EventTable::read(&path).unwrap(); + let etable = EventTable::read(path).unwrap(); etable.entries().first().cloned() } } @@ -134,7 +134,7 @@ impl Iterator for Slices { |frame_table| { let post_inherited_frame_table = match frame_table { TableBackend::Memory(frame_table) => frame_table.inherited.clone(), - TableBackend::Json(path) => FrameTable::read(&path).unwrap().inherited, + TableBackend::Json(path) => FrameTable::read(path).unwrap().inherited, }; Arc::new((*post_inherited_frame_table).clone().try_into().unwrap()) diff --git a/crates/zkwasm/src/runtime/host/external_circuit_plugin.rs b/crates/zkwasm/src/runtime/host/external_circuit_plugin.rs index 6b7c8916a..9113b7618 100644 --- a/crates/zkwasm/src/runtime/host/external_circuit_plugin.rs +++ b/crates/zkwasm/src/runtime/host/external_circuit_plugin.rs @@ -70,7 +70,7 @@ impl ExternalCircuitEnv { pub fn get_statics(&self) -> HashMap { let mut m = HashMap::new(); - for (_, v) in &self.functions { + for v in self.functions.values() { let plugin_name = &v.plugin.name; if !m.contains_key(plugin_name) { diff --git a/crates/zkwasm/src/runtime/host/host_env.rs b/crates/zkwasm/src/runtime/host/host_env.rs index a75730006..d68762ce1 100644 --- a/crates/zkwasm/src/runtime/host/host_env.rs +++ b/crates/zkwasm/src/runtime/host/host_env.rs @@ -67,14 +67,14 @@ impl HostEnv { for (name, op) in &self.external_env.functions { internal_op_allocator_offset = usize::max(internal_op_allocator_offset, op.op_index); - lookup + if lookup .insert( op.op_index, HostFunction { desc: HostFunctionDesc::External { name: name.to_owned(), op: op.op_index, - sig: op.sig.into(), + sig: op.sig, }, execution_env: HostFunctionExecutionEnv { ctx: op.plugin.ctx.clone(), @@ -82,7 +82,10 @@ impl HostEnv { }, }, ) - .map(|_| panic!("conflicting op index of foreign function")); + .is_some() + { + panic!("conflicting op index of foreign function") + } } internal_op_allocator_offset += 1; @@ -165,14 +168,7 @@ impl Externals for ExecEnv { index: usize, args: RuntimeArgs, ) -> Result, Trap> { - match self - .host_env - .cached_lookup - .as_ref() - .unwrap() - .get(&index) - .clone() - { + match self.host_env.cached_lookup.as_ref().unwrap().get(&index) { Some(HostFunction { desc: _desc, execution_env: HostFunctionExecutionEnv { ctx, cb }, diff --git a/crates/zkwasm/src/runtime/host/internal_circuit_plugin.rs b/crates/zkwasm/src/runtime/host/internal_circuit_plugin.rs index 763e770c8..f58578d2f 100644 --- a/crates/zkwasm/src/runtime/host/internal_circuit_plugin.rs +++ b/crates/zkwasm/src/runtime/host/internal_circuit_plugin.rs @@ -94,7 +94,9 @@ impl ModuleImportResolver for InternalCircuitEnv { index.expect("Unsolved host function index."), )) } else { - Err(wasmi::Error::Instantiation(format!("Signature not match",))) + Err(wasmi::Error::Instantiation( + "Signature not match".to_string(), + )) } } else { Err(wasmi::Error::Instantiation(format!( diff --git a/crates/zkwasm/src/runtime/host/mod.rs b/crates/zkwasm/src/runtime/host/mod.rs index a31638950..0de98f54f 100644 --- a/crates/zkwasm/src/runtime/host/mod.rs +++ b/crates/zkwasm/src/runtime/host/mod.rs @@ -33,10 +33,10 @@ impl MatchForeignOpSignature for ExternalHostCallSignature { ExternalHostCallSignature::Argument => { signature.params().len() == 1 && signature.params()[0] == wasmi::ValueType::I64 - && signature.return_type() == None + && signature.return_type().is_none() } ExternalHostCallSignature::Return => { - signature.params().len() == 0 + signature.params().is_empty() && signature.return_type() == Some(wasmi::ValueType::I64) } } diff --git a/crates/zkwasm/src/runtime/mod.rs b/crates/zkwasm/src/runtime/mod.rs index 1075fa7d2..0166f0703 100644 --- a/crates/zkwasm/src/runtime/mod.rs +++ b/crates/zkwasm/src/runtime/mod.rs @@ -77,7 +77,7 @@ pub fn memory_event_of_step(event: &EventTableEntry) -> Vec { value: keep_values[i], }); - sp = sp + 1; + sp += 1; } } @@ -96,7 +96,7 @@ pub fn memory_event_of_step(event: &EventTableEntry) -> Vec { value: keep_values[i], }); - sp = sp - 1; + sp -= 1; } } @@ -124,7 +124,7 @@ pub fn memory_event_of_step(event: &EventTableEntry) -> Vec { value: *condition as u32 as u64, }]; - sp = sp + 1; + sp += 1; if *condition != 0 { return ops; @@ -142,7 +142,7 @@ pub fn memory_event_of_step(event: &EventTableEntry) -> Vec { value: keep_values[i], }); - sp = sp + 1; + sp += 1; } } @@ -161,7 +161,7 @@ pub fn memory_event_of_step(event: &EventTableEntry) -> Vec { value: keep_values[i], }); - sp = sp - 1; + sp -= 1; } } @@ -189,7 +189,7 @@ pub fn memory_event_of_step(event: &EventTableEntry) -> Vec { value: *condition as u32 as u64, }]; - sp = sp + 1; + sp += 1; if *condition == 0 { return ops; @@ -207,7 +207,7 @@ pub fn memory_event_of_step(event: &EventTableEntry) -> Vec { value: keep_values[i], }); - sp = sp + 1; + sp += 1; } } @@ -226,7 +226,7 @@ pub fn memory_event_of_step(event: &EventTableEntry) -> Vec { value: keep_values[i], }); - sp = sp - 1; + sp -= 1; } } @@ -254,7 +254,7 @@ pub fn memory_event_of_step(event: &EventTableEntry) -> Vec { value: *index as u32 as u64, }]; - sp = sp + 1; + sp += 1; { for i in 0..keep.len() { @@ -268,7 +268,7 @@ pub fn memory_event_of_step(event: &EventTableEntry) -> Vec { value: keep_values[i], }); - sp = sp + 1; + sp += 1; } } @@ -287,7 +287,7 @@ pub fn memory_event_of_step(event: &EventTableEntry) -> Vec { value: keep_values[i], }); - sp = sp - 1; + sp -= 1; } } @@ -316,7 +316,7 @@ pub fn memory_event_of_step(event: &EventTableEntry) -> Vec { value: keep_values[i], }); - sp = sp + 1; + sp += 1; } } @@ -335,7 +335,7 @@ pub fn memory_event_of_step(event: &EventTableEntry) -> Vec { value: keep_values[i], }); - sp = sp - 1; + sp -= 1; } } @@ -361,7 +361,7 @@ pub fn memory_event_of_step(event: &EventTableEntry) -> Vec { is_mutable: true, value: *cond, }); - sp = sp + 1; + sp += 1; ops.push(MemoryTableEntry { eid, @@ -372,7 +372,7 @@ pub fn memory_event_of_step(event: &EventTableEntry) -> Vec { is_mutable: true, value: *val2, }); - sp = sp + 1; + sp += 1; ops.push(MemoryTableEntry { eid, @@ -433,7 +433,7 @@ pub fn memory_event_of_step(event: &EventTableEntry) -> Vec { }); } - sp = sp + args.len() as u32; + sp += args.len() as u32; if let Some(ty) = signature.return_type { mops.push(MemoryTableEntry { @@ -653,7 +653,7 @@ pub fn memory_event_of_step(event: &EventTableEntry) -> Vec { value: *block_value1, }; - let load_value2 = if *effective_address % 8 + load_size.byte_size() as u32 > 8 { + let load_value2 = if *effective_address % 8 + load_size.byte_size() > 8 { Some(MemoryTableEntry { eid, offset: effective_address / 8 + 1, @@ -790,7 +790,7 @@ pub fn memory_event_of_step(event: &EventTableEntry) -> Vec { VarType::I32, VarType::I32, &[], - &[event.allocated_memory_pages as u32 as u64], + &[event.allocated_memory_pages as u64], ), StepInfo::MemoryGrow { grow_size, result } => mem_op_from_stack_only_step( sp_before_execution, @@ -947,7 +947,7 @@ pub(crate) fn mem_op_from_stack_only_step( let mut mem_op = vec![]; let mut sp = sp_before_execution; - for i in 0..pop_value.len() { + for value in pop_value { mem_op.push(MemoryTableEntry { eid, offset: sp + 1, @@ -955,12 +955,12 @@ pub(crate) fn mem_op_from_stack_only_step( atype: AccessType::Read, vtype: inputs_type, is_mutable: true, - value: pop_value[i], + value: *value, }); - sp = sp + 1; + sp += 1; } - for i in 0..push_value.len() { + for value in push_value { mem_op.push(MemoryTableEntry { eid, offset: sp, @@ -968,9 +968,9 @@ pub(crate) fn mem_op_from_stack_only_step( atype: AccessType::Write, vtype: outputs_type, is_mutable: true, - value: push_value[i], + value: *value, }); - sp = sp - 1; + sp -= 1; } mem_op diff --git a/crates/zkwasm/src/runtime/monitor/plugins/phantom.rs b/crates/zkwasm/src/runtime/monitor/plugins/phantom.rs index df3405dd0..1125fb715 100644 --- a/crates/zkwasm/src/runtime/monitor/plugins/phantom.rs +++ b/crates/zkwasm/src/runtime/monitor/plugins/phantom.rs @@ -15,7 +15,7 @@ pub struct PhantomHelper { } impl PhantomHelper { - pub fn new(phantom_regex: &Vec, wasm_input: FuncRef) -> Self { + pub fn new(phantom_regex: &[String], wasm_input: FuncRef) -> Self { Self { phantom_regex: phantom_regex .iter() @@ -30,7 +30,7 @@ impl PhantomHelper { } pub(in crate::runtime::monitor) fn is_in_phantom_function(&self) -> bool { - self.frame.len() > 0 + !self.frame.is_empty() } pub(in crate::runtime::monitor) fn is_phantom_function(&self, func_index: u32) -> bool { diff --git a/crates/zkwasm/src/runtime/monitor/plugins/statistic.rs b/crates/zkwasm/src/runtime/monitor/plugins/statistic.rs index 8838fff84..924a2741e 100644 --- a/crates/zkwasm/src/runtime/monitor/plugins/statistic.rs +++ b/crates/zkwasm/src/runtime/monitor/plugins/statistic.rs @@ -17,7 +17,7 @@ pub struct StatisticPlugin { } impl StatisticPlugin { - pub fn new(phantom_regex: &Vec, wasm_input: FuncRef) -> Self { + pub fn new(phantom_regex: &[String], wasm_input: FuncRef) -> Self { Self { phantom_helper: PhantomHelper::new(phantom_regex, wasm_input), observer: Rc::new(RefCell::new(Observer::default())), diff --git a/crates/zkwasm/src/runtime/monitor/plugins/table/frame_table.rs b/crates/zkwasm/src/runtime/monitor/plugins/table/frame_table.rs index 9ee4bce30..6eb791028 100644 --- a/crates/zkwasm/src/runtime/monitor/plugins/table/frame_table.rs +++ b/crates/zkwasm/src/runtime/monitor/plugins/table/frame_table.rs @@ -20,32 +20,32 @@ struct FrameTableEntry { returned: bool, } -impl Into for &FrameTableEntry { - fn into(self) -> CalledFrameTableEntry { - assert!(!self.inherited); +impl From<&FrameTableEntry> for CalledFrameTableEntry { + fn from(entry: &FrameTableEntry) -> CalledFrameTableEntry { + assert!(!entry.inherited); CalledFrameTableEntry(FrameTableEntryInternal { - frame_id: self.frame_id, - next_frame_id: self.next_frame_id, - callee_fid: self.callee_fid, - fid: self.fid, - iid: self.iid, - returned: self.returned, + frame_id: entry.frame_id, + next_frame_id: entry.next_frame_id, + callee_fid: entry.callee_fid, + fid: entry.fid, + iid: entry.iid, + returned: entry.returned, }) } } -impl Into for &FrameTableEntry { - fn into(self) -> InheritedFrameTableEntry { - assert!(self.inherited); +impl From<&FrameTableEntry> for InheritedFrameTableEntry { + fn from(entry: &FrameTableEntry) -> InheritedFrameTableEntry { + assert!(entry.inherited); InheritedFrameTableEntry(Some(FrameTableEntryInternal { - frame_id: self.frame_id, - next_frame_id: self.next_frame_id, - callee_fid: self.callee_fid, - fid: self.fid, - iid: self.iid, - returned: self.returned, + frame_id: entry.frame_id, + next_frame_id: entry.next_frame_id, + callee_fid: entry.callee_fid, + fid: entry.fid, + iid: entry.iid, + returned: entry.returned, })) } } diff --git a/crates/zkwasm/src/runtime/monitor/plugins/table/instruction.rs b/crates/zkwasm/src/runtime/monitor/plugins/table/instruction.rs index 0d97b991c..9ed9360db 100644 --- a/crates/zkwasm/src/runtime/monitor/plugins/table/instruction.rs +++ b/crates/zkwasm/src/runtime/monitor/plugins/table/instruction.rs @@ -719,7 +719,7 @@ pub(super) fn run_instruction_pre( let value = value_stack.top(); Some(RunInstructionTracePre::SetLocal { depth, - value: value.clone(), + value: *value, vtype, }) } @@ -775,7 +775,7 @@ pub(super) fn run_instruction_pre( }; let raw_address = <_>::from_value_internal(*value_stack.top()); - let address = effective_address(offset, raw_address).map_or(None, |addr| Some(addr)); + let address = effective_address(offset, raw_address).ok(); Some(RunInstructionTracePre::Load { offset, @@ -803,7 +803,7 @@ pub(super) fn run_instruction_pre( _ => unreachable!(), }; let raw_address = <_>::from_value_internal(*value_stack.top()); - let address = effective_address(offset, raw_address).map_or(None, |addr| Some(addr)); + let address = effective_address(offset, raw_address).ok(); Some(RunInstructionTracePre::Load { offset, @@ -825,7 +825,7 @@ pub(super) fn run_instruction_pre( let value: u32 = <_>::from_value_internal(*value_stack.pick(1)); let raw_address = <_>::from_value_internal(*value_stack.pick(2)); - let address = effective_address(offset, raw_address).map_or(None, |addr| Some(addr)); + let address = effective_address(offset, raw_address).ok(); let pre_block_value1 = address.map(|address| { let mut buf = [0u8; 8]; @@ -838,22 +838,20 @@ pub(super) fn run_instruction_pre( u64::from_le_bytes(buf) }); - let pre_block_value2 = address - .map(|address| { - if store_size.byte_size() as u32 + address % 8 > 8 { - let mut buf = [0u8; 8]; - function_context - .memory - .clone() - .unwrap() - .get_into((address / 8 + 1) * 8, &mut buf) - .unwrap(); - Some(u64::from_le_bytes(buf)) - } else { - None - } - }) - .flatten(); + let pre_block_value2 = address.and_then(|address| { + if store_size.byte_size() as u32 + address % 8 > 8 { + let mut buf = [0u8; 8]; + function_context + .memory + .clone() + .unwrap() + .get_into((address / 8 + 1) * 8, &mut buf) + .unwrap(); + Some(u64::from_le_bytes(buf)) + } else { + None + } + }); Some(RunInstructionTracePre::Store { offset, @@ -880,7 +878,7 @@ pub(super) fn run_instruction_pre( let value = <_>::from_value_internal(*value_stack.pick(1)); let raw_address = <_>::from_value_internal(*value_stack.pick(2)); - let address = effective_address(offset, raw_address).map_or(None, |addr| Some(addr)); + let address = effective_address(offset, raw_address).ok(); let pre_block_value1 = address.map(|address| { let mut buf = [0u8; 8]; @@ -893,22 +891,20 @@ pub(super) fn run_instruction_pre( u64::from_le_bytes(buf) }); - let pre_block_value2 = address - .map(|address| { - if store_size.byte_size() as u32 + address % 8 > 8 { - let mut buf = [0u8; 8]; - function_context - .memory - .clone() - .unwrap() - .get_into((address / 8 + 1) * 8, &mut buf) - .unwrap(); - Some(u64::from_le_bytes(buf)) - } else { - None - } - }) - .flatten(); + let pre_block_value2 = address.and_then(|address| { + if store_size.byte_size() as u32 + address % 8 > 8 { + let mut buf = [0u8; 8]; + function_context + .memory + .clone() + .unwrap() + .get_into((address / 8 + 1) * 8, &mut buf) + .unwrap(); + Some(u64::from_le_bytes(buf)) + } else { + None + } + }); Some(RunInstructionTracePre::Store { offset, @@ -1091,7 +1087,7 @@ impl TablePlugin { let is_mutable = global_ref.is_mutable(); let vtype: VarType = global_ref.value_type().into_elements().into(); let value = from_value_internal_to_u64_with_typ( - vtype.into(), + vtype, ValueInternal::from(global_ref.get()), ); @@ -1107,7 +1103,7 @@ impl TablePlugin { let is_mutable = global_ref.is_mutable(); let vtype: VarType = global_ref.value_type().into_elements().into(); let value = from_value_internal_to_u64_with_typ( - vtype.into(), + vtype, ValueInternal::from(global_ref.get()), ); @@ -1272,9 +1268,9 @@ impl TablePlugin { desc.signature.clone().into(); let params = signature.params.clone(); - for i in 0..params_len { + for (i, param) in params.iter().enumerate().take(params_len) { args.push(from_value_internal_to_u64_with_typ( - (params[i]).into(), + param.into(), *value_stack.pick(params_len - i), )); } @@ -1364,19 +1360,19 @@ impl TablePlugin { u64::from_le_bytes(buf) }; - let block_value2 = - if effective_address.unwrap() % 8 + load_size.byte_size() as u32 > 8 { - let mut buf = [0u8; 8]; - context - .memory - .clone() - .unwrap() - .get_into((effective_address.unwrap() / 8 + 1) * 8, &mut buf) - .unwrap(); - u64::from_le_bytes(buf) - } else { - 0 - }; + let block_value2 = if effective_address.unwrap() % 8 + load_size.byte_size() > 8 + { + let mut buf = [0u8; 8]; + context + .memory + .clone() + .unwrap() + .get_into((effective_address.unwrap() / 8 + 1) * 8, &mut buf) + .unwrap(); + u64::from_le_bytes(buf) + } else { + 0 + }; StepInfo::Load { vtype: vtype.into(), @@ -1444,7 +1440,7 @@ impl TablePlugin { offset, raw_address, effective_address: effective_address.unwrap(), - value: value as u64, + value, pre_block_value1: pre_block_value1.unwrap(), pre_block_value2: pre_block_value2.unwrap_or(0u64), updated_block_value1, diff --git a/crates/zkwasm/src/runtime/monitor/plugins/table/mod.rs b/crates/zkwasm/src/runtime/monitor/plugins/table/mod.rs index f3013b845..2c7a0b280 100644 --- a/crates/zkwasm/src/runtime/monitor/plugins/table/mod.rs +++ b/crates/zkwasm/src/runtime/monitor/plugins/table/mod.rs @@ -84,7 +84,7 @@ impl TablePlugin { pub fn new( k: u32, host_function_desc: HashMap, - phantom_regex: &Vec, + phantom_regex: &[String], wasm_input: FuncRef, trace_backend: TraceBackend, ) -> Self { @@ -119,7 +119,7 @@ impl TablePlugin { let imtable = InitMemoryTable::new(self.init_memory_table.clone()); let br_table = Arc::new(itable.create_brtable()); let elem_table = Arc::new(ElemTable::new(self.elements.clone())); - let configure_table = Arc::new(self.configure_table.clone()); + let configure_table = Arc::new(self.configure_table); let initialization_state = Arc::new(InitializationState { eid: 1, fid: self.start_fid.unwrap(), @@ -341,11 +341,8 @@ impl Monitor for TablePlugin { { for import_entry in module.import_section().map(|s| s.entries()).unwrap_or(&[]) { - match *import_entry.external() { - External::Function(fn_ty_idx) => { - type_idx_of_func.push(fn_ty_idx); - } - _ => {} + if let External::Function(fn_ty_idx) = *import_entry.external() { + type_idx_of_func.push(fn_ty_idx); } } @@ -410,7 +407,7 @@ impl Monitor for TablePlugin { let wasm_input_func_idx = self.phantom_helper.wasm_input_func_idx(module_ref); let instructions = PhantomFunction::build_phantom_function_instructions( - &func.signature(), + func.signature(), wasm_input_func_idx, ); @@ -421,18 +418,16 @@ impl Monitor for TablePlugin { instruction.into_opcode(&function_mapping), ); } - } else { - if let Some(body) = func.body() { - let code = &body.code; + } else if let Some(body) = func.body() { + let code = &body.code; - let mut iter = code.iterate_from(0); - let mut iid = iter.position(); - while let Some(instr) = iter.next() { - self.itable - .push(fid, iid, instr.into_opcode(&function_mapping)); + let mut iter = code.iterate_from(0); + let mut iid = iter.position(); + while let Some(instr) = iter.next() { + self.itable + .push(fid, iid, instr.into_opcode(&function_mapping)); - iid = iter.position(); - } + iid = iter.position(); } } @@ -510,7 +505,7 @@ impl Monitor for TablePlugin { .offset() .as_ref() .expect("passive segments are rejected due to validation"); - let offset_val = match eval_init_expr(offset, &module_ref) { + let offset_val = match eval_init_expr(offset, module_ref) { RuntimeValue::I32(v) => v as u32, _ => panic!("Due to validation elem segment offset should evaluate to i32"), }; diff --git a/crates/zkwasm/src/runtime/monitor/statistic_monitor.rs b/crates/zkwasm/src/runtime/monitor/statistic_monitor.rs index af07d0fac..f57ac2f03 100644 --- a/crates/zkwasm/src/runtime/monitor/statistic_monitor.rs +++ b/crates/zkwasm/src/runtime/monitor/statistic_monitor.rs @@ -24,7 +24,7 @@ pub struct StatisticMonitor { } impl StatisticMonitor { - pub fn new(phantom_regex: &Vec, env: &HostEnv) -> Self { + pub fn new(phantom_regex: &[String], env: &HostEnv) -> Self { let wasm_input = env .resolve_func( "wasm_input", diff --git a/crates/zkwasm/src/runtime/monitor/table_monitor.rs b/crates/zkwasm/src/runtime/monitor/table_monitor.rs index 20bf5325c..eff1ebd57 100644 --- a/crates/zkwasm/src/runtime/monitor/table_monitor.rs +++ b/crates/zkwasm/src/runtime/monitor/table_monitor.rs @@ -29,7 +29,7 @@ pub struct TableMonitor { } impl TableMonitor { - pub fn new(k: u32, phantom_regex: &Vec, backend: TraceBackend, env: &HostEnv) -> Self { + pub fn new(k: u32, phantom_regex: &[String], backend: TraceBackend, env: &HostEnv) -> Self { let wasm_input = env .resolve_func( "wasm_input", diff --git a/crates/zkwasm/src/runtime/state.rs b/crates/zkwasm/src/runtime/state.rs index 7353e0f54..6f58c967b 100644 --- a/crates/zkwasm/src/runtime/state.rs +++ b/crates/zkwasm/src/runtime/state.rs @@ -28,8 +28,8 @@ impl UpdateInitMemoryTable for InitMemoryTable { // First insert origin imtable entries which may be overwritten. let mut map = self.0.clone(); - let mut it = execution_table.entries().iter(); - while let Some(etable_entry) = it.next() { + let it = execution_table.entries().iter(); + for etable_entry in it { let memory_writing_entires = memory_event_of_step(etable_entry) .into_iter() .filter(|entry| entry.atype == AccessType::Write); @@ -94,7 +94,23 @@ impl UpdateInitializationState for InitializationState { } } - let post_initialization_state = if next_event_entry.is_none() { + let post_initialization_state = if let Some(next_entry) = next_event_entry { + InitializationState { + eid: next_entry.eid, + fid: next_entry.fid, + iid: next_entry.iid, + frame_id: next_entry.last_jump_eid, + sp: next_entry.sp, + + host_public_inputs, + context_in_index, + context_out_index, + external_host_call_call_index, + + initial_memory_pages: next_entry.allocated_memory_pages, + maximal_memory_pages: configure_table.maximal_memory_pages, + } + } else { let last_entry = execution_table.entries().last().unwrap(); InitializationState { @@ -118,24 +134,6 @@ impl UpdateInitializationState for InitializationState { initial_memory_pages: last_entry.allocated_memory_pages, maximal_memory_pages: configure_table.maximal_memory_pages, } - } else { - let next_entry = next_event_entry.unwrap(); - - InitializationState { - eid: next_entry.eid, - fid: next_entry.fid, - iid: next_entry.iid, - frame_id: next_entry.last_jump_eid, - sp: next_entry.sp, - - host_public_inputs, - context_in_index, - context_out_index, - external_host_call_call_index, - - initial_memory_pages: next_entry.allocated_memory_pages, - maximal_memory_pages: configure_table.maximal_memory_pages, - } }; post_initialization_state diff --git a/crates/zkwasm/src/runtime/wasmi_interpreter.rs b/crates/zkwasm/src/runtime/wasmi_interpreter.rs index 7ddf351e8..b5e68f5b6 100644 --- a/crates/zkwasm/src/runtime/wasmi_interpreter.rs +++ b/crates/zkwasm/src/runtime/wasmi_interpreter.rs @@ -70,10 +70,6 @@ impl Execution for CompiledImage> { pub struct WasmiRuntime; impl WasmiRuntime { - pub fn new() -> Self { - WasmiRuntime - } - pub fn compile<'a, I: ImportResolver>( monitor: &mut dyn Monitor, module: &'a wasmi::Module, @@ -81,7 +77,7 @@ impl WasmiRuntime { entry: &str, ) -> Result>> { let instance = - ModuleInstance::new(&module, imports).expect("failed to instantiate wasm module"); + ModuleInstance::new(module, imports).expect("failed to instantiate wasm module"); monitor.register_module(instance.loaded_module.module(), &instance.instance, entry)?; Ok(CompiledImage { diff --git a/crates/zkwasm/src/test/mod.rs b/crates/zkwasm/src/test/mod.rs index 07a1bd3d5..672000001 100644 --- a/crates/zkwasm/src/test/mod.rs +++ b/crates/zkwasm/src/test/mod.rs @@ -59,7 +59,7 @@ fn test_circuit_noexternal(textual_repr: &str) -> Result<()> { let mut features = Features::new(); features.enable_sign_extension(); - let wasm = wat2wasm_with_features(&textual_repr, features).expect("failed to parse wat"); + let wasm = wat2wasm_with_features(textual_repr, features).expect("failed to parse wat"); test_circuit_with_env(MIN_K, wasm, "test".to_string(), vec![], vec![])?; diff --git a/crates/zkwasm/src/test/test_start.rs b/crates/zkwasm/src/test/test_start.rs index aee279b6d..514b1f2de 100644 --- a/crates/zkwasm/src/test/test_start.rs +++ b/crates/zkwasm/src/test/test_start.rs @@ -26,7 +26,7 @@ mod tests { ) "#; - let wasm = wabt::wat2wasm(&textual_repr).expect("failed to parse wat"); + let wasm = wabt::wat2wasm(textual_repr).expect("failed to parse wat"); test_circuit_with_env(18, wasm, "zkmain".to_string(), vec![], vec![]).unwrap(); } diff --git a/crates/zkwasm/src/test/test_wasm_instructions/op_call_host.rs b/crates/zkwasm/src/test/test_wasm_instructions/op_call_host.rs index 847921a38..13aa2c6a9 100644 --- a/crates/zkwasm/src/test/test_wasm_instructions/op_call_host.rs +++ b/crates/zkwasm/src/test/test_wasm_instructions/op_call_host.rs @@ -42,7 +42,7 @@ fn test_call_host_external() { let foreign_playground_plugin = env .external_env - .register_plugin("foreign_playground", Box::new(Context::default())); + .register_plugin("foreign_playground", Box::::default()); env.external_env.register_function( "foreign_push", 0, @@ -78,6 +78,6 @@ fn test_call_host_external() { env }; - let _wasm = wabt::wat2wasm(&textual_repr).expect("failed to parse wat"); + let _wasm = wabt::wat2wasm(textual_repr).expect("failed to parse wat"); // test_circuit_with_env(env, wasm, "test".to_string()).unwrap(); }