This repository was archived by the owner on Mar 24, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathsangria_poseidon.rs
198 lines (167 loc) · 5.7 KB
/
sangria_poseidon.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
use std::{array, io, marker::PhantomData, num::NonZeroUsize, path::Path};
use bn256::G1 as C1;
use criterion::{black_box, criterion_group, Criterion};
use grumpkin::G1 as C2;
use metadata::LevelFilter;
use sirius::{
commitment::CommitmentKey,
ff::{Field, FromUniformBytes, PrimeFieldBits},
group::{prime::PrimeCurve, Group},
halo2_proofs::{
circuit::{AssignedCell, Layouter},
plonk::ConstraintSystem,
},
halo2curves::{bn256, grumpkin, CurveAffine, CurveExt},
ivc::{
sangria::{CircuitPublicParamsInput, PublicParams, IVC},
step_circuit, StepCircuit, SynthesisError,
},
main_gate::{MainGate, MainGateConfig, RegionCtx, WrapValue},
poseidon::{self, poseidon_circuit::PoseidonChip, ROPair, Spec},
};
use tracing::*;
use tracing_subscriber::{fmt::format::FmtSpan, EnvFilter};
const ARITY: usize = 1;
const CIRCUIT_TABLE_SIZE1: usize = 17;
const CIRCUIT_TABLE_SIZE2: usize = 17;
const COMMITMENT_KEY_SIZE: usize = 21;
// Spec for user defined poseidon circuit
const T1: usize = 3;
const RATE1: usize = 2;
const R_F1: usize = 4;
const R_P1: usize = 3;
#[derive(Clone, Debug)]
struct TestPoseidonCircuitConfig {
pconfig: MainGateConfig<T1>,
}
#[derive(Default, Debug, Clone)]
struct TestPoseidonCircuit<F: PrimeFieldBits> {
_p: PhantomData<F>,
}
impl<F: PrimeFieldBits + FromUniformBytes<64>> StepCircuit<ARITY, F> for TestPoseidonCircuit<F> {
type Config = TestPoseidonCircuitConfig;
fn configure(meta: &mut ConstraintSystem<F>) -> Self::Config {
let pconfig = MainGate::configure(meta);
Self::Config { pconfig }
}
fn synthesize_step(
&self,
config: Self::Config,
layouter: &mut impl Layouter<F>,
z_in: &[AssignedCell<F, F>; ARITY],
) -> Result<[AssignedCell<F, F>; ARITY], SynthesisError> {
let spec = Spec::<F, T1, RATE1>::new(R_F1, R_P1);
let mut pchip = PoseidonChip::new(config.pconfig, spec);
let input = z_in.iter().map(|x| x.into()).collect::<Vec<WrapValue<F>>>();
pchip.update(&input);
let output = layouter
.assign_region(
|| "poseidon hash",
|region| {
let ctx = &mut RegionCtx::new(region, 0);
pchip.squeeze(ctx)
},
)
.map_err(SynthesisError::Halo2)?;
Ok([output])
}
}
// specs for IVC circuit
const T: usize = 5;
const RATE: usize = 4;
type RandomOracle = poseidon::PoseidonRO<T, RATE>;
type RandomOracleConstant<F> = <RandomOracle as ROPair<F>>::Args;
const LIMB_WIDTH: NonZeroUsize = unsafe { NonZeroUsize::new_unchecked(32) };
const LIMBS_COUNT: NonZeroUsize = unsafe { NonZeroUsize::new_unchecked(10) };
type C1Affine = <C1 as PrimeCurve>::Affine;
type C2Affine = <C2 as PrimeCurve>::Affine;
type C1Scalar = <C1 as Group>::Scalar;
type C2Scalar = <C2 as Group>::Scalar;
const FOLDER: &str = ".cache/examples";
#[instrument]
fn get_or_create_commitment_key<C: CurveAffine>(
k: usize,
label: &'static str,
) -> io::Result<CommitmentKey<C>> {
unsafe { CommitmentKey::load_or_setup_cache(Path::new(FOLDER), label, k) }
}
pub fn criterion_benchmark(c: &mut Criterion) {
let _span = info_span!("poseidon_bench").entered();
let prepare_span = info_span!("prepare").entered();
// C1
let sc1 = TestPoseidonCircuit::default();
// C2
let sc2 = step_circuit::trivial::Circuit::<ARITY, _>::default();
let primary_spec = RandomOracleConstant::<<C1 as CurveExt>::ScalarExt>::new(10, 10);
let secondary_spec = RandomOracleConstant::<<C2 as CurveExt>::ScalarExt>::new(10, 10);
let primary_commitment_key =
get_or_create_commitment_key::<bn256::G1Affine>(COMMITMENT_KEY_SIZE, "bn256")
.expect("Failed to get secondary key");
let secondary_commitment_key =
get_or_create_commitment_key::<grumpkin::G1Affine>(COMMITMENT_KEY_SIZE, "grumpkin")
.expect("Failed to get primary key");
let pp = PublicParams::<
'_,
ARITY,
ARITY,
T,
C1Affine,
C2Affine,
TestPoseidonCircuit<_>,
step_circuit::trivial::Circuit<ARITY, _>,
RandomOracle,
RandomOracle,
>::new(
CircuitPublicParamsInput::new(
CIRCUIT_TABLE_SIZE1 as u32,
&primary_commitment_key,
primary_spec,
&sc1,
),
CircuitPublicParamsInput::new(
CIRCUIT_TABLE_SIZE2 as u32,
&secondary_commitment_key,
secondary_spec,
&sc2,
),
LIMB_WIDTH,
LIMBS_COUNT,
)
.unwrap();
prepare_span.exit();
let mut group = c.benchmark_group("sangria_ivc_of_poseidon");
group.significance_level(0.1).sample_size(10);
group.bench_function("fold_1_step", |b| {
let mut rnd = rand::thread_rng();
let primary_z_0 = array::from_fn(|_| C1Scalar::random(&mut rnd));
let secondary_z_0 = array::from_fn(|_| C2Scalar::random(&mut rnd));
b.iter(|| {
IVC::fold(
&pp,
&sc1,
black_box(primary_z_0),
&sc2,
black_box(secondary_z_0),
NonZeroUsize::new(1).unwrap(),
)
.unwrap();
})
});
group.finish();
}
criterion_group!(benches, criterion_benchmark);
fn main() {
tracing_subscriber::fmt()
.with_span_events(FmtSpan::ENTER | FmtSpan::CLOSE)
.with_env_filter(
EnvFilter::builder()
.with_default_directive(LevelFilter::INFO.into())
.from_env_lossy(),
)
.json()
.init();
benches();
criterion::Criterion::default()
.configure_from_args()
.final_summary();
}