-
Notifications
You must be signed in to change notification settings - Fork 87
/
ecdsa.rs
359 lines (305 loc) · 12 KB
/
ecdsa.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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
use super::integer::{IntegerChip, IntegerConfig};
use crate::halo2;
use crate::integer;
use crate::maingate;
use ecc::maingate::RegionCtx;
use ecc::{AssignedPoint, EccConfig, GeneralEccChip};
use halo2::arithmetic::CurveAffine;
use halo2::halo2curves::ff::PrimeField;
use halo2::{circuit::Value, plonk::Error};
use integer::rns::Integer;
use integer::{AssignedInteger, IntegerInstructions};
use maingate::{MainGateConfig, RangeConfig};
#[derive(Clone, Debug)]
pub struct EcdsaConfig {
pub main_gate_config: MainGateConfig,
pub range_config: RangeConfig,
}
impl EcdsaConfig {
pub fn new(range_config: RangeConfig, main_gate_config: MainGateConfig) -> Self {
Self {
range_config,
main_gate_config,
}
}
pub fn ecc_chip_config(&self) -> EccConfig {
EccConfig::new(self.range_config.clone(), self.main_gate_config.clone())
}
pub fn integer_chip_config(&self) -> IntegerConfig {
IntegerConfig::new(self.range_config.clone(), self.main_gate_config.clone())
}
}
#[derive(Clone, Debug)]
pub struct EcdsaSig<
W: PrimeField,
N: PrimeField,
const NUMBER_OF_LIMBS: usize,
const BIT_LEN_LIMB: usize,
> {
pub r: Integer<W, N, NUMBER_OF_LIMBS, BIT_LEN_LIMB>,
pub s: Integer<W, N, NUMBER_OF_LIMBS, BIT_LEN_LIMB>,
}
pub struct AssignedEcdsaSig<
W: PrimeField,
N: PrimeField,
const NUMBER_OF_LIMBS: usize,
const BIT_LEN_LIMB: usize,
> {
pub r: AssignedInteger<W, N, NUMBER_OF_LIMBS, BIT_LEN_LIMB>,
pub s: AssignedInteger<W, N, NUMBER_OF_LIMBS, BIT_LEN_LIMB>,
}
pub struct AssignedPublicKey<
W: PrimeField,
N: PrimeField,
const NUMBER_OF_LIMBS: usize,
const BIT_LEN_LIMB: usize,
> {
pub point: AssignedPoint<W, N, NUMBER_OF_LIMBS, BIT_LEN_LIMB>,
}
pub struct EcdsaChip<
E: CurveAffine,
N: PrimeField,
const NUMBER_OF_LIMBS: usize,
const BIT_LEN_LIMB: usize,
>(GeneralEccChip<E, N, NUMBER_OF_LIMBS, BIT_LEN_LIMB>);
impl<E: CurveAffine, N: PrimeField, const NUMBER_OF_LIMBS: usize, const BIT_LEN_LIMB: usize>
EcdsaChip<E, N, NUMBER_OF_LIMBS, BIT_LEN_LIMB>
{
pub fn new(ecc_chip: GeneralEccChip<E, N, NUMBER_OF_LIMBS, BIT_LEN_LIMB>) -> Self {
Self(ecc_chip)
}
pub fn scalar_field_chip(
&self,
) -> &IntegerChip<E::ScalarExt, N, NUMBER_OF_LIMBS, BIT_LEN_LIMB> {
self.0.scalar_field_chip()
}
fn ecc_chip(&self) -> GeneralEccChip<E, N, NUMBER_OF_LIMBS, BIT_LEN_LIMB> {
self.0.clone()
}
}
impl<E: CurveAffine, N: PrimeField, const NUMBER_OF_LIMBS: usize, const BIT_LEN_LIMB: usize>
EcdsaChip<E, N, NUMBER_OF_LIMBS, BIT_LEN_LIMB>
{
pub fn verify(
&self,
ctx: &mut RegionCtx<'_, N>,
sig: &AssignedEcdsaSig<E::Scalar, N, NUMBER_OF_LIMBS, BIT_LEN_LIMB>,
pk: &AssignedPublicKey<E::Base, N, NUMBER_OF_LIMBS, BIT_LEN_LIMB>,
msg_hash: &AssignedInteger<E::Scalar, N, NUMBER_OF_LIMBS, BIT_LEN_LIMB>,
) -> Result<(), Error> {
let ecc_chip = self.ecc_chip();
let scalar_chip = ecc_chip.scalar_field_chip();
let base_chip = ecc_chip.base_field_chip();
// 1. check 0 < r, s < n
// since `assert_not_zero` already includes a in-field check, we can just
// call `assert_not_zero`
scalar_chip.assert_not_zero(ctx, &sig.r)?;
scalar_chip.assert_not_zero(ctx, &sig.s)?;
// 2. w = s^(-1) (mod n)
let (s_inv, _) = scalar_chip.invert(ctx, &sig.s)?;
// 3. u1 = m' * w (mod n)
let u1 = scalar_chip.mul(ctx, msg_hash, &s_inv)?;
// 4. u2 = r * w (mod n)
let u2 = scalar_chip.mul(ctx, &sig.r, &s_inv)?;
// 5. compute Q = u1*G + u2*pk
let e_gen = ecc_chip.assign_point(ctx, Value::known(E::generator()))?;
let pairs = vec![(e_gen, u1), (pk.point.clone(), u2)];
let q = ecc_chip.mul_batch_1d_horizontal(ctx, pairs, 4)?;
// 6. reduce q_x in E::ScalarExt
// assuming E::Base/E::ScalarExt have the same number of limbs
let q_x = q.x();
let q_x_reduced_in_q = base_chip.reduce(ctx, q_x)?;
let q_x_reduced_in_r = scalar_chip.reduce_external(ctx, &q_x_reduced_in_q)?;
// 7. check if Q.x == r (mod n)
scalar_chip.assert_strict_equal(ctx, &q_x_reduced_in_r, &sig.r)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::{AssignedEcdsaSig, AssignedPublicKey, EcdsaChip};
use crate::halo2;
use crate::integer;
use crate::maingate;
use ecc::integer::Range;
use ecc::maingate::big_to_fe;
use ecc::maingate::fe_to_big;
use ecc::maingate::RegionCtx;
use ecc::{EccConfig, GeneralEccChip};
use halo2::arithmetic::CurveAffine;
use halo2::circuit::{Layouter, SimpleFloorPlanner, Value};
use halo2::halo2curves::{
ff::{Field, FromUniformBytes, PrimeField},
group::{Curve, Group},
};
use halo2::plonk::{Circuit, ConstraintSystem, Error};
use integer::IntegerInstructions;
use maingate::mock_prover_verify;
use maingate::{MainGate, MainGateConfig, RangeChip, RangeConfig, RangeInstructions};
use rand_core::OsRng;
use std::marker::PhantomData;
const BIT_LEN_LIMB: usize = 68;
const NUMBER_OF_LIMBS: usize = 4;
#[derive(Clone, Debug)]
struct TestCircuitEcdsaVerifyConfig {
main_gate_config: MainGateConfig,
range_config: RangeConfig,
}
impl TestCircuitEcdsaVerifyConfig {
pub fn new<C: CurveAffine, N: PrimeField>(meta: &mut ConstraintSystem<N>) -> Self {
let (rns_base, rns_scalar) =
GeneralEccChip::<C, N, NUMBER_OF_LIMBS, BIT_LEN_LIMB>::rns();
let main_gate_config = MainGate::<N>::configure(meta);
let mut overflow_bit_lens: Vec<usize> = vec![];
overflow_bit_lens.extend(rns_base.overflow_lengths());
overflow_bit_lens.extend(rns_scalar.overflow_lengths());
let composition_bit_lens = vec![BIT_LEN_LIMB / NUMBER_OF_LIMBS];
let range_config = RangeChip::<N>::configure(
meta,
&main_gate_config,
composition_bit_lens,
overflow_bit_lens,
);
TestCircuitEcdsaVerifyConfig {
main_gate_config,
range_config,
}
}
pub fn ecc_chip_config(&self) -> EccConfig {
EccConfig::new(self.range_config.clone(), self.main_gate_config.clone())
}
pub fn config_range<N: PrimeField>(
&self,
layouter: &mut impl Layouter<N>,
) -> Result<(), Error> {
let range_chip = RangeChip::<N>::new(self.range_config.clone());
range_chip.load_table(layouter)?;
Ok(())
}
}
#[derive(Default, Clone)]
struct TestCircuitEcdsaVerify<E: CurveAffine, N: PrimeField> {
public_key: Value<E>,
signature: Value<(E::Scalar, E::Scalar)>,
msg_hash: Value<E::Scalar>,
aux_generator: E,
window_size: usize,
_marker: PhantomData<N>,
}
impl<E: CurveAffine, N: PrimeField> Circuit<N> for TestCircuitEcdsaVerify<E, N> {
type Config = TestCircuitEcdsaVerifyConfig;
type FloorPlanner = SimpleFloorPlanner;
#[cfg(feature = "circuit-params")]
type Params = ();
fn without_witnesses(&self) -> Self {
Self::default()
}
fn configure(meta: &mut ConstraintSystem<N>) -> Self::Config {
TestCircuitEcdsaVerifyConfig::new::<E, N>(meta)
}
fn synthesize(
&self,
config: Self::Config,
mut layouter: impl Layouter<N>,
) -> Result<(), Error> {
let mut ecc_chip = GeneralEccChip::<E, N, NUMBER_OF_LIMBS, BIT_LEN_LIMB>::new(
config.ecc_chip_config(),
);
layouter.assign_region(
|| "assign aux values",
|region| {
let offset = 0;
let ctx = &mut RegionCtx::new(region, offset);
ecc_chip.assign_aux_generator(ctx, Value::known(self.aux_generator))?;
ecc_chip.assign_aux(ctx, self.window_size, 2)?;
Ok(())
},
)?;
let ecdsa_chip = EcdsaChip::new(ecc_chip.clone());
let scalar_chip = ecc_chip.scalar_field_chip();
layouter.assign_region(
|| "region 0",
|region| {
let offset = 0;
let ctx = &mut RegionCtx::new(region, offset);
let r = self.signature.map(|signature| signature.0);
let s = self.signature.map(|signature| signature.1);
let integer_r = ecc_chip.new_unassigned_scalar(r);
let integer_s = ecc_chip.new_unassigned_scalar(s);
let msg_hash = ecc_chip.new_unassigned_scalar(self.msg_hash);
let r_assigned =
scalar_chip.assign_integer(ctx, integer_r, Range::Remainder)?;
let s_assigned =
scalar_chip.assign_integer(ctx, integer_s, Range::Remainder)?;
let sig = AssignedEcdsaSig {
r: r_assigned,
s: s_assigned,
};
let pk_in_circuit = ecc_chip.assign_point(ctx, self.public_key)?;
let pk_assigned = AssignedPublicKey {
point: pk_in_circuit,
};
let msg_hash = scalar_chip.assign_integer(ctx, msg_hash, Range::Remainder)?;
ecdsa_chip.verify(ctx, &sig, &pk_assigned, &msg_hash)
},
)?;
config.config_range(&mut layouter)?;
Ok(())
}
}
#[test]
fn test_ecdsa_verifier() {
fn mod_n<C: CurveAffine>(x: C::Base) -> C::Scalar {
let x_big = fe_to_big(x);
big_to_fe(x_big)
}
fn run<C: CurveAffine, N: FromUniformBytes<64> + Ord>() {
let g = C::generator();
// Generate a key pair
let sk = <C as CurveAffine>::ScalarExt::random(OsRng);
let public_key = (g * sk).to_affine();
// Generate a valid signature
// Suppose `m_hash` is the message hash
let msg_hash = <C as CurveAffine>::ScalarExt::random(OsRng);
// Draw arandomness
let k = <C as CurveAffine>::ScalarExt::random(OsRng);
let k_inv = k.invert().unwrap();
// Calculate `r`
let r_point = (g * k).to_affine().coordinates().unwrap();
let x = r_point.x();
let r = mod_n::<C>(*x);
// Calculate `s`
let s = k_inv * (msg_hash + (r * sk));
// Sanity check. Ensure we construct a valid signature. So lets verify it
{
let s_inv = s.invert().unwrap();
let u_1 = msg_hash * s_inv;
let u_2 = r * s_inv;
let r_point = ((g * u_1) + (public_key * u_2))
.to_affine()
.coordinates()
.unwrap();
let x_candidate = r_point.x();
let r_candidate = mod_n::<C>(*x_candidate);
assert_eq!(r, r_candidate);
}
let aux_generator = C::CurveExt::random(OsRng).to_affine();
let circuit = TestCircuitEcdsaVerify::<C, N> {
public_key: Value::known(public_key),
signature: Value::known((r, s)),
msg_hash: Value::known(msg_hash),
aux_generator,
window_size: 4,
..Default::default()
};
let instance = vec![vec![]];
mock_prover_verify(&circuit, instance);
}
use crate::curves::bn256::Fr as BnScalar;
use crate::curves::pasta::{Fp as PastaFp, Fq as PastaFq};
use crate::curves::secp256k1::Secp256k1Affine as Secp256k1;
run::<Secp256k1, BnScalar>();
run::<Secp256k1, PastaFp>();
run::<Secp256k1, PastaFq>();
}
}