This repository was archived by the owner on Apr 18, 2025. It is now read-only.
forked from privacy-scaling-explorations/zkevm-circuits
-
Notifications
You must be signed in to change notification settings - Fork 390
/
Copy pathbatch_data.rs
1577 lines (1427 loc) · 64.9 KB
/
batch_data.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
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::{
blob_consistency::BLOB_WIDTH, constants::N_BYTES_U256, BatchHash, ChunkInfo, RlcConfig,
};
use eth_types::{H256, U256};
use ethers_core::utils::keccak256;
use halo2_ecc::bigint::CRTInteger;
use halo2_proofs::{
circuit::{AssignedCell, Layouter, Region, Value},
halo2curves::bn256::Fr,
plonk::{Advice, Column, ConstraintSystem, Error, Expression, SecondPhase, Selector},
poly::Rotation,
};
use itertools::Itertools;
use std::iter::{once, repeat};
use zkevm_circuits::{
table::{KeccakTable, LookupTable, RangeTable, U8Table},
util::{Challenges, Expr},
};
/// The number data bytes we pack each BLS12-381 scalar into. The most-significant byte is 0.
pub const N_DATA_BYTES_PER_COEFFICIENT: usize = 31;
/// The number of bytes that we can fit in a blob. Note that each coefficient is represented in 32
/// bytes, however, since those 32 bytes must represent a BLS12-381 scalar in its canonical form,
/// we explicitly set the most-significant byte to 0, effectively utilising only 31 bytes.
pub const N_BLOB_BYTES: usize = BLOB_WIDTH * N_DATA_BYTES_PER_COEFFICIENT;
/// Allow up to 5x compression via zstd encoding of the batch data.
const N_BATCH_BYTES: usize = N_BLOB_BYTES * 5;
/// The number of rows to encode number of valid chunks (num_valid_snarks) in a batch, in the Blob
/// Data config. Since num_valid_chunks is u16, we use 2 bytes/rows.
const N_ROWS_NUM_CHUNKS: usize = 2;
/// The number of rows to encode chunk size (u32).
const N_ROWS_CHUNK_SIZE: usize = 4;
#[derive(Clone, Debug)]
pub struct BatchDataConfig<const N_SNARKS: usize> {
/// The byte value at this row.
byte: Column<Advice>,
/// The accumulator serves several purposes.
/// 1. For the metadata section, the accumulator holds the running linear combination of the
/// chunk size.
/// 2. For the chunk data section, the accumulator holds the incremental chunk size, which
/// resets to 1 if we encounter a chunk boundary. The accumulator here is referenced while
/// doing a lookup to the Keccak table that requires the input length.
accumulator: Column<Advice>,
/// An increasing counter that denotes the chunk ID. The chunk ID is from [1, N_SNARKS].
chunk_idx: Column<Advice>,
/// A boolean witness that is set only when we encounter the end of a chunk. We enable a lookup
/// to the Keccak table when the boundary is met.
is_boundary: Column<Advice>,
/// A running accumulator of the boundary counts.
boundary_count: Column<Advice>,
/// A boolean witness to indicate padded rows at the end of the data section.
is_padding: Column<Advice>,
/// A running accumulator of the RLC of every byte seen so far.
bytes_rlc: Column<Advice>,
/// Represents the running random linear combination of bytes seen so far, that are a part of
/// the preimage to the Keccak hash. It resets whenever we encounter a chunk boundary.
preimage_rlc: Column<Advice>,
/// Represents the random linear combination of the Keccak digest. This has meaningful values
/// only at the rows where we actually do the Keccak lookup.
digest_rlc: Column<Advice>,
/// Boolean to let us know we are in the "chunk data" section.
pub data_selector: Selector,
/// Boolean to let us know we are in the "digest rlc" section.
pub hash_selector: Selector,
/// Fixed table that consists of [0, 256).
u8_table: U8Table,
/// Fixed table that consists of [0, N_SNARKS).
chunk_idx_range_table: RangeTable<N_SNARKS>,
}
pub struct AssignedBatchDataExport {
pub num_valid_chunks: AssignedCell<Fr, Fr>,
pub batch_data_len: AssignedCell<Fr, Fr>,
pub versioned_hash: Vec<AssignedCell<Fr, Fr>>,
pub chunk_data_digests: Vec<Vec<AssignedCell<Fr, Fr>>>,
pub bytes_rlc: AssignedCell<Fr, Fr>,
}
pub struct AssignedBatchDataConfig {
pub byte: AssignedCell<Fr, Fr>,
pub accumulator: AssignedCell<Fr, Fr>,
pub chunk_idx: AssignedCell<Fr, Fr>,
pub is_boundary: AssignedCell<Fr, Fr>,
pub boundary_count: AssignedCell<Fr, Fr>,
pub is_padding: AssignedCell<Fr, Fr>,
pub bytes_rlc: AssignedCell<Fr, Fr>,
pub preimage_rlc: AssignedCell<Fr, Fr>,
pub digest_rlc: AssignedCell<Fr, Fr>,
}
impl<const N_SNARKS: usize> BatchDataConfig<N_SNARKS> {
pub fn configure(
meta: &mut ConstraintSystem<Fr>,
challenge: &Challenges<Expression<Fr>>,
u8_table: U8Table,
range_table: RangeTable<N_SNARKS>,
keccak_table: &KeccakTable,
) -> Self {
let n_rows_metadata = BatchData::<N_SNARKS>::n_rows_metadata();
let config = Self {
u8_table,
chunk_idx_range_table: range_table,
byte: meta.advice_column(),
accumulator: meta.advice_column(),
is_boundary: meta.advice_column(),
boundary_count: meta.advice_column(),
chunk_idx: meta.advice_column(),
is_padding: meta.advice_column(),
bytes_rlc: meta.advice_column_in(SecondPhase),
preimage_rlc: meta.advice_column_in(SecondPhase),
digest_rlc: meta.advice_column_in(SecondPhase),
data_selector: meta.complex_selector(),
hash_selector: meta.complex_selector(),
};
// TODO: reduce the number of permutation columns
meta.enable_equality(config.byte);
meta.enable_equality(config.accumulator);
meta.enable_equality(config.is_boundary);
meta.enable_equality(config.boundary_count);
meta.enable_equality(config.is_padding);
meta.enable_equality(config.chunk_idx);
meta.enable_equality(config.bytes_rlc);
meta.enable_equality(config.preimage_rlc);
meta.enable_equality(config.digest_rlc);
let r = challenge.keccak_input();
meta.lookup("BatchDataConfig (0 < byte < 256)", |meta| {
let byte_value = meta.query_advice(config.byte, Rotation::cur());
vec![(byte_value, u8_table.into())]
});
meta.lookup(
"BatchDataConfig (chunk idx transition on boundary)",
|meta| {
let is_hash = meta.query_selector(config.hash_selector);
let is_not_hash = 1.expr() - is_hash;
let is_padding_next = meta.query_advice(config.is_padding, Rotation::next());
let is_boundary = meta.query_advice(config.is_boundary, Rotation::cur());
// if we are in the data section, encounter a boundary and the next row is not a
// padding row.
let cond = is_not_hash * is_boundary * (1.expr() - is_padding_next);
let chunk_idx_curr = meta.query_advice(config.chunk_idx, Rotation::cur());
let chunk_idx_next = meta.query_advice(config.chunk_idx, Rotation::next());
// chunk_idx increases by at least 1 and at most N_SNARKS when condition is met.
vec![(
cond * (chunk_idx_next - chunk_idx_curr - 1.expr()),
config.chunk_idx_range_table.into(),
)]
},
);
meta.lookup(
"BatchDataConfig (chunk_idx for non-padding, data rows in [1..N_SNARKS])",
|meta| {
let is_data = meta.query_selector(config.data_selector);
let is_padding = meta.query_advice(config.is_padding, Rotation::cur());
let chunk_idx = meta.query_advice(config.chunk_idx, Rotation::cur());
vec![(
is_data * (1.expr() - is_padding) * (chunk_idx - 1.expr()),
config.chunk_idx_range_table.into(),
)]
},
);
meta.create_gate("BatchDataConfig (boolean columns)", |meta| {
let is_data = meta.query_selector(config.data_selector);
let is_hash = meta.query_selector(config.hash_selector);
// is_data is never 1 when is_hash is 1, so we can add these selectors and still have a
// boolean condition.
let cond = is_data.clone() + is_hash.clone();
let is_boundary = meta.query_advice(config.is_boundary, Rotation::cur());
let is_padding = meta.query_advice(config.is_padding, Rotation::cur());
vec![
cond.clone() * is_boundary.clone() * (1.expr() - is_boundary),
cond * is_padding.clone() * (1.expr() - is_padding),
]
});
meta.create_gate("BatchDataConfig (transition when boundary)", |meta| {
let is_data = meta.query_selector(config.data_selector);
let is_boundary = meta.query_advice(config.is_boundary, Rotation::cur());
let is_padding_next = meta.query_advice(config.is_padding, Rotation::next());
let cond = is_data * is_boundary;
let len_next = meta.query_advice(config.accumulator, Rotation::next());
let preimage_rlc_next = meta.query_advice(config.preimage_rlc, Rotation::next());
let byte_next = meta.query_advice(config.byte, Rotation::next());
let boundary_count_curr = meta.query_advice(config.boundary_count, Rotation::cur());
let boundary_count_prev = meta.query_advice(config.boundary_count, Rotation::prev());
vec![
// if boundary followed by padding, length and preimage_rlc is 0.
cond.expr() * is_padding_next.expr() * len_next.expr(),
cond.expr() * is_padding_next.expr() * preimage_rlc_next.expr(),
// if boundary not followed by padding, length resets to 1, preimage_rlc resets to
// the byte value.
cond.expr() * (1.expr() - is_padding_next.expr()) * (len_next.expr() - 1.expr()),
cond.expr()
* (1.expr() - is_padding_next.expr())
* (preimage_rlc_next - byte_next.expr()),
// the boundary count increments, i.e.
// boundary_count_curr == boundary_count_prev + 1
cond.expr() * (boundary_count_curr - boundary_count_prev - 1.expr()),
]
});
meta.create_gate("BatchDataConfig (transition when no boundary)", |meta| {
let is_data = meta.query_selector(config.data_selector);
let is_boundary = meta.query_advice(config.is_boundary, Rotation::cur());
let is_padding = meta.query_advice(config.is_padding, Rotation::cur());
// in the data section (not padding) when we traverse the same chunk.
let cond = is_data * (1.expr() - is_padding) * (1.expr() - is_boundary);
let chunk_idx_curr = meta.query_advice(config.chunk_idx, Rotation::cur());
let chunk_idx_next = meta.query_advice(config.chunk_idx, Rotation::next());
let len_curr = meta.query_advice(config.accumulator, Rotation::cur());
let len_next = meta.query_advice(config.accumulator, Rotation::next());
let preimage_rlc_curr = meta.query_advice(config.preimage_rlc, Rotation::cur());
let preimage_rlc_next = meta.query_advice(config.preimage_rlc, Rotation::next());
let byte_next = meta.query_advice(config.byte, Rotation::next());
let boundary_count_curr = meta.query_advice(config.boundary_count, Rotation::cur());
let boundary_count_prev = meta.query_advice(config.boundary_count, Rotation::prev());
let digest_rlc = meta.query_advice(config.digest_rlc, Rotation::cur());
vec![
// chunk idx unchanged.
cond.expr() * (chunk_idx_next - chunk_idx_curr),
// length is accumulated.
cond.expr() * (len_next - len_curr - 1.expr()),
// preimage rlc is updated.
cond.expr() * (preimage_rlc_curr * r.expr() + byte_next - preimage_rlc_next),
// boundary count continues.
cond.expr() * (boundary_count_curr - boundary_count_prev),
// digest_rlc is 0.
cond.expr() * digest_rlc,
]
});
meta.create_gate("BatchDataConfig (\"chunk data\" section)", |meta| {
let is_data = meta.query_selector(config.data_selector);
let is_padding_curr = meta.query_advice(config.is_padding, Rotation::cur());
let is_padding_next = meta.query_advice(config.is_padding, Rotation::next());
let diff = is_padding_next - is_padding_curr.expr();
let byte = meta.query_advice(config.byte, Rotation::cur());
let chunk_idx = meta.query_advice(config.chunk_idx, Rotation::cur());
let accumulator = meta.query_advice(config.accumulator, Rotation::cur());
let preimage_rlc = meta.query_advice(config.preimage_rlc, Rotation::cur());
let digest_rlc = meta.query_advice(config.digest_rlc, Rotation::cur());
let boundary_count_curr = meta.query_advice(config.boundary_count, Rotation::cur());
let boundary_count_prev = meta.query_advice(config.boundary_count, Rotation::prev());
let bytes_rlc_curr = meta.query_advice(config.bytes_rlc, Rotation::cur());
let bytes_rlc_prev = meta.query_advice(config.bytes_rlc, Rotation::prev());
vec![
// byte, accumulator, digest_rlc, preimage_rlc, chunk_idx iare 0 when padding in
// the "chunk data" section.
is_data.expr() * is_padding_curr.expr() * byte.expr(),
is_data.expr() * is_padding_curr.expr() * accumulator,
is_data.expr() * is_padding_curr.expr() * digest_rlc,
is_data.expr() * is_padding_curr.expr() * preimage_rlc,
is_data.expr() * is_padding_curr.expr() * chunk_idx,
// diff is 0 or 1, i.e. is_padding transitions from 0 -> 1 only once.
is_data.expr() * diff.expr() * (1.expr() - diff.expr()),
// boundary count continues if padding
is_data.expr()
* is_padding_curr.expr()
* (boundary_count_curr - boundary_count_prev),
// bytes rlc is accumulated appropriately
is_data.expr()
* is_padding_curr.expr()
* (bytes_rlc_curr.expr() - bytes_rlc_prev.expr()),
is_data.expr()
* (1.expr() - is_padding_curr.expr())
* (bytes_rlc_prev * r + byte - bytes_rlc_curr),
]
});
// lookup metadata and chunk data digests in keccak table.
meta.lookup_any(
"BatchDataConfig (metadata/chunk_data/challenge digests in keccak table)",
|meta| {
let is_data = meta.query_selector(config.data_selector);
let is_hash = meta.query_selector(config.hash_selector);
let is_not_hash = 1.expr() - is_hash;
let is_boundary = meta.query_advice(config.is_boundary, Rotation::cur());
// in the "metadata" or "chunk data" section, wherever is_boundary is set.
let cond = is_not_hash * is_boundary;
let accumulator = meta.query_advice(config.accumulator, Rotation::cur());
let preimage_len =
is_data.expr() * accumulator + (1.expr() - is_data) * n_rows_metadata.expr();
[
1.expr(), // q_enable
1.expr(), // is final
meta.query_advice(config.preimage_rlc, Rotation::cur()), // input RLC
preimage_len, // input len
meta.query_advice(config.digest_rlc, Rotation::cur()), // output RLC
]
.into_iter()
.zip_eq(keccak_table.table_exprs(meta))
.map(|(value, table)| (cond.expr() * value, table))
.collect()
},
);
// lookup chunk data digests in the "digest rlc section" of BatchDataConfig.
meta.lookup_any(
"BatchDataConfig (chunk data digests in BatchDataConfig \"hash section\")",
|meta| {
let is_data = meta.query_selector(config.data_selector);
let is_boundary = meta.query_advice(config.is_boundary, Rotation::cur());
// in the "chunk data" section when we encounter a chunk boundary
let cond = is_data * is_boundary;
let hash_section_table = vec![
meta.query_selector(config.hash_selector),
meta.query_advice(config.chunk_idx, Rotation::cur()),
meta.query_advice(config.accumulator, Rotation::cur()),
meta.query_advice(config.digest_rlc, Rotation::cur()),
];
[
1.expr(), // hash section
meta.query_advice(config.chunk_idx, Rotation::cur()), // chunk idx
meta.query_advice(config.accumulator, Rotation::cur()), // chunk len
meta.query_advice(config.digest_rlc, Rotation::cur()), // digest rlc
]
.into_iter()
.zip(hash_section_table)
.map(|(value, table)| (cond.expr() * value, table))
.collect()
},
);
// lookup challenge digest in keccak table.
meta.lookup_any(
"BatchDataConfig (metadata/chunk_data/challenge digests in keccak table)",
|meta| {
let is_hash = meta.query_selector(config.hash_selector);
let is_boundary = meta.query_advice(config.is_boundary, Rotation::cur());
// when is_boundary is set in the "digest RLC" section.
// this is also the last row of the "digest RLC" section.
let cond = is_hash * is_boundary;
// - metadata_digest: 32 bytes
// - chunk[i].chunk_data_digest: 32 bytes each
// - versioned_hash: 32 bytes
let preimage_len = 32.expr() * (N_SNARKS + 1 + 1).expr();
[
1.expr(), // q_enable
1.expr(), // is final
meta.query_advice(config.preimage_rlc, Rotation::cur()), // input rlc
preimage_len, // input len
meta.query_advice(config.digest_rlc, Rotation::cur()), // output rlc
]
.into_iter()
.zip_eq(keccak_table.table_exprs(meta))
.map(|(value, table)| (cond.expr() * value, table))
.collect()
},
);
log::trace!("meta degree: {}", meta.degree());
log::trace!(
"meta degree with lookups: {}",
meta.clone().chunk_lookups().degree(),
);
assert!(meta.degree() <= 5);
config
}
#[allow(clippy::too_many_arguments)]
pub fn assign(
&self,
layouter: &mut impl Layouter<Fr>,
challenge_value: Challenges<Value<Fr>>,
rlc_config: &RlcConfig,
// The chunks_are_padding assigned cells are exports from the conditional constraints in
// `core.rs`. Since these are already constrained, we can just use them as is.
chunks_are_padding: &[AssignedCell<Fr, Fr>],
batch_data: &BatchData<N_SNARKS>,
versioned_hash: H256,
challenge_digest: &CRTInteger<Fr>,
) -> Result<AssignedBatchDataExport, Error> {
self.load_range_tables(layouter)?;
let assigned_rows = layouter.assign_region(
|| "BatchData rows",
|mut region| self.assign_rows(&mut region, challenge_value, batch_data, versioned_hash),
)?;
layouter.assign_region(
|| "BatchData internal checks",
|mut region| {
self.assign_internal_checks(
&mut region,
challenge_value,
rlc_config,
chunks_are_padding,
challenge_digest,
&assigned_rows,
)
},
)
}
pub fn load_range_tables(&self, layouter: &mut impl Layouter<Fr>) -> Result<(), Error> {
self.u8_table.load(layouter)?;
self.chunk_idx_range_table.load(layouter)
}
pub fn assign_rows(
&self,
region: &mut Region<Fr>,
challenge_value: Challenges<Value<Fr>>,
batch_data: &BatchData<N_SNARKS>,
versioned_hash: H256,
) -> Result<Vec<AssignedBatchDataConfig>, Error> {
let n_rows_data = BatchData::<N_SNARKS>::n_rows_data();
let n_rows_metadata = BatchData::<N_SNARKS>::n_rows_metadata();
let n_rows_digest_rlc = BatchData::<N_SNARKS>::n_rows_digest_rlc();
let n_rows_total = BatchData::<N_SNARKS>::n_rows();
let rows = batch_data.to_rows(versioned_hash, challenge_value);
assert_eq!(rows.len(), n_rows_total);
// enable data selector
for offset in n_rows_metadata..n_rows_metadata + n_rows_data {
self.data_selector.enable(region, offset)?;
}
// enable hash selector
for offset in
n_rows_metadata + n_rows_data..n_rows_metadata + n_rows_data + n_rows_digest_rlc
{
self.hash_selector.enable(region, offset)?;
}
let mut assigned_rows = Vec::with_capacity(n_rows_total);
let mut count = 0u64;
let mut bytes_rlc_acc = Value::known(Fr::zero());
for (i, row) in rows.iter().enumerate() {
if !row.is_padding {
bytes_rlc_acc = bytes_rlc_acc * challenge_value.keccak_input()
+ Value::known(Fr::from(row.byte as u64));
}
let byte = region.assign_advice(
|| "byte",
self.byte,
i,
|| Value::known(Fr::from(row.byte as u64)),
)?;
let accumulator = region.assign_advice(
|| "accumulator",
self.accumulator,
i,
|| Value::known(Fr::from(row.accumulator)),
)?;
let chunk_idx = region.assign_advice(
|| "chunk_idx",
self.chunk_idx,
i,
|| Value::known(Fr::from(row.chunk_idx)),
)?;
let is_boundary = region.assign_advice(
|| "is_boundary",
self.is_boundary,
i,
|| Value::known(Fr::from(row.is_boundary as u64)),
)?;
let bcount = if (n_rows_metadata..n_rows_metadata + n_rows_data).contains(&i) {
count += row.is_boundary as u64;
count
} else {
0
};
let boundary_count = region.assign_advice(
|| "boundary_count",
self.boundary_count,
i,
|| Value::known(Fr::from(bcount)),
)?;
let is_padding = region.assign_advice(
|| "is_padding",
self.is_padding,
i,
|| Value::known(Fr::from(row.is_padding as u64)),
)?;
let preimage_rlc = region.assign_advice(
|| "preimage_rlc",
self.preimage_rlc,
i,
|| row.preimage_rlc,
)?;
let digest_rlc =
region.assign_advice(|| "digest_rlc", self.digest_rlc, i, || row.digest_rlc)?;
let bytes_rlc = region.assign_advice(
|| "bytes_rlc",
self.bytes_rlc,
i,
|| {
if i < n_rows_metadata + n_rows_data {
bytes_rlc_acc
} else {
Value::known(Fr::zero())
}
},
)?;
assigned_rows.push(AssignedBatchDataConfig {
byte,
accumulator,
chunk_idx,
is_boundary,
boundary_count,
is_padding,
bytes_rlc,
preimage_rlc,
digest_rlc,
});
}
Ok(assigned_rows)
}
pub fn assign_internal_checks(
&self,
region: &mut Region<Fr>,
challenge_value: Challenges<Value<Fr>>,
rlc_config: &RlcConfig,
// The chunks_are_padding assigned cells are exports from the conditional constraints in
// `core.rs`. Since these are already constrained, we can just use them as is.
chunks_are_padding: &[AssignedCell<Fr, Fr>],
assigned_challenge_digest: &CRTInteger<Fr>,
assigned_rows: &[AssignedBatchDataConfig],
) -> Result<AssignedBatchDataExport, Error> {
let n_rows_metadata = BatchData::<N_SNARKS>::n_rows_metadata();
let n_rows_digest_rlc = BatchData::<N_SNARKS>::n_rows_digest_rlc();
let n_rows_data = BatchData::<N_SNARKS>::n_rows_data();
rlc_config.init(region)?;
let mut rlc_config_offset = 0;
// load some constants that we will use later.
let zero = {
let zero = rlc_config.load_private(region, &Fr::zero(), &mut rlc_config_offset)?;
let zero_cell = rlc_config.zero_cell(zero.cell().region_index);
region.constrain_equal(zero.cell(), zero_cell)?;
zero
};
let one = {
let one = rlc_config.load_private(region, &Fr::one(), &mut rlc_config_offset)?;
let one_cell = rlc_config.one_cell(one.cell().region_index);
region.constrain_equal(one.cell(), one_cell)?;
one
};
let four = {
let four = rlc_config.load_private(region, &Fr::from(4), &mut rlc_config_offset)?;
let four_cell = rlc_config.four_cell(four.cell().region_index);
region.constrain_equal(four.cell(), four_cell)?;
four
};
let two_fifty_six = {
let two_fifty_six =
rlc_config.load_private(region, &Fr::from(256), &mut rlc_config_offset)?;
let two_fifty_six_cell = rlc_config
.pow_of_two_hundred_and_fifty_six_cell(two_fifty_six.cell().region_index, 1);
region.constrain_equal(two_fifty_six.cell(), two_fifty_six_cell)?;
two_fifty_six
};
let fixed_chunk_indices = {
let mut fixed_chunk_indices = vec![one.clone()];
for i in 2..=N_SNARKS {
let i_cell =
rlc_config.load_private(region, &Fr::from(i as u64), &mut rlc_config_offset)?;
// TODO: look into this....
let i_fixed_cell =
rlc_config.fixed_up_to_max_agg_snarks_cell(i_cell.cell().region_index, i);
region.constrain_equal(i_cell.cell(), i_fixed_cell)?;
fixed_chunk_indices.push(i_cell);
}
fixed_chunk_indices
};
let two = fixed_chunk_indices.get(1).expect("N_SNARKS >= 2");
let n_snarks = fixed_chunk_indices.last().expect("N_SNARKS >= 2");
// read randomness challenges for RLC computations.
let r_keccak =
rlc_config.read_challenge1(region, challenge_value, &mut rlc_config_offset)?;
let r_evm = rlc_config.read_challenge2(region, challenge_value, &mut rlc_config_offset)?;
let r32 = {
let r2 = rlc_config.mul(region, &r_keccak, &r_keccak, &mut rlc_config_offset)?;
let r4 = rlc_config.mul(region, &r2, &r2, &mut rlc_config_offset)?;
let r8 = rlc_config.mul(region, &r4, &r4, &mut rlc_config_offset)?;
let r16 = rlc_config.mul(region, &r8, &r8, &mut rlc_config_offset)?;
rlc_config.mul(region, &r16, &r16, &mut rlc_config_offset)?
};
// load cells representing the keccak digest of empty bytes.
let mut empty_digest_cells = Vec::with_capacity(N_BYTES_U256);
for (i, &byte) in keccak256([]).iter().enumerate() {
let cell =
rlc_config.load_private(region, &Fr::from(byte as u64), &mut rlc_config_offset)?;
let fixed_cell = rlc_config.empty_keccak_cell_i(cell.cell().region_index, i);
region.constrain_equal(cell.cell(), fixed_cell)?;
empty_digest_cells.push(cell);
}
let empty_digest_evm_rlc =
rlc_config.rlc(region, &empty_digest_cells, &r_evm, &mut rlc_config_offset)?;
////////////////////////////////////////////////////////////////////////////////
/////////////////////////////// NUM_VALID_CHUNKS ///////////////////////////////
////////////////////////////////////////////////////////////////////////////////
let rows = assigned_rows.iter().take(2).collect::<Vec<_>>();
let (byte_hi, byte_lo, lc1, lc2) = (
&rows[0].byte,
&rows[1].byte,
&rows[0].accumulator,
&rows[1].accumulator,
);
// the linear combination starts with the most-significant byte.
region.constrain_equal(byte_hi.cell(), lc1.cell())?;
// do the linear combination.
let num_valid_chunks =
rlc_config.mul_add(region, lc1, &two_fifty_six, byte_lo, &mut rlc_config_offset)?;
region.constrain_equal(num_valid_chunks.cell(), lc2.cell())?;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////// CHUNK_SIZE //////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
let mut num_nonempty_chunks = zero.clone();
let mut is_empty_chunks = Vec::with_capacity(N_SNARKS);
let mut chunk_sizes = Vec::with_capacity(N_SNARKS);
// init: batch_data_len = 4 * N_SNARKS + 2 (metadata).
let mut batch_data_len =
rlc_config.mul_add(region, &four, n_snarks, two, &mut rlc_config_offset)?;
for (i, is_padded_chunk) in chunks_are_padding.iter().enumerate() {
let rows = assigned_rows
.iter()
.skip(2 + 4 * i)
.take(4)
.collect::<Vec<_>>();
let (byte0, byte1, byte2, byte3) =
(&rows[0].byte, &rows[1].byte, &rows[2].byte, &rows[3].byte);
let (acc0, acc1, acc2, acc3) = (
&rows[0].accumulator,
&rows[1].accumulator,
&rows[2].accumulator,
&rows[3].accumulator,
);
// the linear combination starts with the most-significant byte.
region.constrain_equal(byte0.cell(), acc0.cell())?;
// do the linear combination.
let lc =
rlc_config.mul_add(region, acc0, &two_fifty_six, byte1, &mut rlc_config_offset)?;
region.constrain_equal(lc.cell(), acc1.cell())?;
let lc =
rlc_config.mul_add(region, acc1, &two_fifty_six, byte2, &mut rlc_config_offset)?;
region.constrain_equal(lc.cell(), acc2.cell())?;
let chunk_size =
rlc_config.mul_add(region, acc2, &two_fifty_six, byte3, &mut rlc_config_offset)?;
region.constrain_equal(chunk_size.cell(), acc3.cell())?;
// if the chunk is a padded chunk, its size must be set to 0.
rlc_config.conditional_enforce_equal(
region,
&chunk_size,
&zero,
is_padded_chunk,
&mut rlc_config_offset,
)?;
let is_empty_chunk = rlc_config.is_zero(region, &chunk_size, &mut rlc_config_offset)?;
let is_nonempty_chunk =
rlc_config.not(region, &is_empty_chunk, &mut rlc_config_offset)?;
num_nonempty_chunks = rlc_config.add(
region,
&is_nonempty_chunk,
&num_nonempty_chunks,
&mut rlc_config_offset,
)?;
batch_data_len =
rlc_config.add(region, &batch_data_len, &chunk_size, &mut rlc_config_offset)?;
is_empty_chunks.push(is_empty_chunk);
chunk_sizes.push(chunk_size);
}
let all_chunks_empty =
rlc_config.is_zero(region, &num_nonempty_chunks, &mut rlc_config_offset)?;
let not_all_chunks_empty =
rlc_config.not(region, &all_chunks_empty, &mut rlc_config_offset)?;
// constrain preimage_rlc column
let metadata_rows = &assigned_rows[..n_rows_metadata];
region.constrain_equal(
metadata_rows[0].byte.cell(),
metadata_rows[0].preimage_rlc.cell(),
)?;
for (i, row) in metadata_rows.iter().enumerate().skip(1) {
let preimage_rlc = rlc_config.mul_add(
region,
&metadata_rows[i - 1].preimage_rlc,
&r_keccak,
&row.byte,
&mut rlc_config_offset,
)?;
region.constrain_equal(preimage_rlc.cell(), row.preimage_rlc.cell())?;
}
// these columns are always 0 in the metadata section.
for row in metadata_rows.iter() {
let cells =
[&row.chunk_idx, &row.boundary_count, &row.is_padding].map(AssignedCell::cell);
for cell in cells {
region.constrain_equal(cell, zero.cell())?;
}
}
// in the metadata section, these columns are 0 except (possibly) on the last row.
for row in metadata_rows.iter().take(n_rows_metadata - 1) {
let cells = [&row.is_boundary, &row.digest_rlc].map(AssignedCell::cell);
for cell in cells {
region.constrain_equal(cell, zero.cell())?;
}
}
// in the final row of the metadata section, boundary is 1. note that this triggers a keccak
// lookup which constrains digest_rlc.
region.constrain_equal(
metadata_rows[n_rows_metadata - 1].is_boundary.cell(),
one.cell(),
)?;
// also check that the preimage_rlc at the last row of "metadata" section is equal to the
// bytes_rlc at that row. This value is later used in the custom gate in the "chunk data"
// section to compute the running accumulator bytes_rlc.
region.constrain_equal(
metadata_rows[n_rows_metadata - 1].preimage_rlc.cell(),
metadata_rows[n_rows_metadata - 1].bytes_rlc.cell(),
)?;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////// CHUNK_DATA //////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// the first data row has a length (accumulator) of 1. But in the special case that
// there are no non-empty chunks, this will be 0 and must also be a padding row.
let rows = assigned_rows
.iter()
.skip(n_rows_metadata)
.take(n_rows_data)
.collect::<Vec<_>>();
rlc_config.conditional_enforce_equal(
region,
&rows[0].accumulator,
&one,
¬_all_chunks_empty,
&mut rlc_config_offset,
)?;
rlc_config.conditional_enforce_equal(
region,
&rows[0].is_padding,
&zero,
¬_all_chunks_empty,
&mut rlc_config_offset,
)?;
rlc_config.conditional_enforce_equal(
region,
&rows[0].accumulator,
&zero,
&all_chunks_empty,
&mut rlc_config_offset,
)?;
rlc_config.conditional_enforce_equal(
region,
&rows[0].is_padding,
&one,
&all_chunks_empty,
&mut rlc_config_offset,
)?;
// get the boundary count at the end of the "chunk data" section, and equate it to
// the number of non-empty chunks in the batch.
region.constrain_equal(
rows.last().unwrap().boundary_count.cell(),
num_nonempty_chunks.cell(),
)?;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////// DIGEST RLC //////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
let rows = assigned_rows
.iter()
.skip(n_rows_metadata + n_rows_data)
.take(n_rows_digest_rlc)
.collect::<Vec<_>>();
// rows have chunk_idx set from 0 (metadata) -> N_SNARKS.
region.constrain_equal(rows[0].chunk_idx.cell(), zero.cell())?;
for (row, fixed_chunk_idx) in rows
.iter()
.skip(1)
.take(N_SNARKS)
.zip_eq(fixed_chunk_indices.iter())
{
region.constrain_equal(row.chunk_idx.cell(), fixed_chunk_idx.cell())?;
}
let challenge_digest_preimage_rlc_specified = &rows.last().unwrap().preimage_rlc;
let challenge_digest_rlc_specified = &rows.last().unwrap().digest_rlc;
let versioned_hash_rlc = &rows.get(n_rows_digest_rlc - 2).unwrap().digest_rlc;
// ensure that on the last row of this section the is_boundary is turned on
// which would enable the keccak table lookup for challenge_digest
region.constrain_equal(rows.last().unwrap().is_boundary.cell(), one.cell())?;
let metadata_digest_rlc_computed =
&assigned_rows.get(n_rows_metadata - 1).unwrap().digest_rlc;
let metadata_digest_rlc_specified = &rows.first().unwrap().digest_rlc;
region.constrain_equal(
metadata_digest_rlc_computed.cell(),
metadata_digest_rlc_specified.cell(),
)?;
// if the chunk is a padded chunk, then its chunk data digest should be the
// same as the previous chunk's data digest.
//
// Also, we know that the first chunk is valid. So we can just start the check from
// the second chunk's data digest.
region.constrain_equal(chunks_are_padding[0].cell(), zero.cell())?;
for i in 1..N_SNARKS {
// Note that in `rows`, the first row is the metadata row (hence anyway skip
// it). That's why we have a +1.
rlc_config.conditional_enforce_equal(
region,
&rows[i + 1].digest_rlc,
&rows[i].digest_rlc,
&chunks_are_padding[i],
&mut rlc_config_offset,
)?;
}
let mut chunk_digest_evm_rlcs = Vec::with_capacity(N_SNARKS);
for (((row, chunk_size_decoded), is_empty), is_padded_chunk) in rows
.iter()
.skip(1)
.take(N_SNARKS)
.zip_eq(chunk_sizes)
.zip_eq(is_empty_chunks)
.zip_eq(chunks_are_padding)
{
// if the chunk is a valid chunk (i.e. not padded chunk), but is empty (i.e. no
// L2 transactions), then the chunk's data digest should be the empty keccak
// digest.
let is_valid = rlc_config.not(region, is_padded_chunk, &mut rlc_config_offset)?;
let is_valid_empty =
rlc_config.mul(region, &is_valid, &is_empty, &mut rlc_config_offset)?;
rlc_config.conditional_enforce_equal(
region,
&row.digest_rlc,
&empty_digest_evm_rlc,
&is_valid_empty,
&mut rlc_config_offset,
)?;
// constrain chunk size specified here against decoded in metadata.
region.constrain_equal(row.accumulator.cell(), chunk_size_decoded.cell())?;
chunk_digest_evm_rlcs.push(&row.digest_rlc);
}
////////////////////////////////////////////////////////////////////////////////
///////////////////////////////// DIGEST BYTES /////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
let mut challenge_digest_preimage_keccak_rlc = zero.clone();
let rows = assigned_rows
.iter()
.skip(n_rows_metadata + n_rows_data + n_rows_digest_rlc)
.take(BatchData::<N_SNARKS>::n_rows_digest_bytes())
.collect::<Vec<_>>();
for (i, digest_rlc_specified) in std::iter::once(metadata_digest_rlc_specified)
.chain(chunk_digest_evm_rlcs)
.chain(std::iter::once(versioned_hash_rlc))
.chain(std::iter::once(challenge_digest_rlc_specified))
.enumerate()
{
let digest_rows = rows
.iter()
.skip(N_BYTES_U256 * i)
.take(N_BYTES_U256)
.collect::<Vec<_>>();
let digest_bytes = digest_rows
.iter()
.map(|row| row.byte.clone())
.collect::<Vec<_>>();
let digest_rlc_computed =
rlc_config.rlc(region, &digest_bytes, &r_evm, &mut rlc_config_offset)?;
region.constrain_equal(digest_rlc_computed.cell(), digest_rlc_specified.cell())?;
// compute the keccak input RLC:
// we do this only for the metadata and chunks, not for the blob row itself.
if i < N_SNARKS + 1 + 1 {
let digest_keccak_rlc =
rlc_config.rlc(region, &digest_bytes, &r_keccak, &mut rlc_config_offset)?;
challenge_digest_preimage_keccak_rlc = rlc_config.mul_add(
region,
&challenge_digest_preimage_keccak_rlc,
&r32,
&digest_keccak_rlc,
&mut rlc_config_offset,
)?;
}
}
region.constrain_equal(
challenge_digest_preimage_keccak_rlc.cell(),
challenge_digest_preimage_rlc_specified.cell(),
)?;
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////// EXPORT ////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
let mut chunk_data_digests = Vec::with_capacity(N_SNARKS);
let chunk_data_digests_bytes = assigned_rows
.iter()
.skip(n_rows_metadata + n_rows_data + n_rows_digest_rlc + N_BYTES_U256)
.take(N_SNARKS * N_BYTES_U256)
.map(|row| row.byte.clone())
.collect::<Vec<_>>();
for chunk in chunk_data_digests_bytes.chunks_exact(N_BYTES_U256) {
chunk_data_digests.push(chunk.to_vec());
}
let challenge_digest = assigned_rows
.iter()
.rev()
.take(N_BYTES_U256)
.map(|row| row.byte.clone())
.collect::<Vec<AssignedCell<Fr, Fr>>>();
let export = AssignedBatchDataExport {
num_valid_chunks,
batch_data_len,
versioned_hash: assigned_rows
.iter()
.rev()
.skip(N_BYTES_U256)
.take(N_BYTES_U256)
.map(|row| row.byte.clone())
.rev()
.collect(),
chunk_data_digests,
// bytes rlc is from the last row of the "chunk data" section.
bytes_rlc: assigned_rows
.get(n_rows_metadata + n_rows_data - 1)
.unwrap()
.bytes_rlc
.clone(),
};
////////////////////////////////////////////////////////////////////////////////
//////////////////////////// CHALLENGE DIGEST CHECK ////////////////////////////
////////////////////////////////////////////////////////////////////////////////
rlc_config.constrain_crt_equals_bytes(
region,
assigned_challenge_digest,
&challenge_digest,
&mut rlc_config_offset,
)?;
Ok(export)
}
}