Skip to content

Commit

Permalink
refactor: refine CIRCUIT_CONFIGURE initialization
Browse files Browse the repository at this point in the history
  • Loading branch information
junyu0312 committed Jul 3, 2023
1 parent 7530cac commit a3a99ce
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 59 deletions.
49 changes: 49 additions & 0 deletions src/circuits/config.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
use std::collections::HashSet;
use std::env;
use std::sync::Mutex;

use specs::itable::OpcodeClassPlain;
use specs::CompilationTable;

pub const POW_TABLE_LIMIT: u64 = 128;

pub const MIN_K: u32 = 18;
Expand All @@ -24,6 +28,45 @@ lazy_static! {
env::var("ZKWASM_SHA256_RATIO").map_or(31, |k| k.parse().unwrap());
}

#[derive(Clone)]
pub struct CircuitConfigure {
pub initial_memory_pages: u32,
pub maximal_memory_pages: u32,
pub opcode_selector: HashSet<OpcodeClassPlain>,
}

#[thread_local]
static mut CIRCUIT_CONFIGURE: Option<CircuitConfigure> = None;

impl CircuitConfigure {
#[allow(non_snake_case)]
pub(crate) fn set_global_CIRCUIT_CONFIGURE(self) {
unsafe {
CIRCUIT_CONFIGURE = Some(self);
}
}

pub(crate) fn get() -> CircuitConfigure {
unsafe {
if CIRCUIT_CONFIGURE.is_none() {
panic!("CIRCUIT_CONFIGURE is not set, call init_zkwasm_runtime before configuring circuit.");
} else {
return CIRCUIT_CONFIGURE.clone().unwrap();
}
}
}
}

impl From<&CompilationTable> for CircuitConfigure {
fn from(table: &CompilationTable) -> Self {
CircuitConfigure {
initial_memory_pages: table.configure_table.init_memory_pages,
maximal_memory_pages: table.configure_table.maximal_memory_pages,
opcode_selector: table.itable.opcode_class(),
}
}
}

pub fn set_zkwasm_k(k: u32) {
assert!(k >= MIN_K);

Expand All @@ -35,6 +78,12 @@ pub fn zkwasm_k() -> u32 {
*ZKWASM_K.lock().unwrap()
}

pub fn init_zkwasm_runtime(k: u32, table: &CompilationTable) {
set_zkwasm_k(k);

CircuitConfigure::from(table).set_global_CIRCUIT_CONFIGURE();
}

#[cfg(feature = "checksum")]
pub(crate) fn max_image_table_rows() -> u32 {
8192
Expand Down
25 changes: 3 additions & 22 deletions src/circuits/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,7 @@ use halo2_proofs::transcript::Blake2bWrite;
use halo2_proofs::transcript::Challenge255;
use num_bigint::BigUint;
use rand::rngs::OsRng;
use specs::itable::OpcodeClassPlain;
use specs::Tables;
use std::collections::HashSet;
use std::fs::File;
use std::io::Cursor;
use std::io::Read;
Expand All @@ -56,22 +54,14 @@ pub mod image_table_fixed;
#[cfg(not(feature = "checksum"))]
pub use image_table_fixed as image_table;

use self::config::CircuitConfigure;

pub mod config;
pub mod jtable;
pub mod rtable;
pub mod test_circuit;
pub mod utils;

#[derive(Clone)]
pub struct CircuitConfigure {
pub initial_memory_pages: u32,
pub maximal_memory_pages: u32,
pub opcode_selector: HashSet<OpcodeClassPlain>,
}

#[thread_local]
static mut CIRCUIT_CONFIGURE: Option<CircuitConfigure> = None;

#[derive(Default, Clone)]
pub struct TestCircuit<F: FieldExt> {
pub tables: Tables,
Expand All @@ -80,16 +70,7 @@ pub struct TestCircuit<F: FieldExt> {

impl<F: FieldExt> TestCircuit<F> {
pub fn new(tables: Tables) -> Self {
unsafe {
CIRCUIT_CONFIGURE = Some(CircuitConfigure {
initial_memory_pages: tables.compilation_tables.configure_table.init_memory_pages,
maximal_memory_pages: tables
.compilation_tables
.configure_table
.maximal_memory_pages,
opcode_selector: tables.compilation_tables.itable.opcode_class(),
});
}
CircuitConfigure::from(&tables.compilation_tables).set_global_CIRCUIT_CONFIGURE();

TestCircuit {
tables,
Expand Down
4 changes: 2 additions & 2 deletions src/circuits/test_circuit/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,13 @@ use crate::circuits::utils::table_entry::EventTableWithMemoryInfo;
use crate::circuits::utils::table_entry::MemoryWritingTable;
use crate::circuits::utils::Context;
use crate::circuits::TestCircuit;
use crate::circuits::CIRCUIT_CONFIGURE;
use crate::exec_with_profile;
use crate::foreign::wasm_input_helper::circuits::assign::WasmInputHelperTableChip;
use crate::foreign::wasm_input_helper::circuits::WasmInputHelperTableConfig;
use crate::foreign::wasm_input_helper::circuits::WASM_INPUT_FOREIGN_TABLE_KEY;
use crate::foreign::ForeignTableConfig;

use super::config::CircuitConfigure;
use super::image_table::ImageTableConfig;

pub const VAR_COLUMNS: usize = 52;
Expand Down Expand Up @@ -71,7 +71,7 @@ impl<F: FieldExt> Circuit<F> for TestCircuit<F> {
}

fn configure(meta: &mut ConstraintSystem<F>) -> Self::Config {
let circuit_configure = unsafe { CIRCUIT_CONFIGURE.clone().unwrap() };
let circuit_configure = CircuitConfigure::get();

/*
* Allocate a column to enable assign_advice_from_constant.
Expand Down
15 changes: 8 additions & 7 deletions src/cli/app_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ use log::info;
use std::fs;
use std::path::PathBuf;

use crate::circuits::config::set_zkwasm_k;
use crate::circuits::config::init_zkwasm_runtime;
use crate::circuits::config::MIN_K;
use crate::cli::exec::exec_dry_run;

use super::command::CommandBuilder;
use super::exec::build_circuit_without_witness;
use super::exec::compile_image;
use super::exec::exec_aggregate_create_proof;
use super::exec::exec_create_proof;
#[cfg(feature = "checksum")]
Expand Down Expand Up @@ -65,17 +65,18 @@ pub trait AppBuilder: CommandBuilder {
let top_matches = command.get_matches();

let zkwasm_k = Self::parse_zkwasm_k_arg(&top_matches).unwrap_or(MIN_K);
set_zkwasm_k(zkwasm_k);

let wasm_file_path = Self::parse_zkwasm_file_arg(&top_matches);
let wasm_binary = fs::read(&wasm_file_path).unwrap();

let function_name = Self::parse_function_name(&top_matches);

/*
* FIXME: trigger CIRCUIT_CONFIGURE initialization.
*/
build_circuit_without_witness(&wasm_binary, &function_name);
{
let module = wasmi::Module::from_buffer(&wasm_binary).expect("failed to load wasm");

let (_, table) = compile_image(&module, &function_name);
init_zkwasm_runtime(zkwasm_k, &table.tables);
}

let md5 = format!("{:X}", md5::compute(&wasm_binary));

Expand Down
50 changes: 22 additions & 28 deletions src/cli/exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
use crate::image_hasher::ImageHasher;

use crate::profile::Profiler;
use crate::runtime::wasmi_interpreter::WasmRuntimeIO;
use crate::runtime::CompiledImage;
use anyhow::Result;
use halo2_proofs::arithmetic::BaseExt;
Expand Down Expand Up @@ -48,32 +49,40 @@ use crate::runtime::WasmInterpreter;

const AGGREGATE_PREFIX: &'static str = "aggregate-circuit";

fn compile_image<'a>(
pub fn compile_image<'a>(
module: &'a Module,
function_name: &str,
) -> CompiledImage<NotStartedModuleRef<'a>, Tracer> {
) -> (
WasmRuntimeIO,
CompiledImage<NotStartedModuleRef<'a>, Tracer>,
) {
let mut env = HostEnv::new();
register_wasm_input_foreign(&mut env, vec![], vec![]);
let wasm_runtime_io = register_wasm_input_foreign(&mut env, vec![], vec![]);
register_require_foreign(&mut env);
register_log_foreign(&mut env);
env.finalize();
let imports = ImportsBuilder::new().with_resolver("env", &env);

let compiler = WasmInterpreter::new();
compiler
.compile(
&module,
&imports,
&env.function_description_table(),
function_name,
)
.expect("file cannot be complied")
(
wasm_runtime_io,
compiler
.compile(
&module,
&imports,
&env.function_description_table(),
function_name,
)
.expect("file cannot be complied"),
)
}

#[cfg(feature = "checksum")]
fn hash_image(wasm_binary: &Vec<u8>, function_name: &str) -> Fr {
let module = wasmi::Module::from_buffer(wasm_binary).expect("failed to load wasm");

compile_image(&module, function_name).tables.hash()
let (_, compiled_image) = compile_image(&module, function_name);
compiled_image.tables.hash()
}

pub fn build_circuit_without_witness(
Expand All @@ -82,22 +91,7 @@ pub fn build_circuit_without_witness(
) -> TestCircuit<Fr> {
let module = wasmi::Module::from_buffer(wasm_binary).expect("failed to load wasm");

let mut env = HostEnv::new();
let wasm_runtime_io = register_wasm_input_foreign(&mut env, vec![], vec![]);
register_require_foreign(&mut env);
register_log_foreign(&mut env);
env.finalize();
let imports = ImportsBuilder::new().with_resolver("env", &env);

let compiler = WasmInterpreter::new();
let compiled_module = compiler
.compile(
&module,
&imports,
&env.function_description_table(),
function_name,
)
.expect("file cannot be complied");
let (wasm_runtime_io, compiled_module) = compile_image(&module, function_name);

let builder = ZkWasmCircuitBuilder {
tables: Tables {
Expand Down

0 comments on commit a3a99ce

Please sign in to comment.