This repository has been archived by the owner on Jun 8, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 52
/
mod.rs
executable file
·1559 lines (1343 loc) · 70.3 KB
/
mod.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
#[macro_use]
pub mod logger;
mod commitment;
mod constants;
#[macro_use]
mod datastructures;
#[macro_use]
mod helpers;
mod hash;
pub mod issuer;
pub mod prover;
pub mod verifier;
use bn::BigNumber;
use errors::IndyCryptoError;
use pair::*;
use std::collections::{HashMap, HashSet, BTreeSet, BTreeMap};
use std::hash::Hash;
/// Creates random nonce
///
/// # Example
/// ```
/// use indy_crypto::cl::new_nonce;
///
/// let _nonce = new_nonce().unwrap();
/// ```
pub fn new_nonce() -> Result<Nonce, IndyCryptoError> {
Ok(helpers::bn_rand(constants::LARGE_NONCE)?)
}
/// A list of attributes a Credential is based on.
#[derive(Debug, Clone)]
pub struct CredentialSchema {
attrs: BTreeSet<String>, /* attr names */
}
/// A Builder of `Credential Schema`.
#[derive(Debug)]
pub struct CredentialSchemaBuilder {
attrs: BTreeSet<String>, /* attr names */
}
impl CredentialSchemaBuilder {
pub fn new() -> Result<CredentialSchemaBuilder, IndyCryptoError> {
Ok(CredentialSchemaBuilder { attrs: BTreeSet::new() })
}
pub fn add_attr(&mut self, attr: &str) -> Result<(), IndyCryptoError> {
self.attrs.insert(attr.to_owned());
Ok(())
}
pub fn finalize(self) -> Result<CredentialSchema, IndyCryptoError> {
Ok(CredentialSchema { attrs: self.attrs })
}
}
#[derive(Debug, Clone)]
pub struct NonCredentialSchema {
attrs: BTreeSet<String>,
}
#[derive(Debug)]
pub struct NonCredentialSchemaBuilder {
attrs: BTreeSet<String>,
}
impl NonCredentialSchemaBuilder {
pub fn new() -> Result<NonCredentialSchemaBuilder, IndyCryptoError> {
Ok(NonCredentialSchemaBuilder {
attrs: BTreeSet::new(),
})
}
pub fn add_attr(&mut self, attr: &str) -> Result<(), IndyCryptoError> {
self.attrs.insert(attr.to_owned());
Ok(())
}
pub fn finalize(self) -> Result<NonCredentialSchema, IndyCryptoError> {
Ok(NonCredentialSchema { attrs: self.attrs })
}
}
/// The m value for attributes,
/// commitments also store a blinding factor
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
pub enum CredentialValue {
Known { value: BigNumber }, //Issuer and Prover know these
Hidden { value: BigNumber }, //Only known to Prover who binds these into the U factor
Commitment {
value: BigNumber,
blinding_factor: BigNumber,
}, //Only known to Prover, not included in the credential, used for proving knowledge during issuance
}
impl CredentialValue {
pub fn clone(&self) -> Result<CredentialValue, IndyCryptoError> {
Ok(match *self {
CredentialValue::Known { ref value } => CredentialValue::Known {
value: value.clone()?,
},
CredentialValue::Hidden { ref value } => CredentialValue::Hidden {
value: value.clone()?,
},
CredentialValue::Commitment {
ref value,
ref blinding_factor,
} => CredentialValue::Commitment {
value: value.clone()?,
blinding_factor: blinding_factor.clone()?,
},
})
}
pub fn is_known(&self) -> bool {
match *self {
CredentialValue::Known { .. } => true,
_ => false,
}
}
pub fn is_hidden(&self) -> bool {
match *self {
CredentialValue::Hidden { .. } => true,
_ => false,
}
}
pub fn is_commitment(&self) -> bool {
match *self {
CredentialValue::Commitment { .. } => true,
_ => false,
}
}
pub fn value(&self) -> &BigNumber {
match *self {
CredentialValue::Known { ref value } => value,
CredentialValue::Hidden { ref value } => value,
CredentialValue::Commitment { ref value, .. } => value,
}
}
}
/// Values of attributes from `Claim Schema` (must be integers).
#[derive(Debug)]
pub struct CredentialValues {
attrs_values: BTreeMap<String, CredentialValue>,
}
impl CredentialValues {
pub fn clone(&self) -> Result<CredentialValues, IndyCryptoError> {
Ok(CredentialValues {
attrs_values: clone_credential_value_map(&self.attrs_values)?
})
}
}
/// A Builder of `Credential Values`.
#[derive(Debug)]
pub struct CredentialValuesBuilder {
attrs_values: BTreeMap<String, CredentialValue>, /* attr_name -> int representation of value */
}
impl CredentialValuesBuilder {
pub fn new() -> Result<CredentialValuesBuilder, IndyCryptoError> {
Ok(CredentialValuesBuilder { attrs_values: BTreeMap::new() })
}
pub fn add_dec_known(&mut self, attr: &str, value: &str) -> Result<(), IndyCryptoError> {
self.attrs_values.insert(
attr.to_owned(),
CredentialValue::Known { value: BigNumber::from_dec(value)? },
);
Ok(())
}
pub fn add_dec_hidden(&mut self, attr: &str, value: &str) -> Result<(), IndyCryptoError> {
self.attrs_values.insert(
attr.to_owned(),
CredentialValue::Hidden { value: BigNumber::from_dec(value)? },
);
Ok(())
}
pub fn add_dec_commitment(
&mut self,
attr: &str,
value: &str,
blinding_factor: &str,
) -> Result<(), IndyCryptoError> {
self.attrs_values.insert(
attr.to_owned(),
CredentialValue::Commitment {
value: BigNumber::from_dec(value)?,
blinding_factor: BigNumber::from_dec(blinding_factor)?,
},
);
Ok(())
}
pub fn add_value_known(
&mut self,
attr: &str,
value: &BigNumber,
) -> Result<(), IndyCryptoError> {
self.attrs_values.insert(
attr.to_owned(),
CredentialValue::Known { value: value.clone()? },
);
Ok(())
}
pub fn add_value_hidden(
&mut self,
attr: &str,
value: &BigNumber,
) -> Result<(), IndyCryptoError> {
self.attrs_values.insert(
attr.to_owned(),
CredentialValue::Hidden { value: value.clone()? },
);
Ok(())
}
pub fn add_value_commitment(
&mut self,
attr: &str,
value: &BigNumber,
blinding_factor: &BigNumber,
) -> Result<(), IndyCryptoError> {
self.attrs_values.insert(
attr.to_owned(),
CredentialValue::Commitment {
value: value.clone()?,
blinding_factor: blinding_factor.clone()?,
},
);
Ok(())
}
pub fn finalize(self) -> Result<CredentialValues, IndyCryptoError> {
Ok(CredentialValues { attrs_values: self.attrs_values })
}
}
/// `Issuer Public Key` contains 2 internal parts.
/// One for signing primary credentials and second for signing non-revocation credentials.
/// These keys are used to proof that credential was issued and doesn’t revoked by this issuer.
/// Issuer keys have global identifier that must be known to all parties.
#[derive(Debug, Deserialize, Serialize, PartialEq)]
pub struct CredentialPublicKey {
p_key: CredentialPrimaryPublicKey,
r_key: Option<CredentialRevocationPublicKey>,
}
impl CredentialPublicKey {
pub fn clone(&self) -> Result<CredentialPublicKey, IndyCryptoError> {
Ok(CredentialPublicKey {
p_key: self.p_key.clone()?,
r_key: self.r_key.clone()
})
}
pub fn get_primary_key(&self) -> Result<CredentialPrimaryPublicKey, IndyCryptoError> {
Ok(self.p_key.clone()?)
}
pub fn get_revocation_key(&self) -> Result<Option<CredentialRevocationPublicKey>, IndyCryptoError> {
Ok(self.r_key.clone())
}
pub fn build_from_parts(p_key: &CredentialPrimaryPublicKey, r_key: Option<&CredentialRevocationPublicKey>) -> Result<CredentialPublicKey, IndyCryptoError> {
Ok(CredentialPublicKey {
p_key: p_key.clone()?,
r_key: r_key.map(|key| key.clone())
})
}
}
/// `Issuer Private Key`: contains 2 internal parts.
/// One for signing primary credentials and second for signing non-revocation credentials.
#[derive(Debug, Deserialize, Serialize)]
pub struct CredentialPrivateKey {
p_key: CredentialPrimaryPrivateKey,
r_key: Option<CredentialRevocationPrivateKey>,
}
/// Issuer's "Public Key" is used to verify the Issuer's signature over the Credential's attributes' values (primary credential).
#[derive(Debug, PartialEq, Serialize)]
pub struct CredentialPrimaryPublicKey {
n: BigNumber,
s: BigNumber,
r: HashMap<String /* attr_name */, BigNumber>,
rctxt: BigNumber,
z: BigNumber
}
impl CredentialPrimaryPublicKey {
pub fn clone(&self) -> Result<CredentialPrimaryPublicKey, IndyCryptoError> {
Ok(CredentialPrimaryPublicKey {
n: self.n.clone()?,
s: self.s.clone()?,
r: clone_bignum_map(&self.r)?,
rctxt: self.rctxt.clone()?,
z: self.z.clone()?
})
}
}
impl <'a> ::serde::de::Deserialize<'a> for CredentialPrimaryPublicKey {
fn deserialize<D: ::serde::de::Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(Deserialize)]
struct CredentialPrimaryPublicKeyV1 {
n: BigNumber,
s: BigNumber,
r: HashMap<String /* attr_name */, BigNumber>,
rctxt: BigNumber,
#[serde(default)]
rms: BigNumber,
z: BigNumber
}
let mut helper = CredentialPrimaryPublicKeyV1::deserialize(deserializer)?;
if helper.rms != BigNumber::default() {
helper.r.insert("master_secret".to_string(), helper.rms);
}
Ok(CredentialPrimaryPublicKey {
n: helper.n,
s: helper.s,
rctxt: helper.rctxt,
z: helper.z,
r: helper.r
})
}
}
/// Issuer's "Private Key" used for signing Credential's attributes' values (primary credential)
#[derive(Debug, PartialEq, Deserialize, Serialize)]
pub struct CredentialPrimaryPrivateKey {
p: BigNumber,
q: BigNumber
}
/// `Primary Public Key Metadata` required for building of Proof Correctness of `Issuer Public Key`
#[derive(Debug)]
pub struct CredentialPrimaryPublicKeyMetadata {
xz: BigNumber,
xr: HashMap<String, BigNumber>
}
/// Proof of `Issuer Public Key` correctness
#[derive(Debug, PartialEq, Deserialize, Serialize)]
pub struct CredentialKeyCorrectnessProof {
c: BigNumber,
xz_cap: BigNumber,
xr_cap: Vec<(String, BigNumber)>,
}
/// `Revocation Public Key` is used to verify that credential was'nt revoked by Issuer.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct CredentialRevocationPublicKey {
g: PointG1,
g_dash: PointG2,
h: PointG1,
h0: PointG1,
h1: PointG1,
h2: PointG1,
htilde: PointG1,
h_cap: PointG2,
u: PointG2,
pk: PointG1,
y: PointG2,
}
/// `Revocation Private Key` is used for signing Credential.
#[derive(Debug, Deserialize, Serialize)]
pub struct CredentialRevocationPrivateKey {
x: GroupOrderElement,
sk: GroupOrderElement
}
pub type Accumulator = PointG2;
/// `Revocation Registry` contains accumulator.
/// Must be published by Issuer on a tamper-evident and highly available storage
/// Used by prover to prove that a credential hasn't revoked by the issuer
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RevocationRegistry {
accum: Accumulator
}
impl From<RevocationRegistryDelta> for RevocationRegistry {
fn from(rev_reg_delta: RevocationRegistryDelta) -> RevocationRegistry {
RevocationRegistry { accum: rev_reg_delta.accum }
}
}
/// `Revocation Registry Delta` contains Accumulator changes.
/// Must be applied to `Revocation Registry`
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RevocationRegistryDelta {
#[serde(skip_serializing_if = "Option::is_none")]
prev_accum: Option<Accumulator>,
accum: Accumulator,
#[serde(skip_serializing_if = "HashSet::is_empty")]
#[serde(default)]
issued: HashSet<u32>,
#[serde(skip_serializing_if = "HashSet::is_empty")]
#[serde(default)]
revoked: HashSet<u32>
}
impl RevocationRegistryDelta {
pub fn from_parts(rev_reg_from: Option<&RevocationRegistry>,
rev_reg_to: &RevocationRegistry,
issued: &HashSet<u32>,
revoked: &HashSet<u32>) -> RevocationRegistryDelta {
RevocationRegistryDelta {
prev_accum: rev_reg_from.map(|rev_reg| rev_reg.accum),
accum: rev_reg_to.accum.clone(),
issued: issued.clone(),
revoked: revoked.clone()
}
}
pub fn merge(&mut self, other_delta: &RevocationRegistryDelta) -> Result<(), IndyCryptoError> {
if other_delta.prev_accum.is_none() || self.accum != other_delta.prev_accum.unwrap() {
return Err(IndyCryptoError::InvalidStructure(format!("Deltas can not be merged.")));
}
self.accum = other_delta.accum;
self.issued.extend(
other_delta.issued.difference(&self.revoked));
self.revoked.extend(
other_delta.revoked.difference(&self.issued));
for index in other_delta.revoked.iter() {
self.issued.remove(index);
}
for index in other_delta.issued.iter() {
self.revoked.remove(index);
}
Ok(())
}
}
/// `Revocation Key Public` Accumulator public key.
/// Must be published together with Accumulator
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RevocationKeyPublic {
z: Pair
}
/// `Revocation Key Private` Accumulator primate key.
#[derive(Debug, Deserialize, Serialize)]
pub struct RevocationKeyPrivate {
gamma: GroupOrderElement
}
/// `Tail` point of curve used to update accumulator.
pub type Tail = PointG2;
impl Tail {
fn new_tail(index: u32, g_dash: &PointG2, gamma: &GroupOrderElement) -> Result<Tail, IndyCryptoError> {
let i_bytes = helpers::transform_u32_to_array_of_u8(index);
let mut pow = GroupOrderElement::from_bytes(&i_bytes)?;
pow = gamma.pow_mod(&pow)?;
Ok(g_dash.mul(&pow)?)
}
}
/// Generator of `Tail's`.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RevocationTailsGenerator {
size: u32,
current_index: u32,
g_dash: PointG2,
gamma: GroupOrderElement
}
impl RevocationTailsGenerator {
fn new(max_cred_num: u32, gamma: GroupOrderElement, g_dash: PointG2) -> Self {
RevocationTailsGenerator {
size: 2 * max_cred_num + 1, /* Unused 0th + valuable 1..L + unused (L+1)th + valuable (L+2)..(2L) */
current_index: 0,
gamma,
g_dash,
}
}
pub fn count(&self) -> u32 {
self.size - self.current_index
}
pub fn next(&mut self) -> Result<Option<Tail>, IndyCryptoError> {
if self.current_index >= self.size {
return Ok(None);
}
let tail = Tail::new_tail(self.current_index, &self.g_dash, &self.gamma)?;
self.current_index += 1;
Ok(Some(tail))
}
}
pub trait RevocationTailsAccessor {
fn access_tail(&self, tail_id: u32, accessor: &mut FnMut(&Tail)) -> Result<(), IndyCryptoError>;
}
/// Simple implementation of `RevocationTailsAccessor` that stores all tails as BTreeMap.
#[derive(Debug, Clone)]
pub struct SimpleTailsAccessor {
tails: Vec<Tail>
}
impl RevocationTailsAccessor for SimpleTailsAccessor {
fn access_tail(&self, tail_id: u32, accessor: &mut FnMut(&Tail)) -> Result<(), IndyCryptoError> {
Ok(accessor(&self.tails[tail_id as usize]))
}
}
impl SimpleTailsAccessor {
pub fn new(rev_tails_generator: &mut RevocationTailsGenerator) -> Result<SimpleTailsAccessor, IndyCryptoError> {
let mut tails: Vec<Tail> = Vec::new();
while let Some(tail) = rev_tails_generator.next()? {
tails.push(tail);
}
Ok(SimpleTailsAccessor { tails })
}
}
/// Issuer's signature over Credential attribute values.
#[derive(Debug, Deserialize, Serialize)]
pub struct CredentialSignature {
p_credential: PrimaryCredentialSignature,
r_credential: Option<NonRevocationCredentialSignature> /* will be used to proof is credential revoked preparation */,
}
impl CredentialSignature {
pub fn extract_index(&self) -> Option<u32> {
self.r_credential
.as_ref()
.map(|r_credential| r_credential.i)
}
}
#[derive(Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct PrimaryCredentialSignature {
m_2: BigNumber,
a: BigNumber,
e: BigNumber,
v: BigNumber
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct NonRevocationCredentialSignature {
sigma: PointG1,
c: GroupOrderElement,
vr_prime_prime: GroupOrderElement,
witness_signature: WitnessSignature,
g_i: PointG1,
i: u32,
m2: GroupOrderElement
}
#[derive(Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct SignatureCorrectnessProof {
se: BigNumber,
c: BigNumber
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Witness {
omega: PointG2
}
impl Witness {
pub fn new<RTA>(rev_idx: u32,
max_cred_num: u32,
issuance_by_default: bool,
rev_reg_delta: &RevocationRegistryDelta,
rev_tails_accessor: &RTA) -> Result<Witness, IndyCryptoError> where RTA: RevocationTailsAccessor {
trace!("Witness::new: >>> rev_idx: {:?}, max_cred_num: {:?}, issuance_by_default: {:?}, rev_reg_delta: {:?}",
rev_idx, max_cred_num, issuance_by_default, rev_reg_delta);
let mut omega = PointG2::new_inf()?;
let mut issued = if issuance_by_default {
(1..max_cred_num + 1).collect::<HashSet<u32>>()
.difference(&rev_reg_delta.revoked).cloned().collect::<HashSet<u32>>()
} else {
rev_reg_delta.issued.clone()
};
issued.remove(&rev_idx);
for j in issued.iter() {
let index = max_cred_num + 1 - j + rev_idx;
rev_tails_accessor.access_tail(index, &mut |tail| {
omega = omega.add(tail).unwrap();
})?;
}
let witness = Witness { omega };
trace!("Witness::new: <<< witness: {:?}", witness);
Ok(witness)
}
pub fn update<RTA>(&mut self,
rev_idx: u32,
max_cred_num: u32,
rev_reg_delta: &RevocationRegistryDelta,
rev_tails_accessor: &RTA) -> Result<(), IndyCryptoError> where RTA: RevocationTailsAccessor {
trace!("Witness::update: >>> rev_idx: {:?}, max_cred_num: {:?}, rev_reg_delta: {:?}",
rev_idx, max_cred_num, rev_reg_delta);
let mut omega_denom = PointG2::new_inf()?;
for j in rev_reg_delta.revoked.iter() {
if rev_idx.eq(j) { continue; }
let index = max_cred_num + 1 - j + rev_idx;
rev_tails_accessor.access_tail(index, &mut |tail| {
omega_denom = omega_denom.add(tail).unwrap();
})?;
}
let mut omega_num = PointG2::new_inf()?;
for j in rev_reg_delta.issued.iter() {
if rev_idx.eq(j) { continue; }
let index = max_cred_num + 1 - j + rev_idx;
rev_tails_accessor.access_tail(index, &mut |tail| {
omega_num = omega_num.add(tail).unwrap();
})?;
}
let new_omega: PointG2 = self.omega.add(&omega_num.sub(&omega_denom)?)?;
self.omega = new_omega;
trace!("Witness::update: <<<");
Ok(())
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct WitnessSignature {
sigma_i: PointG2,
u_i: PointG2,
g_i: PointG1
}
/// Secret key encoded in a credential that is used to prove that prover owns the credential; can be used to
/// prove linkage across credentials.
/// Prover blinds master secret, generating `BlindedCredentialSecrets` and `CredentialSecretsBlindingFactors` (blinding factors)
/// and sends the `BlindedCredentialSecrets` to Issuer who then encodes it credential creation.
/// The blinding factors are used by Prover for post processing of issued credentials.
#[derive(Debug, Deserialize, Serialize)]
pub struct MasterSecret {
ms: BigNumber,
}
impl MasterSecret {
pub fn clone(&self) -> Result<MasterSecret, IndyCryptoError> {
Ok(MasterSecret { ms: self.ms.clone()? })
}
pub fn value(&self) -> Result<BigNumber, IndyCryptoError> {
Ok(self.ms.clone()?)
}
}
/// Blinded Master Secret uses by Issuer in credential creation.
#[derive(Debug, Deserialize, Serialize)]
pub struct BlindedCredentialSecrets {
u: BigNumber,
ur: Option<PointG1>,
hidden_attributes: BTreeSet<String>,
committed_attributes: BTreeMap<String, BigNumber>
}
/// `CredentialSecretsBlindingFactors` used by Prover for post processing of credentials received from Issuer.
#[derive(Debug, Deserialize, Serialize)]
pub struct CredentialSecretsBlindingFactors {
v_prime: BigNumber,
vr_prime: Option<GroupOrderElement>
}
#[derive(Eq, PartialEq, Debug)]
pub struct PrimaryBlindedCredentialSecretsFactors {
u: BigNumber,
v_prime: BigNumber,
hidden_attributes: BTreeSet<String>,
committed_attributes: BTreeMap<String, BigNumber>,
}
#[derive(Debug)]
pub struct RevocationBlindedCredentialSecretsFactors {
ur: PointG1,
vr_prime: GroupOrderElement,
}
#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct BlindedCredentialSecretsCorrectnessProof {
c: BigNumber, // Fiat-Shamir challenge hash
v_dash_cap: BigNumber, // Value to prove knowledge of `u` construction in `BlindedCredentialSecrets`
m_caps: BTreeMap<String, BigNumber>, // Values for proving knowledge of committed values
r_caps: BTreeMap<String, BigNumber>, // Blinding values for m_caps
}
/// “Sub Proof Request” - input to create a Proof for a credential;
/// Contains attributes to be revealed and predicates.
#[derive(Debug, Clone)]
pub struct SubProofRequest {
revealed_attrs: BTreeSet<String>,
predicates: BTreeSet<Predicate>,
}
/// Builder of “Sub Proof Request”.
#[derive(Debug)]
pub struct SubProofRequestBuilder {
value: SubProofRequest
}
impl SubProofRequestBuilder {
pub fn new() -> Result<SubProofRequestBuilder, IndyCryptoError> {
Ok(SubProofRequestBuilder {
value: SubProofRequest {
revealed_attrs: BTreeSet::new(),
predicates: BTreeSet::new()
}
})
}
pub fn add_revealed_attr(&mut self, attr: &str) -> Result<(), IndyCryptoError> {
self.value.revealed_attrs.insert(attr.to_owned());
Ok(())
}
pub fn add_predicate(&mut self, attr_name: &str, p_type: &str, value: i32) -> Result<(), IndyCryptoError> {
let p_type = match p_type {
"GE" => PredicateType::GE,
"LE" => PredicateType::LE,
"GT" => PredicateType::GT,
"LT" => PredicateType::LT,
p_type => return Err(IndyCryptoError::InvalidStructure(format!("Invalid predicate type: {:?}", p_type)))
};
let predicate = Predicate {
attr_name: attr_name.to_owned(),
p_type,
value
};
self.value.predicates.insert(predicate);
Ok(())
}
pub fn finalize(self) -> Result<SubProofRequest, IndyCryptoError> {
Ok(self.value)
}
}
/// Some condition that must be satisfied.
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
pub struct Predicate {
attr_name: String,
p_type: PredicateType,
value: i32,
}
impl Predicate {
pub fn get_delta(&self, attr_value: i32) -> i32 {
match self.p_type {
PredicateType::GE => attr_value - self.value,
PredicateType::GT => attr_value - self.value - 1,
PredicateType::LE => self.value - attr_value,
PredicateType::LT => self.value - attr_value - 1
}
}
pub fn get_delta_prime(&self) -> Result<BigNumber, IndyCryptoError> {
match self.p_type {
PredicateType::GE => BigNumber::from_dec(&self.value.to_string()),
PredicateType::GT => BigNumber::from_dec(&(self.value + 1).to_string()),
PredicateType::LE => BigNumber::from_dec(&self.value.to_string()),
PredicateType::LT => BigNumber::from_dec(&(self.value - 1).to_string())
}
}
pub fn is_less(&self) -> bool {
match self.p_type {
PredicateType::GE | PredicateType::GT => false,
PredicateType::LE | PredicateType::LT => true
}
}
}
/// Condition type
#[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
pub enum PredicateType {
GE,
LE,
GT,
LT
}
/// Proof is complex crypto structure created by prover over multiple credentials that allows to prove that prover:
/// 1) Knows signature over credentials issued with specific issuer keys (identified by key id)
/// 2) Credential contains attributes with specific values that prover wants to disclose
/// 3) Credential contains attributes with valid predicates that verifier wants the prover to satisfy.
#[derive(Debug, Deserialize, Serialize)]
pub struct Proof {
proofs: Vec<SubProof>,
aggregated_proof: AggregatedProof,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct SubProof {
primary_proof: PrimaryProof,
non_revoc_proof: Option<NonRevocProof>
}
#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct AggregatedProof {
c_hash: BigNumber,
c_list: Vec<Vec<u8>>
}
#[derive(Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct PrimaryProof {
eq_proof: PrimaryEqualProof,
ne_proofs: Vec<PrimaryPredicateInequalityProof>
}
#[derive(Debug, PartialEq, Eq, Serialize)]
pub struct PrimaryEqualProof {
revealed_attrs: BTreeMap<String /* attr_name of revealed */, BigNumber>,
a_prime: BigNumber,
e: BigNumber,
v: BigNumber,
m: HashMap<String /* attr_name of all except revealed */, BigNumber>,
m2: BigNumber
}
impl <'a> ::serde::de::Deserialize<'a> for PrimaryEqualProof {
fn deserialize<D: ::serde::de::Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(Deserialize)]
struct PrimaryEqualProofV1 {
revealed_attrs: BTreeMap<String /* attr_name of revealed */, BigNumber>,
a_prime: BigNumber,
e: BigNumber,
v: BigNumber,
m: HashMap<String /* attr_name of all except revealed */, BigNumber>,
#[serde(default)]
m1: BigNumber,
m2: BigNumber
}
let mut helper = PrimaryEqualProofV1::deserialize(deserializer)?;
if helper.m1 != BigNumber::default() {
helper.m.insert("master_secret".to_string(), helper.m1);
}
Ok(PrimaryEqualProof {
revealed_attrs: helper.revealed_attrs,
a_prime: helper.a_prime,
e: helper.e,
v: helper.v,
m: helper.m,
m2: helper.m2
})
}
}
#[derive(Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct PrimaryPredicateInequalityProof {
u: HashMap<String, BigNumber>,
r: HashMap<String, BigNumber>,
mj: BigNumber,
alpha: BigNumber,
t: HashMap<String, BigNumber>,
predicate: Predicate
}
#[derive(Debug, Deserialize, Serialize)]
pub struct NonRevocProof {
x_list: NonRevocProofXList,
c_list: NonRevocProofCList
}
#[derive(Debug)]
pub struct InitProof {
primary_init_proof: PrimaryInitProof,
non_revoc_init_proof: Option<NonRevocInitProof>,
credential_values: CredentialValues,
sub_proof_request: SubProofRequest,
credential_schema: CredentialSchema,
non_credential_schema: NonCredentialSchema,
}
#[derive(Debug, Eq, PartialEq)]
pub struct PrimaryInitProof {
eq_proof: PrimaryEqualInitProof,
ne_proofs: Vec<PrimaryPredicateInequalityInitProof>
}
impl PrimaryInitProof {
pub fn as_c_list(&self) -> Result<Vec<Vec<u8>>, IndyCryptoError> {
let mut c_list: Vec<Vec<u8>> = self.eq_proof.as_list()?;
for ne_proof in self.ne_proofs.iter() {
c_list.append_vec(ne_proof.as_list()?)?;
}
Ok(c_list)
}
pub fn as_tau_list(&self) -> Result<Vec<Vec<u8>>, IndyCryptoError> {
let mut tau_list: Vec<Vec<u8>> = self.eq_proof.as_tau_list()?;
for ne_proof in self.ne_proofs.iter() {
tau_list.append_vec(ne_proof.as_tau_list()?)?;
}
Ok(tau_list)
}
}
#[derive(Debug)]
pub struct NonRevocInitProof {
c_list_params: NonRevocProofXList,
tau_list_params: NonRevocProofXList,
c_list: NonRevocProofCList,
tau_list: NonRevocProofTauList
}
impl NonRevocInitProof {
pub fn as_c_list(&self) -> Result<Vec<Vec<u8>>, IndyCryptoError> {
let vec = self.c_list.as_list()?;
Ok(vec)
}
pub fn as_tau_list(&self) -> Result<Vec<Vec<u8>>, IndyCryptoError> {
let vec = self.tau_list.as_slice()?;
Ok(vec)
}
}
#[derive(Debug, Eq, PartialEq)]
pub struct PrimaryEqualInitProof {
a_prime: BigNumber,
t: BigNumber,
e_tilde: BigNumber,
e_prime: BigNumber,
v_tilde: BigNumber,
v_prime: BigNumber,
m_tilde: HashMap<String, BigNumber>,
m2_tilde: BigNumber,
m2: BigNumber,
}
impl PrimaryEqualInitProof {
pub fn as_list(&self) -> Result<Vec<Vec<u8>>, IndyCryptoError> {
Ok(vec![self.a_prime.to_bytes()?])
}
pub fn as_tau_list(&self) -> Result<Vec<Vec<u8>>, IndyCryptoError> {
Ok(vec![self.t.to_bytes()?])
}
}
#[derive(Debug, Eq, PartialEq)]
pub struct PrimaryPredicateInequalityInitProof {
c_list: Vec<BigNumber>,
tau_list: Vec<BigNumber>,
u: HashMap<String, BigNumber>,
u_tilde: HashMap<String, BigNumber>,
r: HashMap<String, BigNumber>,
r_tilde: HashMap<String, BigNumber>,
alpha_tilde: BigNumber,
predicate: Predicate,
t: HashMap<String, BigNumber>,
}
impl PrimaryPredicateInequalityInitProof {
pub fn as_list(&self) -> Result<&Vec<BigNumber>, IndyCryptoError> {
Ok(&self.c_list)
}