Skip to content

Commit

Permalink
chore: add misc utility functions (#146)
Browse files Browse the repository at this point in the history
* chore(keccak_leaf): make `generate_circuit_final_outputs` public

* chore: add misc utility functions
  • Loading branch information
jonathanpwang authored Sep 10, 2023
1 parent 14bec5a commit c2a9341
Show file tree
Hide file tree
Showing 5 changed files with 42 additions and 9 deletions.
7 changes: 3 additions & 4 deletions halo2-base/src/gates/circuit/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ impl<F: ScalarField> BaseCircuitBuilder<F> {
/// Sets the copy manager to the given one in all shared references.
pub fn set_copy_manager(&mut self, copy_manager: SharedCopyConstraintManager<F>) {
for lm in &mut self.lookup_manager {
lm.copy_manager = copy_manager.clone();
lm.set_copy_manager(copy_manager.clone());
}
self.core.set_copy_manager(copy_manager);
}
Expand All @@ -116,10 +116,9 @@ impl<F: ScalarField> BaseCircuitBuilder<F> {
pub fn deep_clone(&self) -> Self {
let cm: CopyConstraintManager<F> = self.core.copy_manager.lock().unwrap().clone();
let cm_ref = Arc::new(Mutex::new(cm));
let mut clone = self.clone().use_copy_manager(cm_ref);
let mut clone = self.clone().use_copy_manager(cm_ref.clone());
for lm in &mut clone.lookup_manager {
let ctl_clone = lm.cells_to_lookup.lock().unwrap().clone();
lm.cells_to_lookup = Arc::new(Mutex::new(ctl_clone));
*lm = lm.deep_clone(cm_ref.clone());
}
clone
}
Expand Down
10 changes: 10 additions & 0 deletions halo2-base/src/safe_types/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,11 @@ impl<F: ScalarField, const LEN: usize> FixLenBytes<F, LEN> {
pub fn len(&self) -> usize {
LEN
}

/// Returns inner array of [SafeByte]s.
pub fn into_bytes(self) -> [SafeByte<F>; LEN] {
self.bytes
}
}

/// Represents a fixed length byte array in circuit. Not encouraged to use because `MAX_LEN` cannot be verified at compile time.
Expand All @@ -148,6 +153,11 @@ impl<F: ScalarField> FixLenBytesVec<F> {
pub fn len(&self) -> usize {
self.bytes.len()
}

/// Returns inner array of [SafeByte]s.
pub fn into_bytes(self) -> Vec<SafeByte<F>> {
self.bytes
}
}

impl<F: ScalarField, const TOTAL_BITS: usize> From<SafeType<F, 1, TOTAL_BITS>>
Expand Down
13 changes: 13 additions & 0 deletions halo2-base/src/safe_types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,19 @@ impl<F: ScalarField, const BYTES_PER_ELE: usize, const TOTAL_BITS: usize> AsRef<
}
}

impl<F: ScalarField, const TOTAL_BITS: usize> TryFrom<Vec<SafeByte<F>>>
for SafeType<F, 1, TOTAL_BITS>
{
type Error = String;

fn try_from(value: Vec<SafeByte<F>>) -> Result<Self, Self::Error> {
if value.len() * 8 != TOTAL_BITS {
return Err("Invalid length".to_owned());
}
Ok(Self::new(value.into_iter().map(|b| b.0).collect::<Vec<_>>()))
}
}

/// Represent TOTAL_BITS with the least number of AssignedValue<F>.
/// (2^(F::NUM_BITS) - 1) might not be a valid value for F. e.g. max value of F is a prime in [2^(F::NUM_BITS-1), 2^(F::NUM_BITS) - 1]
#[allow(type_alias_bounds)]
Expand Down
19 changes: 15 additions & 4 deletions halo2-base/src/virtual_region/lookups.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex, OnceLock};

use getset::Getters;
use getset::{CopyGetters, Getters, Setters};

use crate::ff::Field;
use crate::halo2_proofs::{
Expand Down Expand Up @@ -37,15 +37,16 @@ use super::manager::VirtualRegionManager;
/// The assumption is that the [Context] is thread-local.
///
/// Cheap to clone across threads because everything is in [Arc].
#[derive(Clone, Debug, Getters)]
#[derive(Clone, Debug, Getters, CopyGetters, Setters)]
pub struct LookupAnyManager<F: Field + Ord, const ADVICE_COLS: usize> {
/// Shared cells to lookup, tagged by (type id, context id).
#[allow(clippy::type_complexity)]
pub cells_to_lookup: Arc<Mutex<BTreeMap<ContextTag, Vec<[AssignedValue<F>; ADVICE_COLS]>>>>,
/// Global shared copy manager
pub copy_manager: SharedCopyConstraintManager<F>,
#[getset(get = "pub", set = "pub")]
copy_manager: SharedCopyConstraintManager<F>,
/// Specify whether constraints should be imposed for additional safety.
#[getset(get = "pub")]
#[getset(get_copy = "pub")]
witness_gen_only: bool,
/// Flag for whether `assign_raw` has been called, for safety only.
pub(crate) assigned: Arc<OnceLock<()>>,
Expand Down Expand Up @@ -90,6 +91,16 @@ impl<F: Field + Ord, const ADVICE_COLS: usize> LookupAnyManager<F, ADVICE_COLS>
self.copy_manager.lock().unwrap().clear();
self.assigned = Arc::new(OnceLock::new());
}

/// Deep clone with the specified copy manager. Unsets `assigned`.
pub fn deep_clone(&self, copy_manager: SharedCopyConstraintManager<F>) -> Self {
Self {
witness_gen_only: self.witness_gen_only,
cells_to_lookup: Arc::new(Mutex::new(self.cells_to_lookup.lock().unwrap().clone())),
copy_manager,
assigned: Default::default(),
}
}
}

impl<F: Field + Ord, const ADVICE_COLS: usize> Drop for LookupAnyManager<F, ADVICE_COLS> {
Expand Down
2 changes: 1 addition & 1 deletion hashes/zkevm/src/keccak/coprocessor/circuit/leaf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,7 @@ impl<F: Field> KeccakCoprocessorLeafCircuit<F> {
}

/// Combine lookup keys and Keccak results to generate final outputs of the circuit.
fn generate_circuit_final_outputs(
pub fn generate_circuit_final_outputs(
ctx: &mut Context<F>,
gate: &impl GateInstructions<F>,
lookup_key_per_keccak_f: &[PoseidonCompactOutput<F>],
Expand Down

0 comments on commit c2a9341

Please sign in to comment.