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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
use halo2_proofs::{
circuit::{AssignedCell, Chip, Layouter},
plonk::{Advice, Column, ConstraintSystem, Constraints, Error, Selector},
poly::Rotation,
};
use pasta_curves::{arithmetic::FieldExt, pallas};
use super::MerkleInstructions;
use crate::{
primitives::sinsemilla,
{
ecc::FixedPoints,
sinsemilla::{
chip::{SinsemillaChip, SinsemillaConfig},
CommitDomains, HashDomains, SinsemillaInstructions,
},
utilities::{
bitrange_subset,
cond_swap::{CondSwapChip, CondSwapConfig, CondSwapInstructions},
UtilitiesInstructions,
},
},
};
use group::ff::PrimeField;
#[derive(Clone, Debug)]
pub struct MerkleConfig<Hash, Commit, Fixed>
where
Hash: HashDomains<pallas::Affine>,
Fixed: FixedPoints<pallas::Affine>,
Commit: CommitDomains<pallas::Affine, Fixed, Hash>,
{
advices: [Column<Advice>; 5],
q_decompose: Selector,
pub(super) cond_swap_config: CondSwapConfig,
pub(super) sinsemilla_config: SinsemillaConfig<Hash, Commit, Fixed>,
}
#[derive(Clone, Debug)]
pub struct MerkleChip<Hash, Commit, Fixed>
where
Hash: HashDomains<pallas::Affine>,
Fixed: FixedPoints<pallas::Affine>,
Commit: CommitDomains<pallas::Affine, Fixed, Hash>,
{
config: MerkleConfig<Hash, Commit, Fixed>,
}
impl<Hash, Commit, Fixed> Chip<pallas::Base> for MerkleChip<Hash, Commit, Fixed>
where
Hash: HashDomains<pallas::Affine>,
Fixed: FixedPoints<pallas::Affine>,
Commit: CommitDomains<pallas::Affine, Fixed, Hash>,
{
type Config = MerkleConfig<Hash, Commit, Fixed>;
type Loaded = ();
fn config(&self) -> &Self::Config {
&self.config
}
fn loaded(&self) -> &Self::Loaded {
&()
}
}
impl<Hash, Commit, F> MerkleChip<Hash, Commit, F>
where
Hash: HashDomains<pallas::Affine>,
F: FixedPoints<pallas::Affine>,
Commit: CommitDomains<pallas::Affine, F, Hash>,
{
pub fn configure(
meta: &mut ConstraintSystem<pallas::Base>,
sinsemilla_config: SinsemillaConfig<Hash, Commit, F>,
) -> MerkleConfig<Hash, Commit, F> {
let advices = sinsemilla_config.advices();
let cond_swap_config = CondSwapChip::configure(meta, advices);
let q_decompose = meta.selector();
meta.create_gate("Decomposition check", |meta| {
let q_decompose = meta.query_selector(q_decompose);
let l_whole = meta.query_advice(advices[4], Rotation::next());
let two_pow_5 = pallas::Base::from(1 << 5);
let two_pow_10 = two_pow_5.square();
let a_whole = meta.query_advice(advices[0], Rotation::cur());
let b_whole = meta.query_advice(advices[1], Rotation::cur());
let c_whole = meta.query_advice(advices[2], Rotation::cur());
let left_node = meta.query_advice(advices[3], Rotation::cur());
let right_node = meta.query_advice(advices[4], Rotation::cur());
let z1_a = meta.query_advice(advices[0], Rotation::next());
let a_1 = z1_a;
let a_0 = a_whole - a_1.clone() * pallas::Base::from(1 << 10);
let l_check = a_0 - l_whole;
let z1_b = meta.query_advice(advices[1], Rotation::next());
let b_1 = meta.query_advice(advices[2], Rotation::next());
let b_2 = meta.query_advice(advices[3], Rotation::next());
let b1_b2_check = z1_b.clone() - (b_1.clone() + b_2.clone() * two_pow_5);
let b_0 = b_whole - (z1_b * two_pow_10);
let left_check = {
let reconstructed = {
let two_pow_240 = pallas::Base::from_u128(1 << 120).square();
a_1 + (b_0 + b_1 * two_pow_10) * two_pow_240
};
reconstructed - left_node
};
let right_check = b_2 + c_whole * two_pow_5 - right_node;
Constraints::with_selector(
q_decompose,
[
("l_check", l_check),
("left_check", left_check),
("right_check", right_check),
("b1_b2_check", b1_b2_check),
],
)
});
MerkleConfig {
advices,
q_decompose,
cond_swap_config,
sinsemilla_config,
}
}
pub fn construct(config: MerkleConfig<Hash, Commit, F>) -> Self {
MerkleChip { config }
}
}
impl<Hash, Commit, F, const MERKLE_DEPTH: usize>
MerkleInstructions<pallas::Affine, MERKLE_DEPTH, { sinsemilla::K }, { sinsemilla::C }>
for MerkleChip<Hash, Commit, F>
where
Hash: HashDomains<pallas::Affine>,
F: FixedPoints<pallas::Affine>,
Commit: CommitDomains<pallas::Affine, F, Hash>,
{
#[allow(non_snake_case)]
fn hash_layer(
&self,
mut layouter: impl Layouter<pallas::Base>,
Q: pallas::Affine,
l: usize,
left: Self::Var,
right: Self::Var,
) -> Result<Self::Var, Error> {
let config = self.config().clone();
let a = {
let a = {
let a_0 = bitrange_subset(&pallas::Base::from(l as u64), 0..10);
let a_1 = left.value().map(|value| bitrange_subset(value, 0..240));
a_1.map(|a_1| a_0 + a_1 * pallas::Base::from(1 << 10))
};
self.witness_message_piece(layouter.namespace(|| "Witness a = a_0 || a_1"), a, 25)?
};
let (b_1, b_2, b) = {
let b_0 = left.value().map(|value| bitrange_subset(value, 240..250));
let b_1 = {
let b_1 = left
.value()
.map(|value| bitrange_subset(value, 250..(pallas::Base::NUM_BITS as usize)));
config
.sinsemilla_config
.lookup_config()
.witness_short_check(layouter.namespace(|| "Constrain b_1 to 5 bits"), b_1, 5)?
};
let b_2 = {
let b_2 = right.value().map(|value| bitrange_subset(value, 0..5));
config
.sinsemilla_config
.lookup_config()
.witness_short_check(layouter.namespace(|| "Constrain b_2 to 5 bits"), b_2, 5)?
};
let b = {
let b = b_0
.zip(b_1.value())
.zip(b_2.value())
.map(|((b_0, b_1), b_2)| {
b_0 + b_1 * pallas::Base::from(1 << 10) + b_2 * pallas::Base::from(1 << 15)
});
self.witness_message_piece(
layouter.namespace(|| "Witness b = b_0 || b_1 || b_2"),
b,
2,
)?
};
(b_1, b_2, b)
};
let c = {
let c = right
.value()
.map(|value| bitrange_subset(value, 5..(pallas::Base::NUM_BITS as usize)));
self.witness_message_piece(layouter.namespace(|| "Witness c"), c, 25)?
};
let (point, zs) = self.hash_to_point(
layouter.namespace(|| format!("hash at l = {}", l)),
Q,
vec![a.clone(), b.clone(), c.clone()].into(),
)?;
let z1_a = zs[0][1].clone();
let z1_b = zs[1][1].clone();
{
layouter.assign_region(
|| "Check piece decomposition",
|mut region| {
config.q_decompose.enable(&mut region, 0)?;
region.assign_advice_from_constant(
|| format!("l {}", l),
config.advices[4],
1,
pallas::Base::from(l as u64),
)?;
a.cell_value()
.copy_advice(|| "copy a", &mut region, config.advices[0], 0)?;
b.cell_value()
.copy_advice(|| "copy b", &mut region, config.advices[1], 0)?;
c.cell_value()
.copy_advice(|| "copy c", &mut region, config.advices[2], 0)?;
left.copy_advice(|| "left", &mut region, config.advices[3], 0)?;
right.copy_advice(|| "right", &mut region, config.advices[4], 0)?;
z1_a.copy_advice(|| "z1_a", &mut region, config.advices[0], 1)?;
z1_b.copy_advice(|| "z1_b", &mut region, config.advices[1], 1)?;
b_1.copy_advice(|| "b_1", &mut region, config.advices[2], 1)?;
b_2.copy_advice(|| "b_2", &mut region, config.advices[3], 1)?;
Ok(())
},
)?;
}
let result = Self::extract(&point);
#[cfg(test)]
{
use crate::{primitives::sinsemilla::HashDomain, utilities::i2lebsp};
use group::ff::PrimeFieldBits;
if let (Some(left), Some(right)) = (left.value(), right.value()) {
let l = i2lebsp::<10>(l as u64);
let left: Vec<_> = left
.to_le_bits()
.iter()
.by_val()
.take(pallas::Base::NUM_BITS as usize)
.collect();
let right: Vec<_> = right
.to_le_bits()
.iter()
.by_val()
.take(pallas::Base::NUM_BITS as usize)
.collect();
let merkle_crh = HashDomain::from_Q(Q.into());
let mut message = l.to_vec();
message.extend_from_slice(&left);
message.extend_from_slice(&right);
let expected = merkle_crh.hash(message.into_iter()).unwrap();
assert_eq!(expected.to_repr(), result.value().unwrap().to_repr());
}
}
Ok(result)
}
}
impl<Hash, Commit, F> UtilitiesInstructions<pallas::Base> for MerkleChip<Hash, Commit, F>
where
Hash: HashDomains<pallas::Affine>,
F: FixedPoints<pallas::Affine>,
Commit: CommitDomains<pallas::Affine, F, Hash>,
{
type Var = AssignedCell<pallas::Base, pallas::Base>;
}
impl<Hash, Commit, F> CondSwapInstructions<pallas::Base> for MerkleChip<Hash, Commit, F>
where
Hash: HashDomains<pallas::Affine>,
F: FixedPoints<pallas::Affine>,
Commit: CommitDomains<pallas::Affine, F, Hash>,
{
#[allow(clippy::type_complexity)]
fn swap(
&self,
layouter: impl Layouter<pallas::Base>,
pair: (Self::Var, Option<pallas::Base>),
swap: Option<bool>,
) -> Result<(Self::Var, Self::Var), Error> {
let config = self.config().cond_swap_config.clone();
let chip = CondSwapChip::<pallas::Base>::construct(config);
chip.swap(layouter, pair, swap)
}
}
impl<Hash, Commit, F> SinsemillaInstructions<pallas::Affine, { sinsemilla::K }, { sinsemilla::C }>
for MerkleChip<Hash, Commit, F>
where
Hash: HashDomains<pallas::Affine>,
F: FixedPoints<pallas::Affine>,
Commit: CommitDomains<pallas::Affine, F, Hash>,
{
type CellValue = <SinsemillaChip<Hash, Commit, F> as SinsemillaInstructions<
pallas::Affine,
{ sinsemilla::K },
{ sinsemilla::C },
>>::CellValue;
type Message = <SinsemillaChip<Hash, Commit, F> as SinsemillaInstructions<
pallas::Affine,
{ sinsemilla::K },
{ sinsemilla::C },
>>::Message;
type MessagePiece = <SinsemillaChip<Hash, Commit, F> as SinsemillaInstructions<
pallas::Affine,
{ sinsemilla::K },
{ sinsemilla::C },
>>::MessagePiece;
type RunningSum = <SinsemillaChip<Hash, Commit, F> as SinsemillaInstructions<
pallas::Affine,
{ sinsemilla::K },
{ sinsemilla::C },
>>::RunningSum;
type X = <SinsemillaChip<Hash, Commit, F> as SinsemillaInstructions<
pallas::Affine,
{ sinsemilla::K },
{ sinsemilla::C },
>>::X;
type NonIdentityPoint = <SinsemillaChip<Hash, Commit, F> as SinsemillaInstructions<
pallas::Affine,
{ sinsemilla::K },
{ sinsemilla::C },
>>::NonIdentityPoint;
type FixedPoints = <SinsemillaChip<Hash, Commit, F> as SinsemillaInstructions<
pallas::Affine,
{ sinsemilla::K },
{ sinsemilla::C },
>>::FixedPoints;
type HashDomains = <SinsemillaChip<Hash, Commit, F> as SinsemillaInstructions<
pallas::Affine,
{ sinsemilla::K },
{ sinsemilla::C },
>>::HashDomains;
type CommitDomains = <SinsemillaChip<Hash, Commit, F> as SinsemillaInstructions<
pallas::Affine,
{ sinsemilla::K },
{ sinsemilla::C },
>>::CommitDomains;
fn witness_message_piece(
&self,
layouter: impl Layouter<pallas::Base>,
value: Option<pallas::Base>,
num_words: usize,
) -> Result<Self::MessagePiece, Error> {
let config = self.config().sinsemilla_config.clone();
let chip = SinsemillaChip::<Hash, Commit, F>::construct(config);
chip.witness_message_piece(layouter, value, num_words)
}
#[allow(non_snake_case)]
#[allow(clippy::type_complexity)]
fn hash_to_point(
&self,
layouter: impl Layouter<pallas::Base>,
Q: pallas::Affine,
message: Self::Message,
) -> Result<(Self::NonIdentityPoint, Vec<Vec<Self::CellValue>>), Error> {
let config = self.config().sinsemilla_config.clone();
let chip = SinsemillaChip::<Hash, Commit, F>::construct(config);
chip.hash_to_point(layouter, Q, message)
}
fn extract(point: &Self::NonIdentityPoint) -> Self::X {
SinsemillaChip::<Hash, Commit, F>::extract(point)
}
}