-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathconstraint_system.rs
More file actions
1473 lines (1242 loc) · 42.6 KB
/
constraint_system.rs
File metadata and controls
1473 lines (1242 loc) · 42.6 KB
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 std::{
borrow::Cow,
cmp,
ops::{Index, IndexMut},
};
use binius_utils::serialization::{DeserializeBytes, SerializationError, SerializeBytes};
use bytes::{Buf, BufMut};
use crate::{consts, error::ConstraintSystemError, word::Word};
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct ValueIndex(pub u32);
impl ValueIndex {
/// The value index that is not considered to be valid.
pub const INVALID: ValueIndex = ValueIndex(u32::MAX);
}
// The most sensible default for a value index is to make it invalid.
impl Default for ValueIndex {
fn default() -> Self {
Self::INVALID
}
}
impl SerializeBytes for ValueIndex {
fn serialize(&self, write_buf: impl BufMut) -> Result<(), SerializationError> {
self.0.serialize(write_buf)
}
}
impl DeserializeBytes for ValueIndex {
fn deserialize(read_buf: impl Buf) -> Result<Self, SerializationError>
where
Self: Sized,
{
Ok(ValueIndex(u32::deserialize(read_buf)?))
}
}
/// A different variants of shifting a value.
///
/// Note that there is no shift left arithmetic because it is redundant.
#[derive(Copy, Clone, Debug)]
pub enum ShiftVariant {
/// Shift logical left.
Sll,
/// Shift logical right.
Slr,
/// Shift arithmetic right.
Sar,
}
impl SerializeBytes for ShiftVariant {
fn serialize(&self, write_buf: impl BufMut) -> Result<(), SerializationError> {
let index = match self {
ShiftVariant::Sll => 0u8,
ShiftVariant::Slr => 1u8,
ShiftVariant::Sar => 2u8,
};
index.serialize(write_buf)
}
}
impl DeserializeBytes for ShiftVariant {
fn deserialize(read_buf: impl Buf) -> Result<Self, SerializationError>
where
Self: Sized,
{
let index = u8::deserialize(read_buf)?;
match index {
0 => Ok(ShiftVariant::Sll),
1 => Ok(ShiftVariant::Slr),
2 => Ok(ShiftVariant::Sar),
_ => Err(SerializationError::UnknownEnumVariant {
name: "ShiftVariant",
index,
}),
}
}
}
#[derive(Copy, Clone, Debug)]
pub struct ShiftedValueIndex {
/// The index of this value in the input values vector `z`.
pub value_index: ValueIndex,
/// The flavour of the shift that the value must be shifted by.
pub shift_variant: ShiftVariant,
/// The number of bits by which the value must be shifted by.
///
/// Must be less than 64.
pub amount: usize,
}
impl ShiftedValueIndex {
/// Create a value index that just uses the specified value.
pub fn plain(value_index: ValueIndex) -> Self {
Self {
value_index,
shift_variant: ShiftVariant::Sll,
amount: 0,
}
}
/// Shift Left Logical by the given number of bits.
pub fn sll(value_index: ValueIndex, amount: usize) -> Self {
assert!(amount < 64, "shift amount n={amount} out of range");
Self {
value_index,
shift_variant: ShiftVariant::Sll,
amount,
}
}
pub fn srl(value_index: ValueIndex, amount: usize) -> Self {
assert!(amount < 64, "shift amount n={amount} out of range");
Self {
value_index,
shift_variant: ShiftVariant::Slr,
amount,
}
}
pub fn sar(value_index: ValueIndex, amount: usize) -> Self {
assert!(amount < 64, "shift amount n={amount} out of range");
Self {
value_index,
shift_variant: ShiftVariant::Sar,
amount,
}
}
}
impl SerializeBytes for ShiftedValueIndex {
fn serialize(&self, mut write_buf: impl BufMut) -> Result<(), SerializationError> {
self.value_index.serialize(&mut write_buf)?;
self.shift_variant.serialize(&mut write_buf)?;
self.amount.serialize(write_buf)
}
}
impl DeserializeBytes for ShiftedValueIndex {
fn deserialize(mut read_buf: impl Buf) -> Result<Self, SerializationError>
where
Self: Sized,
{
let value_index = ValueIndex::deserialize(&mut read_buf)?;
let shift_variant = ShiftVariant::deserialize(&mut read_buf)?;
let amount = usize::deserialize(read_buf)?;
// Validate that amount is within valid range
if amount >= 64 {
return Err(SerializationError::InvalidConstruction {
name: "ShiftedValueIndex::amount",
});
}
Ok(ShiftedValueIndex {
value_index,
shift_variant,
amount,
})
}
}
pub type Operand = Vec<ShiftedValueIndex>;
#[derive(Debug, Clone, Default)]
pub struct AndConstraint {
pub a: Operand,
pub b: Operand,
pub c: Operand,
}
impl AndConstraint {
pub fn plain_abc(
a: impl IntoIterator<Item = ValueIndex>,
b: impl IntoIterator<Item = ValueIndex>,
c: impl IntoIterator<Item = ValueIndex>,
) -> AndConstraint {
AndConstraint {
a: a.into_iter().map(ShiftedValueIndex::plain).collect(),
b: b.into_iter().map(ShiftedValueIndex::plain).collect(),
c: c.into_iter().map(ShiftedValueIndex::plain).collect(),
}
}
pub fn abc(
a: impl IntoIterator<Item = ShiftedValueIndex>,
b: impl IntoIterator<Item = ShiftedValueIndex>,
c: impl IntoIterator<Item = ShiftedValueIndex>,
) -> AndConstraint {
AndConstraint {
a: a.into_iter().collect(),
b: b.into_iter().collect(),
c: c.into_iter().collect(),
}
}
}
impl SerializeBytes for AndConstraint {
fn serialize(&self, mut write_buf: impl BufMut) -> Result<(), SerializationError> {
self.a.serialize(&mut write_buf)?;
self.b.serialize(&mut write_buf)?;
self.c.serialize(write_buf)
}
}
impl DeserializeBytes for AndConstraint {
fn deserialize(mut read_buf: impl Buf) -> Result<Self, SerializationError>
where
Self: Sized,
{
let a = Vec::<ShiftedValueIndex>::deserialize(&mut read_buf)?;
let b = Vec::<ShiftedValueIndex>::deserialize(&mut read_buf)?;
let c = Vec::<ShiftedValueIndex>::deserialize(read_buf)?;
Ok(AndConstraint { a, b, c })
}
}
#[derive(Debug, Clone, Default)]
pub struct MulConstraint {
pub a: Operand,
pub b: Operand,
pub hi: Operand,
pub lo: Operand,
}
impl SerializeBytes for MulConstraint {
fn serialize(&self, mut write_buf: impl BufMut) -> Result<(), SerializationError> {
self.a.serialize(&mut write_buf)?;
self.b.serialize(&mut write_buf)?;
self.hi.serialize(&mut write_buf)?;
self.lo.serialize(write_buf)
}
}
impl DeserializeBytes for MulConstraint {
fn deserialize(mut read_buf: impl Buf) -> Result<Self, SerializationError>
where
Self: Sized,
{
let a = Vec::<ShiftedValueIndex>::deserialize(&mut read_buf)?;
let b = Vec::<ShiftedValueIndex>::deserialize(&mut read_buf)?;
let hi = Vec::<ShiftedValueIndex>::deserialize(&mut read_buf)?;
let lo = Vec::<ShiftedValueIndex>::deserialize(read_buf)?;
Ok(MulConstraint { a, b, hi, lo })
}
}
#[derive(Debug, Clone)]
pub struct ConstraintSystem {
pub value_vec_layout: ValueVecLayout,
pub constants: Vec<Word>,
pub and_constraints: Vec<AndConstraint>,
pub mul_constraints: Vec<MulConstraint>,
}
impl ConstraintSystem {
/// Serialization format version for compatibility checking
pub const SERIALIZATION_VERSION: u32 = 1;
}
impl ConstraintSystem {
pub fn new(
constants: Vec<Word>,
value_vec_layout: ValueVecLayout,
and_constraints: Vec<AndConstraint>,
mul_constraints: Vec<MulConstraint>,
) -> Self {
assert_eq!(constants.len(), value_vec_layout.n_const);
ConstraintSystem {
constants,
value_vec_layout,
and_constraints,
mul_constraints,
}
}
/// Validates and prepares this constraint system for proving/verifying.
///
/// This function performs the following:
/// 1. Validates the value vector layout (including public input checks)
/// 2. Pads the AND and MUL constraints to the next po2 size
pub fn validate_and_prepare(&mut self) -> Result<(), ConstraintSystemError> {
// Validate the value vector layout
self.value_vec_layout.validate()?;
// Both AND and MUL constraint list have requirements wrt their sizes.
let and_target_size =
cmp::max(consts::MIN_AND_CONSTRAINTS, self.and_constraints.len()).next_power_of_two();
let mul_target_size =
cmp::max(consts::MIN_MUL_CONSTRAINTS, self.mul_constraints.len()).next_power_of_two();
self.and_constraints
.resize_with(and_target_size, AndConstraint::default);
self.mul_constraints
.resize_with(mul_target_size, MulConstraint::default);
Ok(())
}
pub fn add_and_constraint(&mut self, and_constraint: AndConstraint) {
self.and_constraints.push(and_constraint);
}
pub fn add_mul_constraint(&mut self, mul_constraint: MulConstraint) {
self.mul_constraints.push(mul_constraint);
}
pub fn n_and_constraints(&self) -> usize {
self.and_constraints.len()
}
pub fn n_mul_constraints(&self) -> usize {
self.mul_constraints.len()
}
/// The total length of the [`ValueVec`] expected by this constraint system.
pub fn value_vec_len(&self) -> usize {
self.value_vec_layout.total_len
}
/// Create a new [`ValueVec`] with the size expected by this constraint system.
pub fn new_value_vec(&self) -> ValueVec {
ValueVec::new(self.value_vec_layout.clone())
}
}
impl SerializeBytes for ConstraintSystem {
fn serialize(&self, mut write_buf: impl BufMut) -> Result<(), SerializationError> {
Self::SERIALIZATION_VERSION.serialize(&mut write_buf)?;
self.value_vec_layout.serialize(&mut write_buf)?;
self.constants.serialize(&mut write_buf)?;
self.and_constraints.serialize(&mut write_buf)?;
self.mul_constraints.serialize(write_buf)
}
}
impl DeserializeBytes for ConstraintSystem {
fn deserialize(mut read_buf: impl Buf) -> Result<Self, SerializationError>
where
Self: Sized,
{
let version = u32::deserialize(&mut read_buf)?;
if version != Self::SERIALIZATION_VERSION {
return Err(SerializationError::InvalidConstruction {
name: "ConstraintSystem::version",
});
}
let value_vec_layout = ValueVecLayout::deserialize(&mut read_buf)?;
let constants = Vec::<Word>::deserialize(&mut read_buf)?;
let and_constraints = Vec::<AndConstraint>::deserialize(&mut read_buf)?;
let mul_constraints = Vec::<MulConstraint>::deserialize(read_buf)?;
if constants.len() != value_vec_layout.n_const {
return Err(SerializationError::InvalidConstruction {
name: "ConstraintSystem::constants",
});
}
Ok(ConstraintSystem {
value_vec_layout,
constants,
and_constraints,
mul_constraints,
})
}
}
/// Description of a layout of the value vector for a particular circuit.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ValueVecLayout {
/// The number of the constants declared by the circuit.
pub n_const: usize,
/// The number of the input output parameters declared by the circuit.
pub n_inout: usize,
/// The number of the witness parameters declared by the circuit.
pub n_witness: usize,
/// The number of the internal values declared by the circuit.
///
/// Those are outputs and intermediaries created by the gates.
pub n_internal: usize,
/// The offset at which `inout` parameters start.
pub offset_inout: usize,
/// The offset at which `witness` parameters start.
///
/// The public section of the value vec has the power-of-two size and is greater than the
/// minimum number of words. By public section we mean the constants and the inout values.
pub offset_witness: usize,
/// The total size of the value vec vector.
///
/// This must be a power-of-two.
pub total_len: usize,
}
impl ValueVecLayout {
/// Validates that the value vec layout has a correct shape.
pub fn validate(&self) -> Result<(), ConstraintSystemError> {
if !self.total_len.is_power_of_two() {
return Err(ConstraintSystemError::ValueVecLenNotPowerOfTwo);
}
if !self.offset_witness.is_power_of_two() {
return Err(ConstraintSystemError::PublicInputPowerOfTwo);
}
let pub_input_size = self.offset_witness;
if pub_input_size < consts::MIN_WORDS_PER_SEGMENT {
return Err(ConstraintSystemError::PublicInputTooShort { pub_input_size });
}
Ok(())
}
}
impl SerializeBytes for ValueVecLayout {
fn serialize(&self, mut write_buf: impl BufMut) -> Result<(), SerializationError> {
self.n_const.serialize(&mut write_buf)?;
self.n_inout.serialize(&mut write_buf)?;
self.n_witness.serialize(&mut write_buf)?;
self.n_internal.serialize(&mut write_buf)?;
self.offset_inout.serialize(&mut write_buf)?;
self.offset_witness.serialize(&mut write_buf)?;
self.total_len.serialize(write_buf)
}
}
impl DeserializeBytes for ValueVecLayout {
fn deserialize(mut read_buf: impl Buf) -> Result<Self, SerializationError>
where
Self: Sized,
{
let n_const = usize::deserialize(&mut read_buf)?;
let n_inout = usize::deserialize(&mut read_buf)?;
let n_witness = usize::deserialize(&mut read_buf)?;
let n_internal = usize::deserialize(&mut read_buf)?;
let offset_inout = usize::deserialize(&mut read_buf)?;
let offset_witness = usize::deserialize(&mut read_buf)?;
let total_len = usize::deserialize(read_buf)?;
Ok(ValueVecLayout {
n_const,
n_inout,
n_witness,
n_internal,
offset_inout,
offset_witness,
total_len,
})
}
}
/// The vector of values.
///
/// This is a prover-only structure.
///
/// The size of the value vec is always a power-of-two.
#[derive(Clone, Debug)]
pub struct ValueVec {
layout: ValueVecLayout,
data: Vec<Word>,
}
impl ValueVec {
pub fn new(layout: ValueVecLayout) -> ValueVec {
let size = layout.total_len;
ValueVec {
layout,
data: vec![Word::ZERO; size],
}
}
pub fn new_from_data(
layout: ValueVecLayout,
mut public: Vec<Word>,
private: Vec<Word>,
) -> Result<ValueVec, ConstraintSystemError> {
public.extend_from_slice(&private);
if public.len() != layout.total_len {
return Err(ConstraintSystemError::ValueVecLenMismatch {
expected: layout.total_len,
actual: public.len(),
});
}
Ok(ValueVec {
layout,
data: public,
})
}
/// The total size of the vector.
pub fn size(&self) -> usize {
self.data.len()
}
pub fn get(&self, index: usize) -> Word {
self.data[index]
}
pub fn set(&mut self, index: usize, value: Word) {
self.data[index] = value;
}
/// Returns the public portion of the values vector.
pub fn public(&self) -> &[Word] {
&self.data[..self.layout.offset_witness]
}
/// Return all non-public values (witness + internal).
pub fn non_public(&self) -> &[Word] {
&self.data[self.layout.offset_witness..]
}
/// Returns the witness portion of the values vector.
pub fn witness(&self) -> &[Word] {
let start = self.layout.offset_witness;
let end = start + self.layout.n_witness;
&self.data[start..end]
}
/// Returns the combined values vector.
pub fn combined_witness(&self) -> &[Word] {
&self.data
}
}
impl Index<ValueIndex> for ValueVec {
type Output = Word;
fn index(&self, index: ValueIndex) -> &Self::Output {
&self.data[index.0 as usize]
}
}
impl IndexMut<ValueIndex> for ValueVec {
fn index_mut(&mut self, index: ValueIndex) -> &mut Self::Output {
&mut self.data[index.0 as usize]
}
}
/// Values data for zero-knowledge proofs (either public witness or non-public part - private inputs
/// and internal values).
///
/// It uses `Cow<[Word]>` to avoid unnecessary clones while supporting
/// both borrowed and owned data.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ValuesData<'a> {
data: Cow<'a, [Word]>,
}
impl<'a> ValuesData<'a> {
/// Serialization format version for compatibility checking
pub const SERIALIZATION_VERSION: u32 = 1;
/// Create a new ValuesData from borrowed data
pub fn borrowed(data: &'a [Word]) -> Self {
Self {
data: Cow::Borrowed(data),
}
}
/// Create a new ValuesData from owned data
pub fn owned(data: Vec<Word>) -> Self {
Self {
data: Cow::Owned(data),
}
}
/// Get the values data as a slice
pub fn as_slice(&self) -> &[Word] {
&self.data
}
/// Get the number of words in the values data
pub fn len(&self) -> usize {
self.data.len()
}
/// Check if the witness is empty
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
/// Convert to owned data, consuming self
pub fn into_owned(self) -> Vec<Word> {
self.data.into_owned()
}
/// Convert to owned version of ValuesData
pub fn to_owned(&self) -> ValuesData<'static> {
ValuesData {
data: Cow::Owned(self.data.to_vec()),
}
}
}
impl<'a> SerializeBytes for ValuesData<'a> {
fn serialize(&self, mut write_buf: impl BufMut) -> Result<(), SerializationError> {
Self::SERIALIZATION_VERSION.serialize(&mut write_buf)?;
self.data.as_ref().serialize(write_buf)
}
}
impl DeserializeBytes for ValuesData<'static> {
fn deserialize(mut read_buf: impl Buf) -> Result<Self, SerializationError>
where
Self: Sized,
{
let version = u32::deserialize(&mut read_buf)?;
if version != Self::SERIALIZATION_VERSION {
return Err(SerializationError::InvalidConstruction {
name: "Witness::version",
});
}
let data = Vec::<Word>::deserialize(read_buf)?;
Ok(ValuesData::owned(data))
}
}
impl<'a> From<&'a [Word]> for ValuesData<'a> {
fn from(data: &'a [Word]) -> Self {
ValuesData::borrowed(data)
}
}
impl From<Vec<Word>> for ValuesData<'static> {
fn from(data: Vec<Word>) -> Self {
ValuesData::owned(data)
}
}
impl<'a> AsRef<[Word]> for ValuesData<'a> {
fn as_ref(&self) -> &[Word] {
self.as_slice()
}
}
impl<'a> std::ops::Deref for ValuesData<'a> {
type Target = [Word];
fn deref(&self) -> &Self::Target {
self.as_slice()
}
}
impl<'a> From<ValuesData<'a>> for Vec<Word> {
fn from(value: ValuesData<'a>) -> Self {
value.into_owned()
}
}
/// A zero-knowledge proof that can be serialized for cross-host verification.
///
/// This structure contains the complete proof transcript generated by the prover,
/// along with information about the challenger type needed for verification.
/// The proof data represents the Fiat-Shamir transcript that can be deserialized
/// by the verifier to recreate the interactive protocol.
///
/// # Design
///
/// The proof contains:
/// - `data`: The actual proof transcript as bytes (zero-copy with Cow)
/// - `challenger_type`: String identifying the challenger used (e.g., `"HasherChallenger<Sha256>"`)
///
/// This enables complete cross-host verification where a proof generated on one
/// machine can be serialized, transmitted, and verified on another machine with
/// the correct challenger configuration.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Proof<'a> {
data: Cow<'a, [u8]>,
challenger_type: String,
}
impl<'a> Proof<'a> {
/// Serialization format version for compatibility checking
pub const SERIALIZATION_VERSION: u32 = 1;
/// Create a new Proof from borrowed transcript data
pub fn borrowed(data: &'a [u8], challenger_type: String) -> Self {
Self {
data: Cow::Borrowed(data),
challenger_type,
}
}
/// Create a new Proof from owned transcript data
pub fn owned(data: Vec<u8>, challenger_type: String) -> Self {
Self {
data: Cow::Owned(data),
challenger_type,
}
}
/// Get the proof transcript data as a slice
pub fn as_slice(&self) -> &[u8] {
&self.data
}
/// Get the challenger type identifier
pub fn challenger_type(&self) -> &str {
&self.challenger_type
}
/// Get the number of bytes in the proof transcript
pub fn len(&self) -> usize {
self.data.len()
}
/// Check if the proof transcript is empty
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
/// Convert to owned data, consuming self
pub fn into_owned(self) -> (Vec<u8>, String) {
(self.data.into_owned(), self.challenger_type)
}
/// Convert to owned version of Proof
pub fn to_owned(&self) -> Proof<'static> {
Proof {
data: Cow::Owned(self.data.to_vec()),
challenger_type: self.challenger_type.clone(),
}
}
}
impl<'a> SerializeBytes for Proof<'a> {
fn serialize(&self, mut write_buf: impl BufMut) -> Result<(), SerializationError> {
Self::SERIALIZATION_VERSION.serialize(&mut write_buf)?;
self.challenger_type.serialize(&mut write_buf)?;
self.data.as_ref().serialize(write_buf)
}
}
impl DeserializeBytes for Proof<'static> {
fn deserialize(mut read_buf: impl Buf) -> Result<Self, SerializationError>
where
Self: Sized,
{
let version = u32::deserialize(&mut read_buf)?;
if version != Self::SERIALIZATION_VERSION {
return Err(SerializationError::InvalidConstruction {
name: "Proof::version",
});
}
let challenger_type = String::deserialize(&mut read_buf)?;
let data = Vec::<u8>::deserialize(read_buf)?;
Ok(Proof::owned(data, challenger_type))
}
}
impl<'a> From<(&'a [u8], String)> for Proof<'a> {
fn from((data, challenger_type): (&'a [u8], String)) -> Self {
Proof::borrowed(data, challenger_type)
}
}
impl From<(Vec<u8>, String)> for Proof<'static> {
fn from((data, challenger_type): (Vec<u8>, String)) -> Self {
Proof::owned(data, challenger_type)
}
}
impl<'a> AsRef<[u8]> for Proof<'a> {
fn as_ref(&self) -> &[u8] {
self.as_slice()
}
}
impl<'a> std::ops::Deref for Proof<'a> {
type Target = [u8];
fn deref(&self) -> &Self::Target {
self.as_slice()
}
}
#[cfg(test)]
mod serialization_tests {
use rand::{RngCore, SeedableRng, rngs::StdRng};
use super::*;
pub(crate) fn create_test_constraint_system() -> ConstraintSystem {
let constants = vec![
Word::from_u64(1),
Word::from_u64(42),
Word::from_u64(0xDEADBEEF),
];
let value_vec_layout = ValueVecLayout {
n_const: 3,
n_inout: 2,
n_witness: 10,
n_internal: 3,
offset_inout: 4, // Must be power of 2 and >= n_const
offset_witness: 8, // Must be power of 2 and >= offset_inout + n_inout
total_len: 16, // Must be power of 2 and >= offset_witness + n_witness
};
let and_constraints = vec![
AndConstraint::plain_abc(
vec![ValueIndex(0), ValueIndex(1)],
vec![ValueIndex(2)],
vec![ValueIndex(3), ValueIndex(4)],
),
AndConstraint::abc(
vec![ShiftedValueIndex::sll(ValueIndex(0), 5)],
vec![ShiftedValueIndex::srl(ValueIndex(1), 10)],
vec![ShiftedValueIndex::sar(ValueIndex(2), 15)],
),
];
let mul_constraints = vec![MulConstraint {
a: vec![ShiftedValueIndex::plain(ValueIndex(0))],
b: vec![ShiftedValueIndex::plain(ValueIndex(1))],
hi: vec![ShiftedValueIndex::plain(ValueIndex(2))],
lo: vec![ShiftedValueIndex::plain(ValueIndex(3))],
}];
ConstraintSystem::new(constants, value_vec_layout, and_constraints, mul_constraints)
}
#[test]
fn test_word_serialization_round_trip() {
let mut rng = StdRng::seed_from_u64(0);
let word = Word::from_u64(rng.next_u64());
let mut buf = Vec::new();
word.serialize(&mut buf).unwrap();
let deserialized = Word::deserialize(&mut buf.as_slice()).unwrap();
assert_eq!(word, deserialized);
}
#[test]
fn test_shift_variant_serialization_round_trip() {
let variants = [ShiftVariant::Sll, ShiftVariant::Slr, ShiftVariant::Sar];
for variant in variants {
let mut buf = Vec::new();
variant.serialize(&mut buf).unwrap();
let deserialized = ShiftVariant::deserialize(&mut buf.as_slice()).unwrap();
match (variant, deserialized) {
(ShiftVariant::Sll, ShiftVariant::Sll)
| (ShiftVariant::Slr, ShiftVariant::Slr)
| (ShiftVariant::Sar, ShiftVariant::Sar) => {}
_ => panic!("ShiftVariant round trip failed: {:?} != {:?}", variant, deserialized),
}
}
}
#[test]
fn test_shift_variant_unknown_variant() {
// Create invalid variant index
let mut buf = Vec::new();
255u8.serialize(&mut buf).unwrap();
let result = ShiftVariant::deserialize(&mut buf.as_slice());
assert!(result.is_err());
match result.unwrap_err() {
SerializationError::UnknownEnumVariant { name, index } => {
assert_eq!(name, "ShiftVariant");
assert_eq!(index, 255);
}
_ => panic!("Expected UnknownEnumVariant error"),
}
}
#[test]
fn test_value_index_serialization_round_trip() {
let value_index = ValueIndex(12345);
let mut buf = Vec::new();
value_index.serialize(&mut buf).unwrap();
let deserialized = ValueIndex::deserialize(&mut buf.as_slice()).unwrap();
assert_eq!(value_index, deserialized);
}
#[test]
fn test_shifted_value_index_serialization_round_trip() {
let shifted_value_index = ShiftedValueIndex::srl(ValueIndex(42), 23);
let mut buf = Vec::new();
shifted_value_index.serialize(&mut buf).unwrap();
let deserialized = ShiftedValueIndex::deserialize(&mut buf.as_slice()).unwrap();
assert_eq!(shifted_value_index.value_index, deserialized.value_index);
assert_eq!(shifted_value_index.amount, deserialized.amount);
match (shifted_value_index.shift_variant, deserialized.shift_variant) {
(ShiftVariant::Slr, ShiftVariant::Slr) => {}
_ => panic!("ShiftVariant mismatch"),
}
}
#[test]
fn test_shifted_value_index_invalid_amount() {
// Create a buffer with invalid shift amount (>= 64)
let mut buf = Vec::new();
ValueIndex(0).serialize(&mut buf).unwrap();
ShiftVariant::Sll.serialize(&mut buf).unwrap();
64usize.serialize(&mut buf).unwrap(); // Invalid amount
let result = ShiftedValueIndex::deserialize(&mut buf.as_slice());
assert!(result.is_err());
match result.unwrap_err() {
SerializationError::InvalidConstruction { name } => {
assert_eq!(name, "ShiftedValueIndex::amount");
}
_ => panic!("Expected InvalidConstruction error"),
}
}
#[test]
fn test_and_constraint_serialization_round_trip() {
let constraint = AndConstraint::abc(
vec![ShiftedValueIndex::sll(ValueIndex(1), 5)],
vec![ShiftedValueIndex::srl(ValueIndex(2), 10)],
vec![
ShiftedValueIndex::sar(ValueIndex(3), 15),
ShiftedValueIndex::plain(ValueIndex(4)),
],
);
let mut buf = Vec::new();
constraint.serialize(&mut buf).unwrap();
let deserialized = AndConstraint::deserialize(&mut buf.as_slice()).unwrap();
assert_eq!(constraint.a.len(), deserialized.a.len());
assert_eq!(constraint.b.len(), deserialized.b.len());
assert_eq!(constraint.c.len(), deserialized.c.len());
for (orig, deser) in constraint.a.iter().zip(deserialized.a.iter()) {
assert_eq!(orig.value_index, deser.value_index);
assert_eq!(orig.amount, deser.amount);
}
}
#[test]
fn test_mul_constraint_serialization_round_trip() {
let constraint = MulConstraint {
a: vec![ShiftedValueIndex::plain(ValueIndex(0))],
b: vec![ShiftedValueIndex::srl(ValueIndex(1), 32)],
hi: vec![ShiftedValueIndex::plain(ValueIndex(2))],
lo: vec![ShiftedValueIndex::plain(ValueIndex(3))],
};
let mut buf = Vec::new();
constraint.serialize(&mut buf).unwrap();
let deserialized = MulConstraint::deserialize(&mut buf.as_slice()).unwrap();
assert_eq!(constraint.a.len(), deserialized.a.len());
assert_eq!(constraint.b.len(), deserialized.b.len());
assert_eq!(constraint.hi.len(), deserialized.hi.len());
assert_eq!(constraint.lo.len(), deserialized.lo.len());
}
#[test]
fn test_value_vec_layout_serialization_round_trip() {
let layout = ValueVecLayout {
n_const: 5,
n_inout: 3,
n_witness: 12,
n_internal: 7,
offset_inout: 8,
offset_witness: 16,
total_len: 32,
};
let mut buf = Vec::new();
layout.serialize(&mut buf).unwrap();
let deserialized = ValueVecLayout::deserialize(&mut buf.as_slice()).unwrap();
assert_eq!(layout, deserialized);
}
#[test]
fn test_constraint_system_serialization_round_trip() {
let original = create_test_constraint_system();
let mut buf = Vec::new();
original.serialize(&mut buf).unwrap();