Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Release v0.4.1 #246

Merged
merged 167 commits into from
Jan 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
167 commits
Select commit Hold shift + click to select a range
863de11
feat: upgrade overall `halo2-base` API to support future multi-threaded
jonathanpwang Feb 6, 2023
941035a
BUG: `GateInstructions::idx_to_indicator` was missing a constraint to
jonathanpwang Feb 6, 2023
4abc9cd
update: working benches for `mul` and `inner_product`
jonathanpwang Feb 6, 2023
ec80e15
feat: add `test_multithread_gates`
jonathanpwang Feb 7, 2023
987853e
BUG: `get_last_bit` did not do an `assert_bit` check on the answer
jonathanpwang Feb 7, 2023
631a71e
fix: `builder::assign_*` was not handling cases where two gates overlap
jonathanpwang Feb 7, 2023
22195f4
feat: update `gates::range` to working tests and new API
jonathanpwang Feb 7, 2023
eff200f
fix: change `AssignedValue` type to `KeccakAssignedValue` for
jonathanpwang Feb 8, 2023
bd55bf5
Initial version 0.3.0 of halo2-ecc (#12)
jonathanpwang Apr 15, 2023
10d1d9f
Fix: assert uses of size hint in release mode (#13)
jonathanpwang Apr 15, 2023
8ab531c
Fix: bit decomposition edge cases (#14)
jonathanpwang Apr 15, 2023
ac1a926
Initial checkpoint for halo2-ecc v0.3.0 (#15)
jonathanpwang Apr 15, 2023
d3f21dc
Fix: make `GateThreadBuilder` compatible with external usage (#16)
jonathanpwang Apr 15, 2023
514dbda
Fix: under-constrained `idx_to_indicator` (#17)
jonathanpwang Apr 15, 2023
11adaa1
Fix: soundness error in `FpChip::assert_eq` due to typo (#18)
jonathanpwang Apr 16, 2023
61e516d
Remove redundant code and prevent race conditions (#19)
jonathanpwang Apr 16, 2023
fe649ae
chore: use `info!` instead of `println` for params
jonathanpwang Apr 28, 2023
0a2964f
Fix: `inner_product_left_last` size hint (#25)
jonathanpwang Apr 28, 2023
6f0ca51
Add documentation for halo2-base (#27)
jonathanpwang May 3, 2023
06905cc
Smart Range Builder (#29)
jonathanpwang May 6, 2023
f566451
fix: `div_mod_var` when `a_num_bits <= b_num_bits` (#31)
jonathanpwang May 10, 2023
a79db0e
Feat: extend halo2 base test coverage (#35)
PatStiles May 18, 2023
086c62c
fix(ecdsa): allow u1*G == u2*PK case (#36)
jonathanpwang May 19, 2023
55eebd4
fix: `log2_ceil(0)` should return `0` (#37)
jonathanpwang May 19, 2023
0948203
Guard `ScalarField` byte representations to always be little-endian (…
jonathanpwang May 19, 2023
e477c34
fix: get_last_bit two errors (#39)
jonathanpwang May 19, 2023
7e564c8
Add documentation for all debug_asserts (#40)
jonathanpwang May 19, 2023
34f1e7e
fix: `FieldChip::divide` renamed `divide_unsafe` (#41)
jonathanpwang May 19, 2023
0f037e7
Use new types to validate input assumptions (#43)
jonathanpwang May 22, 2023
07f2eba
Better handling of EC point at infinity (#44)
jonathanpwang May 22, 2023
652f9e3
feat: use strict ec ops more often (#45)
jonathanpwang May 22, 2023
f978636
feat: add `parallelize_in` helper function (#46)
jonathanpwang May 22, 2023
e5cbf14
fix: minor code quality fixes (#47)
jonathanpwang May 22, 2023
28d6220
feat: `fixed_base::msm_par` handles identity point (#48)
jonathanpwang May 22, 2023
2c76cc3
chore: add assert for query_cell_at_pos (#50)
jonathanpwang May 23, 2023
0e176f3
feat: add Github CI running tests (#51)
jonathanpwang May 23, 2023
3fce68c
fix: ignore code block for doctest (#52)
jonathanpwang May 23, 2023
4a24493
feat: add docs and assert with non-empty array checks (#53)
jonathanpwang May 23, 2023
53e3ad3
Release 0.3.0 ecdsa tests (#54)
jonathanpwang May 23, 2023
bebfb39
chore: fix CI
jonathanpwang May 23, 2023
71cfc51
fix: `prop_test_is_less_than_safe` (#58)
jonathanpwang May 23, 2023
bce3c82
Add halo2-base readme (#66)
jonathanpwang May 26, 2023
282ee8e
fix: change all `1` to `1u64` to prevent unexpected overflow (#72)
jonathanpwang Jun 3, 2023
8b9bdc2
[Fix] Panic when dealing with identity point (#71)
jonathanpwang Jun 6, 2023
05cfc1c
fix: redundant check in `ec_sub_unequal`
jonathanpwang Jun 7, 2023
0be26d4
Add SafeType (#26)
nyunyunyunyu May 23, 2023
d3ed3a9
feat(CI): switch to larger runner
jonathanpwang Jun 9, 2023
e4b956b
fix(builder): handle empty ctx with only equality constraints
jonathanpwang Jun 9, 2023
5293793
feat: add SafeAddress and SafeUint160 (#85)
PatStiles Jun 14, 2023
f6b22ab
Merge release v0.3.0 into develop (#90)
jonathanpwang Jul 7, 2023
da451da
feat: `FpChip::range_check` now works with `max_bits < n * (k-1)` (#91)
jonathanpwang Jul 7, 2023
08a16ce
Feat: test suite (#92)
jonathanpwang Jul 20, 2023
d1beb92
chore: make `bit_length` const function
jonathanpwang Jul 21, 2023
160f503
feat: add debugging functions (#99)
jonathanpwang Jul 26, 2023
081d475
chore: remove cfg(test) for debug functions
jonathanpwang Jul 26, 2023
2b3dd5d
feat(halo2-base): add `GateChip::pow_var` (#103)
jonathanpwang Aug 6, 2023
0b16812
Use halo2curves v0.4.0 and ff v0.13 (#107)
jonathanpwang Aug 15, 2023
3408b7a
Add `sub_mul` to GateInstructions (#102)
mmagician Aug 8, 2023
a62ae5d
fix(test): `select_from_idx` wasn't calling the right function (#105)
mmagician Aug 9, 2023
7100c23
chore: add back RangeCircuitBuilder::config (#111)
jonathanpwang Aug 17, 2023
49aeedd
fix: `RangeCircuitBuilder::config` remember `lookup_bits`
jonathanpwang Aug 17, 2023
a7b5433
[Feat] Add Poseidon Hasher Chip (#110)
nyunyunyunyu Aug 17, 2023
f724c9b
feat: add VariableByteArray (#88)
PatStiles Aug 18, 2023
3bacff7
chore: reduce CI real prover load
jonathanpwang Aug 18, 2023
cd9b6a4
Rename PoseidonHasherChip to PoseidonHasher (#113)
nyunyunyunyu Aug 18, 2023
25e211a
chore(safe_types): add conversion `SafeType` to/from `FixLenBytes`
jonathanpwang Aug 21, 2023
b58046c
chore(safe_type): add `unsafe_to_safe_type` unsafe conversion fn
jonathanpwang Aug 21, 2023
204a699
feat: add `select_array_by_indicator` to `GateInstructions` (#115)
jonathanpwang Aug 21, 2023
1c33fbc
cleanup: use test-utils for benching (#112)
jonathanpwang Aug 22, 2023
83ca65e
fix(safe_types): `VarLenBytes` should allow `len == MAX_LEN` (#117)
jonathanpwang Aug 22, 2023
7b23747
[feat] Add Poseidon Chip (#114)
nyunyunyunyu Aug 22, 2023
9798c85
[chore] Reorg Folder Structure of hashes/zkevm (#118)
nyunyunyunyu Aug 22, 2023
9fac2a8
[fix] CI for zkevm hashes (#119)
nyunyunyunyu Aug 23, 2023
154cd8c
[chore] Split keccak implementation into multiple files (#120)
nyunyunyunyu Aug 23, 2023
89da366
feat: keccak constant visibility changes (#121)
MonkeyKing-1 Aug 24, 2023
eb4fe65
[feat] Keccak Raw Output (#122)
nyunyunyunyu Aug 27, 2023
15bca77
Virtual region managers and dynamic lookup support (#123)
jonathanpwang Aug 27, 2023
f4c7e2a
Use `raw_assign_{advice,fixed}` in keccak (#125)
jonathanpwang Aug 28, 2023
7831b00
[feat] PoseidonHasher supports multiple inputs in compact format (#127)
nyunyunyunyu Aug 28, 2023
7bdf089
[feat] Expose Keccack Raw Inputs in Bytes instead of Input RLCs (#124)
nyunyunyunyu Aug 29, 2023
d07b0d4
Bump `zkevm-hashes` to v0.1.4
jonathanpwang Aug 29, 2023
6c80289
chore: clippy fix
jonathanpwang Aug 29, 2023
f2cf3e8
Generic vertical gate assignment (#129)
jonathanpwang Aug 29, 2023
be52d1d
Add `deep_clone` to `BaseCircuitBuilder` (#131)
jonathanpwang Sep 1, 2023
edd239f
fix: `SingleCorePhaseManager` should not create thread in constructor
jonathanpwang Sep 2, 2023
f39fef3
chore: make `new_context` public
jonathanpwang Sep 3, 2023
608b8f2
Convenience functions and fixes for multi-phase (#133)
jonathanpwang Sep 4, 2023
2b03c17
chore: add `BaseCircuitBuilder::set_k` fn
jonathanpwang Sep 5, 2023
64c8123
fix: `CopyConstraintManager::clear` was dropping
jonathanpwang Sep 5, 2023
04a40d4
feat: impl `From<SafeByte>` for `AssignedValue`
jonathanpwang Sep 5, 2023
671f0cc
chore(poseidon): add `derive` statements
jonathanpwang Sep 5, 2023
d27e46a
fix(copy_constraints): backend permutation argument depends on order
jonathanpwang Sep 6, 2023
a1fec64
feat: add `left_pad` functions for var length arrays (#137)
jonathanpwang Sep 6, 2023
72b53bf
chore: use `PrimeField` for `OptimizedPoseidonSpec` (#139)
jonathanpwang Sep 8, 2023
0acc05a
chore: add getter functions to Poseidon spec (#140)
jonathanpwang Sep 8, 2023
61fda9d
feat: use `(TypeId, usize)` instead of `usize` for lookup tag (#142)
jonathanpwang Sep 9, 2023
58155d7
chore: add `ContextTag` type alias
jonathanpwang Sep 9, 2023
3a35050
feat(base): add `GateInstructions::inner_product_left` function (#143)
jonathanpwang Sep 9, 2023
9377d90
[feat] Keccak Coprocessor Leaf Circuit (#130)
nyunyunyunyu Sep 9, 2023
54044c9
[feat] App Circuit Utils for Keccak Coprocessor (#141)
nyunyunyunyu Sep 9, 2023
14bec5a
[chore] Fix fmt (#144)
nyunyunyunyu Sep 10, 2023
c2a9341
chore: add misc utility functions (#146)
jonathanpwang Sep 10, 2023
482bed6
feat(keccak): add `ingestion` module for Rust native input formatting…
jonathanpwang Sep 10, 2023
41ea795
chore(keccak): use `snark-verifier` native Poseidon for encoding (#148)
jonathanpwang Sep 10, 2023
1ea4f84
feat: optimize leaf poseidon with `hash_compact_chunk_inputs` (#149)
jonathanpwang Sep 11, 2023
2ccfc43
[chore] cleanup code (#150)
jonathanpwang Sep 11, 2023
18057d3
chore: get halo2-pse working again
jonathanpwang Sep 11, 2023
46c5769
Merge branch 'main' into release-0.4.0-rc0
jonathanpwang Sep 11, 2023
eb5b284
chore: fix fmt
jonathanpwang Sep 11, 2023
92277ce
[Doc] Keccak Doc (#145)
nyunyunyunyu Sep 11, 2023
1bf36b1
chore: pin snark-verifier branch
jonathanpwang Sep 11, 2023
12f190a
[fix] max_rows in BaseCircuitBuilder in Keccak Leaf Circuit (#152)
nyunyunyunyu Sep 12, 2023
9a2fc70
[chore] Remove Unnecessary Lookup in Keccak Coprocessor Leaf Circuit …
nyunyunyunyu Sep 18, 2023
17d297b
Revert "chore: pin snark-verifier branch"
jonathanpwang Sep 11, 2023
26b81a3
[rename] (coprocessor, leaf) -> (component, shard) (#161)
jonathanpwang Sep 18, 2023
712d889
[rename] (coprocessor, leaf) -> (component, shard) (#161)
jonathanpwang Sep 18, 2023
e36c45b
[fix] Multiple Phase Lookup (#162)
nyunyunyunyu Sep 19, 2023
d3828a4
[fix] Multiple Phase Lookup (#162)
nyunyunyunyu Sep 19, 2023
215fe1c
[chore] add conversion `SafePrimitive` to `QuantumCell::Existing` (#169)
jonathanpwang Sep 26, 2023
524c818
fix: bad import on halo2-pse
jonathanpwang Sep 26, 2023
7acbe4d
[chore] add conversion `SafePrimitive` to `QuantumCell::Existing` (#169)
jonathanpwang Sep 26, 2023
5a43f96
fix: bad import on halo2-pse
jonathanpwang Sep 26, 2023
4cd0844
chore: make `{Fixed,Var}LenBytes*` constructor public
jonathanpwang Sep 26, 2023
3f84ec2
chore: make `{Fixed,Var}LenBytes*` constructor public
jonathanpwang Sep 26, 2023
16fa9e5
chore(keccak): `format_requests` always returns true capacity (#171)
jonathanpwang Sep 28, 2023
dff0e63
[chore] derive `Hash` for `BaseCircuitParams` (#172)
jonathanpwang Sep 29, 2023
8a5d469
[chore] impl `AsRef, AsMut` for `BaseCircuitBuilder` to self (#173)
jonathanpwang Oct 1, 2023
addfbec
[chore] impl `AsRef, AsMut` for `BaseConfig` to self (#174)
jonathanpwang Oct 1, 2023
9e6c9a1
[chore] Add getters to `KeccakComponentShardCircuit` (#178)
jonathanpwang Oct 7, 2023
fef7316
[chore] Expose Keccak Packing (#180)
nyunyunyunyu Oct 10, 2023
5411321
[chore] Expose Keccak Format (#181)
nyunyunyunyu Oct 11, 2023
bf71f0e
[feat] basic dynamic lookup table gadget (#182)
jonathanpwang Oct 11, 2023
9ff8994
[chore] expose `spec` in `PoseidonHasher` (#183)
jonathanpwang Oct 16, 2023
ff0cadf
[chore] fix halo2-pse build error (#184)
jonathanpwang Oct 18, 2023
582f671
[feat] expose keccak table loading/packing functions for external cra…
jonathanpwang Oct 20, 2023
eef553c
[chore] add getters to `PoseidonCompactChunkInput` (#196)
jonathanpwang Oct 20, 2023
ca498e5
[chore] fix deref after using CopyGetters (#197)
jonathanpwang Oct 21, 2023
2e996ae
[feat] implement `CircuitExt` for `KeccakComponentShardCircuit` (#198)
jonathanpwang Oct 22, 2023
ee822b9
Merge branch 'release-0.4.0-rc' into develop
jonathanpwang Oct 23, 2023
267123f
chore: fix `snark-verifier-sdk` version
jonathanpwang Oct 23, 2023
4ba2efc
[chore] add `cargo audit` to CI (#207)
jonathanpwang Nov 2, 2023
d4bf2fa
[fix] `FieldChip::range_check` should take `FieldPoint` instead of `U…
jonathanpwang Nov 2, 2023
4bc9f0a
[feat] update docs (#211)
jonathanpwang Nov 3, 2023
4e78e40
[chore] fix dev graph tests (#212)
jonathanpwang Nov 3, 2023
a30e3b1
[fix] `BasicDynLookupConfig` needs selector on advice table to preven…
jonathanpwang Nov 3, 2023
6cc92c6
[feat] add keccak circuit tests against Known Answer Test vectors (#213)
jonathanpwang Nov 3, 2023
cba20ed
[chore] fix documentation (#215)
jonathanpwang Nov 3, 2023
67e3a0e
[chore] fix doc comment (#216)
jonathanpwang Nov 3, 2023
5e2706f
chore: fix halo2-pse compile
jonathanpwang Nov 12, 2023
70d6d8a
fix: `TypeId` in `ContextTag` not stable across builds (#217)
jonathanpwang Nov 13, 2023
dacb885
Merge branch 'release-0.4.0-rc' into release-0.4.1-rc
jonathanpwang Nov 13, 2023
b880af1
chore: fix RAM test to use `&str` type id
jonathanpwang Nov 13, 2023
adb9694
[chore] add crate prefix to `type_id`s (#218)
jonathanpwang Nov 14, 2023
b6a5750
chore: use halo2-axiom from crates.io
jonathanpwang Nov 16, 2023
d45800d
chore: use poseidon-primitives from crates.io
jonathanpwang Nov 16, 2023
26a4504
chore: Bump halo2-axiom to v0.4
jonathanpwang Nov 20, 2023
12e07e1
chore: add `get_mut` for keccak circuit params
jonathanpwang Nov 20, 2023
b6625fa
[fix] soundness bug in `BasicDynLookupConfig::assign_virtual_table_to…
jonathanpwang Nov 30, 2023
fe3e439
[chore] make `KeccakComponentShardCircuit` `inputs` into `RefCell` (#…
jonathanpwang Dec 10, 2023
ae6f378
chore: fix keccak capacity check (#232)
jonathanpwang Dec 10, 2023
4acc096
chore: add utility traits to aid in proving key generation (#227)
jonathanpwang Dec 13, 2023
aae4ae0
[chore] `get_pinning_after_keygen` uses `self` (#235)
jonathanpwang Dec 15, 2023
f323d89
fix(docs): `div_unsafe` docs (#237)
shuklaayush Dec 16, 2023
395cc26
chore: remove clippy warning
jonathanpwang Dec 28, 2023
e73f6ed
[chore] Keccak Output Computation Optimization (#242)
nyunyunyunyu Dec 30, 2023
21285fa
Merge -s ours branch 'main' into release-0.4.1-rc
jonathanpwang Jan 18, 2024
57d3e19
chore: update Cargo.toml
jonathanpwang Jan 18, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ jobs:
working-directory: "hashes/zkevm"
run: |
cargo test packed_multi_keccak_prover::k_14
cargo test bit_sha256_prover::k_10
cargo t test_vanilla_keccak_kat_vectors

lint:
Expand Down
7 changes: 2 additions & 5 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,5 @@ Cargo.lock

*.png

**/params/*
**/params/
**/proptest-regressions/
**/results/
**/*.DS_Store
/halo2_ecc/src/bn254/data/
/halo2_ecc/src/secp256k1/data/
6 changes: 3 additions & 3 deletions halo2-base/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "halo2-base"
version = "0.4.0"
version = "0.4.1"
authors = ["Intrinsic Technologies"]
license = "MIT"
edition = "2021"
Expand All @@ -16,15 +16,15 @@ num-integer = "0.1"
num-traits = "0.2"
rand_chacha = "0.3"
rustc-hash = "1.1"
rayon = "1.7"
rayon = "1.8"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
log = "0.4"
getset = "0.1.2"
ark-std = { version = "0.3.0", features = ["print-trace"], optional = true }

# Use Axiom's custom halo2 monorepo for faster proving when feature = "halo2-axiom" is on
halo2_proofs_axiom = { version = "0.3", package = "halo2-axiom", optional = true }
halo2_proofs_axiom = { version = "0.4", package = "halo2-axiom", optional = true }
# Use PSE halo2 and halo2curves for compatibility when feature = "halo2-pse" is on
halo2_proofs = { git = "https://github.com/privacy-scaling-explorations/halo2.git", rev = "7a21656", optional = true }

Expand Down
12 changes: 12 additions & 0 deletions halo2-base/src/gates/circuit/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -372,3 +372,15 @@ pub struct RangeStatistics {
/// Total special advice cells that need to be looked up, per phase
pub total_lookup_advice_per_phase: Vec<usize>,
}

impl<F: ScalarField> AsRef<BaseCircuitBuilder<F>> for BaseCircuitBuilder<F> {
fn as_ref(&self) -> &BaseCircuitBuilder<F> {
self
}
}

impl<F: ScalarField> AsMut<BaseCircuitBuilder<F>> for BaseCircuitBuilder<F> {
fn as_mut(&mut self) -> &mut BaseCircuitBuilder<F> {
self
}
}
14 changes: 13 additions & 1 deletion halo2-base/src/gates/circuit/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub mod builder;

/// A struct defining the configuration parameters for a halo2-base circuit
/// - this is used to configure [BaseConfig].
#[derive(Clone, Default, Debug, Serialize, Deserialize)]
#[derive(Clone, Default, Debug, Hash, Serialize, Deserialize)]
pub struct BaseCircuitParams {
// Keeping FlexGateConfigParams expanded for backwards compatibility
/// Specifies the number of rows in the circuit to be 2<sup>k</sup>
Expand Down Expand Up @@ -215,3 +215,15 @@ impl CircuitBuilderStage {
matches!(self, CircuitBuilderStage::Prover)
}
}

impl<F: ScalarField> AsRef<BaseConfig<F>> for BaseConfig<F> {
fn as_ref(&self) -> &BaseConfig<F> {
self
}
}

impl<F: ScalarField> AsMut<BaseConfig<F>> for BaseConfig<F> {
fn as_mut(&mut self) -> &mut BaseConfig<F> {
self
}
}
6 changes: 3 additions & 3 deletions halo2-base/src/gates/flex_gate/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,9 +303,9 @@ pub trait GateInstructions<F: ScalarField> {
ctx.assign_region([Constant(F::ZERO), Existing(x), Existing(x), Existing(x)], [0]);
}

/// Constrains and returns a / b = 0.
/// Constrains and returns a / b = out.
///
/// Defines a vertical gate of form | 0 | b^1 * a | b | a |, where b^1 * a = out.
/// Defines a vertical gate of form | 0 | a / b | b | a |, where a / b = out.
///
/// Assumes `b != 0`.
/// * `ctx`: [Context] to add the constraints to
Expand Down Expand Up @@ -823,7 +823,7 @@ pub trait GateInstructions<F: ScalarField> {

/// Constrains and returns little-endian bit vector representation of `a`.
///
/// Assumes `range_bits <= number of bits in a`.
/// Assumes `range_bits >= bit_length(a)`.
/// * `a`: [QuantumCell] of the value to convert
/// * `range_bits`: range of bits needed to represent `a`
fn num_to_bits(
Expand Down
10 changes: 8 additions & 2 deletions halo2-base/src/gates/flex_gate/threads/single_phase.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,9 +219,15 @@ pub fn assign_with_constraints<F: ScalarField, const ROTATIONS: usize>(
.assign_advice(|| "", column, row_offset, || value.map(|v| *v))
.unwrap()
.cell();
copy_manager
if let Some(old_cell) = copy_manager
.assigned_advices
.insert(ContextCell::new(ctx.type_id, ctx.context_id, i), cell);
.insert(ContextCell::new(ctx.type_id, ctx.context_id, i), cell)
{
assert!(
old_cell.row_offset == cell.row_offset && old_cell.column == cell.column,
"Trying to overwrite virtual cell with a different raw cell"
);
}

// If selector enabled and row_offset is valid add break point, account for break point overlap, and enforce equality constraint for gate outputs.
// ⚠️ This assumes overlap is of form: gate enabled at `i - delta` and `i`, where `delta = ROTATIONS - 1`. We currently do not support `delta < ROTATIONS - 1`.
Expand Down
31 changes: 19 additions & 12 deletions halo2-base/src/poseidon/hasher/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::{
ScalarField,
};

use getset::Getters;
use getset::{CopyGetters, Getters};
use num_bigint::BigUint;
use std::{cell::OnceCell, mem};

Expand All @@ -23,8 +23,10 @@ pub mod spec;
pub mod state;

/// Stateless Poseidon hasher.
#[derive(Clone, Debug)]
#[derive(Clone, Debug, Getters)]
pub struct PoseidonHasher<F: ScalarField, const T: usize, const RATE: usize> {
/// Spec, contains round constants and optimized matrices.
#[getset(get = "pub")]
spec: OptimizedPoseidonSpec<F, T, RATE>,
consts: OnceCell<PoseidonHasherConsts<F, T, RATE>>,
}
Expand All @@ -51,13 +53,16 @@ impl<F: ScalarField, const T: usize, const RATE: usize> PoseidonHasherConsts<F,
}

/// 1 logical row of compact input for Poseidon hasher.
#[derive(Copy, Clone, Debug)]
#[derive(Copy, Clone, Debug, Getters, CopyGetters)]
pub struct PoseidonCompactInput<F: ScalarField, const RATE: usize> {
// Right padded inputs. No constrains on paddings.
/// Right padded inputs. No constrains on paddings.
#[getset(get = "pub")]
inputs: [AssignedValue<F>; RATE],
// is_final = 1 triggers squeeze.
/// is_final = 1 triggers squeeze.
#[getset(get_copy = "pub")]
is_final: SafeBool<F>,
// Length of `inputs`.
/// Length of `inputs`.
#[getset(get_copy = "pub")]
len: AssignedValue<F>,
}

Expand Down Expand Up @@ -87,11 +92,13 @@ impl<F: ScalarField, const RATE: usize> PoseidonCompactInput<F, RATE> {
}

/// A compact chunk input for Poseidon hasher. The end of a logical input could only be at the boundary of a chunk.
#[derive(Clone, Debug)]
#[derive(Clone, Debug, Getters, CopyGetters)]
pub struct PoseidonCompactChunkInput<F: ScalarField, const RATE: usize> {
// Inputs of a chunk. All witnesses will be absorbed.
/// Inputs of a chunk. All witnesses will be absorbed.
#[getset(get = "pub")]
inputs: Vec<[AssignedValue<F>; RATE]>,
// is_final = 1 triggers squeeze.
/// is_final = 1 triggers squeeze.
#[getset(get_copy = "pub")]
is_final: SafeBool<F>,
}

Expand All @@ -103,13 +110,13 @@ impl<F: ScalarField, const RATE: usize> PoseidonCompactChunkInput<F, RATE> {
}

/// 1 logical row of compact output for Poseidon hasher.
#[derive(Copy, Clone, Debug, Getters)]
#[derive(Copy, Clone, Debug, CopyGetters)]
pub struct PoseidonCompactOutput<F: ScalarField> {
/// hash of 1 logical input.
#[getset(get = "pub")]
#[getset(get_copy = "pub")]
hash: AssignedValue<F>,
/// is_final = 1 ==> this is the end of a logical input.
#[getset(get = "pub")]
#[getset(get_copy = "pub")]
is_final: SafeBool<F>,
}

Expand Down
2 changes: 1 addition & 1 deletion halo2-base/src/poseidon/hasher/tests/hasher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ fn hasher_compact_chunk_inputs_compatiblity_verification<
for (compact_output, chunk_input) in compact_outputs.iter().zip(chunk_inputs) {
// into() doesn't work if ! is in the beginning in the bool expression...
let is_final_input = chunk_input.is_final.as_ref().value();
let is_final_output = compact_output.is_final().as_ref().value();
let is_final_output = compact_output.is_final.as_ref().value();
assert_eq!(is_final_input, is_final_output);
if is_final_output == &Fr::ONE {
assert_eq!(native_results[output_offset], *compact_output.hash().value());
Expand Down
114 changes: 113 additions & 1 deletion halo2-base/src/utils/halo2.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
use std::collections::hash_map::Entry;

use crate::ff::Field;
use crate::halo2_proofs::{
circuit::{AssignedCell, Cell, Region, Value},
plonk::{Advice, Assigned, Column, Fixed},
plonk::{Advice, Assigned, Circuit, Column, Fixed},
};
use crate::virtual_region::copy_constraints::{CopyConstraintManager, EXTERNAL_CELL_TYPE_ID};
use crate::AssignedValue;

/// Raw (physical) assigned cell in Plonkish arithmetization.
#[cfg(feature = "halo2-axiom")]
Expand Down Expand Up @@ -71,3 +75,111 @@ pub fn raw_constrain_equal<F: Field>(region: &mut Region<F>, left: Cell, right:
#[cfg(not(feature = "halo2-axiom"))]
region.constrain_equal(left, right).unwrap();
}

/// Constrains that `virtual_cell` is equal to `external_cell`. The `virtual_cell` must have
/// already been raw assigned with the raw assigned cell stored in `copy_manager`
/// **unless** it is marked an external-only cell with type id [EXTERNAL_CELL_TYPE_ID].
/// * When the virtual cell has already been assigned, the assigned cell is constrained to be equal to the external cell.
/// * When the virtual cell has not been assigned **and** it is marked as an external cell, it is assigned to `external_cell` and the mapping is stored in `copy_manager`.
///
/// This should only be called when `witness_gen_only` is false, otherwise it will panic.
///
/// ## Panics
/// If witness generation only mode is true.
pub fn constrain_virtual_equals_external<F: Field + Ord>(
region: &mut Region<F>,
virtual_cell: AssignedValue<F>,
external_cell: Cell,
copy_manager: &mut CopyConstraintManager<F>,
) {
let ctx_cell = virtual_cell.cell.unwrap();
match copy_manager.assigned_advices.entry(ctx_cell) {
Entry::Occupied(acell) => {
// The virtual cell has already been assigned, so we can constrain it to equal the external cell.
region.constrain_equal(*acell.get(), external_cell);
}
Entry::Vacant(assigned) => {
// The virtual cell **must** be an external cell
assert_eq!(ctx_cell.type_id, EXTERNAL_CELL_TYPE_ID);
// We map the virtual cell to point to the raw external cell in `copy_manager`
assigned.insert(external_cell);
}
}
}

/// This trait should be implemented on the minimal circuit configuration data necessary to
/// completely determine a circuit (independent of circuit inputs).
/// This is used to generate a _dummy_ instantiation of a concrete `Circuit` type for the purposes of key generation.
/// This dummy instantiation just needs to have the correct arithmetization format, but the witnesses do not need to
/// satisfy constraints.
pub trait KeygenCircuitIntent<F: Field> {
/// Concrete circuit type
type ConcreteCircuit: Circuit<F>;
/// Additional data that "pins" down the circuit. These can always to deterministically rederived from `Self`, but
/// storing the `Pinning` saves recomputations in future proof generations.
type Pinning;

/// The intent must include the log_2 domain size of the circuit.
/// This is used to get the correct trusted setup file.
fn get_k(&self) -> u32;

/// Builds a _dummy_ instantiation of `Self::ConcreteCircuit` for the purposes of key generation.
/// This dummy instantiation just needs to have the correct arithmetization format, but the witnesses do not need to
/// satisfy constraints.
fn build_keygen_circuit(self) -> Self::ConcreteCircuit;

/// Pinning is only fully computed after `synthesize` has been run during keygen
fn get_pinning_after_keygen(
self,
kzg_params: &ParamsKZG<Bn256>,
circuit: &Self::ConcreteCircuit,
) -> Self::Pinning;
}

use halo2_proofs_axiom::halo2curves::bn256::Bn256;
use halo2_proofs_axiom::poly::kzg::commitment::ParamsKZG;
pub use keygen::ProvingKeyGenerator;

mod keygen {
use halo2_proofs_axiom::poly::commitment::Params;

use crate::halo2_proofs::{
halo2curves::bn256::{Bn256, Fr, G1Affine},
plonk::{self, ProvingKey},
poly::kzg::commitment::ParamsKZG,
};

use super::KeygenCircuitIntent;

/// Trait for creating a proving key and a pinning for a circuit from minimal circuit configuration data.
pub trait ProvingKeyGenerator {
/// Create proving key and pinning.
fn create_pk_and_pinning(
self,
kzg_params: &ParamsKZG<Bn256>,
) -> (ProvingKey<G1Affine>, serde_json::Value);
}

impl<CI> ProvingKeyGenerator for CI
where
CI: KeygenCircuitIntent<Fr> + Clone,
CI::Pinning: serde::Serialize,
{
fn create_pk_and_pinning(
self,
kzg_params: &ParamsKZG<Bn256>,
) -> (ProvingKey<G1Affine>, serde_json::Value) {
assert_eq!(kzg_params.k(), self.get_k());
let circuit = self.clone().build_keygen_circuit();
#[cfg(feature = "halo2-axiom")]
let pk = plonk::keygen_pk2(kzg_params, &circuit, false).unwrap();
#[cfg(not(feature = "halo2-axiom"))]
let pk = {
let vk = plonk::keygen_vk_custom(kzg_params, &circuit, false).unwrap();
plonk::keygen_pk(kzg_params, vk, &circuit).unwrap()
};
let pinning = self.get_pinning_after_keygen(kzg_params, &circuit);
(pk, serde_json::to_value(pinning).unwrap())
}
}
}
13 changes: 10 additions & 3 deletions halo2-base/src/virtual_region/copy_constraints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ use crate::{ff::Field, ContextCell};

use super::manager::VirtualRegionManager;

/// Type ID to distinguish external raw Halo2 cells. **This Type ID must be unique.**
pub const EXTERNAL_CELL_TYPE_ID: &str = "halo2-base:External Raw Halo2 Cell";

/// Thread-safe shared global manager for all copy constraints.
pub type SharedCopyConstraintManager<F> = Arc<Mutex<CopyConstraintManager<F>>>;

Expand Down Expand Up @@ -86,11 +89,15 @@ impl<F: Field + Ord> CopyConstraintManager<F> {
}

fn load_external_cell_impl(&mut self, cell: Option<Cell>) -> ContextCell {
let context_cell =
ContextCell::new("halo2-base:External Raw Halo2 Cell", 0, self.external_cell_count);
let context_cell = ContextCell::new(EXTERNAL_CELL_TYPE_ID, 0, self.external_cell_count);
self.external_cell_count += 1;
if let Some(cell) = cell {
self.assigned_advices.insert(context_cell, cell);
if let Some(old_cell) = self.assigned_advices.insert(context_cell, cell) {
assert!(
old_cell.row_offset == cell.row_offset && old_cell.column == cell.column,
"External cell already assigned"
)
}
}
context_cell
}
Expand Down
Loading
Loading