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
use crate::chaum_pedersen::{ChaumPedersen, GroupParams};
use crate::conversion::ByteConvertible;
use crate::rand::RandomGenerator;
use num_bigint::{BigUint, RandBigInt};
use num_traits::One;
use rand::rngs::OsRng;
use std::error::Error;

/// A struct representing the Chaum-Pedersen protocol specialized for discrete logarithm-based groups.
/// This protocol is used for demonstrating knowledge of a secret in a zero-knowledge manner.
#[derive(Clone)]
pub struct DiscreteLogChaumPedersen {}

impl ChaumPedersen for DiscreteLogChaumPedersen {
    /// Defines the type of secret values used in this protocol as `BigUint`.
    type Secret = BigUint;

    /// Defines the type of randomness used during the commitment phase as `BigUint`.
    type CommitmentRandom = BigUint;

    /// Defines the type of response generated in the protocol as `BigUint`.
    type Response = BigUint;

    /// Defines the type of challenge used in the protocol as `BigUint`.
    type Challenge = BigUint;

    /// Defines the group parameters specific to discrete logarithm groups as `GroupParams<BigUint>`.
    type GroupParameters = GroupParams<BigUint>;

    /// Defines the type of parameters returned during the commitment phase.
    /// These include two values representing the commitment and two values representing the randomness.
    type CommitParameters = (BigUint, BigUint, BigUint, BigUint);

    /// Calculates the commitment for the given secret `x` using the provided group parameters.
    ///
    /// # Arguments
    /// * `params`: Group parameters which include the base points `g` and `h`, and the moduli `p` and `q`.
    /// * `x`: The secret value for which the commitment is being calculated.
    ///
    /// # Returns
    /// A tuple containing:
    /// * A tuple of commitments (`y1`, `y2`, `r1`, `r2`), where `y1` and `y2` are the actual commitments
    ///   and `r1` and `r2` are the random commitments.
    /// * The random value `k` used in the commitment calculations.
    fn commitment(
        params: &Self::GroupParameters, x: &Self::Secret,
    ) -> (Self::CommitParameters, Self::CommitmentRandom)
    where
        Self: Sized,
    {
        let y1 = params.g.modpow(x, &params.p);
        let y2 = params.h.modpow(x, &params.p);
        let mut rng = OsRng;
        let k = rng.gen_biguint_below(&params.p);
        let r1 = params.g.modpow(&k, &params.p);
        let r2 = params.h.modpow(&k, &params.p);
        ((y1, y2, r1, r2), k)
    }

    /// Generates a random challenge for the protocol within the group's range.
    /// This challenge is used as part of the verification process.
    ///
    /// # Arguments
    /// * `params`: Group parameters used to define the range within which the challenge is generated.
    ///
    /// # Returns
    /// A `BigUint` representing the challenge value.
    fn challenge(params: &GroupParams<BigUint>) -> BigUint {
        let mut rng = OsRng;
        rng.gen_biguint_below(&params.p)
    }

    /// Generates a random challenge for the protocol within the group's range.
    /// This challenge is used as part of the verification process.
    ///
    /// # Arguments
    /// * `params`: Group parameters used to define the range within which the challenge is generated.
    ///
    /// # Returns
    /// A `BigUint` representing the challenge value.
    fn challenge_response(
        params: &Self::GroupParameters, k: &Self::CommitmentRandom, c: &Self::Challenge,
        x: &Self::Secret,
    ) -> Self::Response
    where
        Self: Sized,
    {
        if k >= &(c * x) {
            (k - c * x).modpow(&BigUint::one(), &params.q)
        } else {
            &params.q - (c * x - k).modpow(&BigUint::one(), &params.q)
        }
    }

    /// Verifies the response against the given commitment, challenge, and group parameters.
    /// The function checks if the response is valid based on the protocol's criteria.
    ///
    /// # Arguments
    /// * `params`: Group parameters used in the verification.
    /// * `s`: The response to be verified.
    /// * `c`: The challenge against which the response is being verified.
    /// * `cp`: The commitment parameters (`y1`, `y2`, `r1`, `r2`) against which the response is being verified.
    ///
    /// # Returns
    /// `true` if the verification is successful and the response is valid; `false` otherwise.
    fn verify(
        params: &Self::GroupParameters, s: &Self::Response, c: &Self::Challenge,
        cp: &Self::CommitParameters,
    ) -> bool {
        let (y1, y2, r1, r2) = cp;

        let lhs1 = params.g.modpow(s, &params.p);
        let rhs1 = (r1 * y1.modpow(&(&params.p - c - BigUint::one()), &params.p)) % &params.p;
        let lhs2 = params.h.modpow(s, &params.p);
        let rhs2 = (r2 * y2.modpow(&(&params.p - c - BigUint::one()), &params.p)) % &params.p;

        lhs1 == rhs1 && lhs2 == rhs2
    }
}

/// Implementation of `ByteConvertible` for `BigUint`.
///
/// This implementation provides methods to convert `BigUint` objects to and from
/// byte arrays, using big-endian byte order.
impl ByteConvertible<BigUint> for BigUint {
    fn convert_to(t: &BigUint) -> Vec<u8> {
        t.to_bytes_be()
    }

    fn convert_from(bytes: &[u8]) -> Result<BigUint, Box<dyn Error>> {
        Ok(BigUint::from_bytes_be(bytes))
    }
}

// Implementation of `RandomGenerator` trait for `BigUint`.
impl RandomGenerator<BigUint> for BigUint {
    /// Generates a random `BigUint`.
    ///
    /// # Returns
    /// A `Result` containing the random `BigUint`, or an error if the generation fails.
    ///
    /// # Errors
    /// Returns an error if the conversion from bytes to `BigUint` fails.
    fn generate_random() -> Result<BigUint, Box<dyn std::error::Error>> {
        use rand::RngCore;
        let mut rng = OsRng;
        let mut bytes = [0u8; 32];
        rng.fill_bytes(&mut bytes);
        Ok(BigUint::from_bytes_be(&bytes))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::chaum_pedersen::constants::{
        RFC5114_MODP_1024_160_BIT_PARAMS, RFC5114_MODP_2048_224_BIT_PARAMS,
        RFC5114_MODP_2048_256_BIT_PARAMS,
    };
    use crate::chaum_pedersen::test::test_execute_protocol;
    use crate::rand::RandomGenerator;
    use num_bigint::ToBigUint;

    // Test case to ensure round-trip conversion for `BigUint`.
    #[test]
    fn biguint_conversion_round_trip() {
        let original = 123456789u64.to_biguint().unwrap();
        let bytes = BigUint::convert_to(&original);
        let recovered = BigUint::convert_from(&bytes).unwrap();
        assert_eq!(original, recovered);
    }

    #[test]
    fn test_discrete_log_commitment() {
        let g = BigUint::from(4u32);
        let h = BigUint::from(9u32);
        let p = BigUint::from(23u32);
        let q = BigUint::from(11u32);
        let x = BigUint::from(3u32);

        let params = GroupParams::<BigUint> {
            g: g.clone(),
            h: h.clone(),
            p: p.clone(),
            q: q.clone(),
        };

        let (cp, _k) = DiscreteLogChaumPedersen::commitment(&params, &x);
        let (y1, y2, r1, r2) = cp;

        assert_eq!(y1, params.g.modpow(&x, &params.p));
        assert_eq!(y2, params.h.modpow(&x, &params.p));
        assert!(r1 < params.p && r2 < params.p);
    }

    #[test]
    fn test_discrete_log_verification() {
        let g = BigUint::from(4u32);
        let h = BigUint::from(9u32);
        let p = BigUint::from(23u32);
        let q = BigUint::from(11u32);
        let x = BigUint::from(3u32);

        let params = GroupParams::<BigUint> {
            g: g.clone(),
            h: h.clone(),
            p: p.clone(),
            q: q.clone(),
        };

        assert!(test_execute_protocol::<DiscreteLogChaumPedersen>(&params, &x));
    }

    #[test]
    fn test_rfc_1024_160_bits_params() {
        let params = RFC5114_MODP_1024_160_BIT_PARAMS.to_owned();
        let mut rng = OsRng;
        let x = rng.gen_biguint_below(&params.p);
        assert!(test_execute_protocol::<DiscreteLogChaumPedersen>(&params, &x));
    }

    #[test]
    fn test_rfc_2048_224_bits_params() {
        let params = RFC5114_MODP_2048_224_BIT_PARAMS.to_owned();
        let mut rng = OsRng;
        let x = rng.gen_biguint_below(&params.p);
        assert!(test_execute_protocol::<DiscreteLogChaumPedersen>(&params, &x));
    }

    #[test]
    fn test_rfc_2048_256_bits_params() {
        let params = RFC5114_MODP_2048_256_BIT_PARAMS.to_owned();
        let mut rng = OsRng;
        let x = rng.gen_biguint_below(&params.p);
        assert!(test_execute_protocol::<DiscreteLogChaumPedersen>(&params, &x));
    }

    #[test]
    fn test_fail_rfc_1024_160_bits_params() {
        let params = RFC5114_MODP_1024_160_BIT_PARAMS.to_owned();
        let mut rng = OsRng;
        let x = rng.gen_biguint_below(&params.p);

        let (cp, _) = DiscreteLogChaumPedersen::commitment(&params, &x);
        let c = DiscreteLogChaumPedersen::challenge(&params);
        let fake_response = BigUint::generate_random().unwrap();
        let verified = DiscreteLogChaumPedersen::verify(&params, &fake_response, &c, &cp);
        assert!(!verified);
    }

    #[test]
    fn test_fail_rfc_2048_224_bits_params() {
        let params = RFC5114_MODP_2048_224_BIT_PARAMS.to_owned();
        let mut rng = OsRng;
        let x = rng.gen_biguint_below(&params.p);

        let (cp, _) = DiscreteLogChaumPedersen::commitment(&params, &x);
        let c = DiscreteLogChaumPedersen::challenge(&params);
        let fake_response = BigUint::generate_random().unwrap();
        let verified = DiscreteLogChaumPedersen::verify(&params, &fake_response, &c, &cp);
        assert!(!verified);
    }

    #[test]
    fn test_fail_rfc_2048_256_bits_params() {
        let params = RFC5114_MODP_2048_256_BIT_PARAMS.to_owned();
        let mut rng = OsRng;
        let x = rng.gen_biguint_below(&params.p);

        let (cp, _) = DiscreteLogChaumPedersen::commitment(&params, &x);
        let c = DiscreteLogChaumPedersen::challenge(&params);
        let fake_response = BigUint::generate_random().unwrap();
        let verified = DiscreteLogChaumPedersen::verify(&params, &fake_response, &c, &cp);
        assert!(!verified);
    }

    #[test]
    fn test_verify() {
        let g = BigUint::from(4u32);
        let h = BigUint::from(9u32);
        let p = BigUint::from(23u32);
        let q = BigUint::from(11u32);

        let params = GroupParams::<BigUint> {
            g: g.clone(),
            h: h.clone(),
            p: p.clone(),
            q: q.clone(),
        };

        let cp = (
            BigUint::from(6u32),
            BigUint::from(18u32),
            BigUint::from(2u32),
            BigUint::from(3u32),
        );

        // client calculates response
        let x = BigUint::from(10u32);
        let k = BigUint::from(17u32);
        let c = BigUint::from(0u32);
        let s = DiscreteLogChaumPedersen::challenge_response(&params, &k, &c, &x);
        println!("Response: {:?}", s);

        // server verifies
        assert!(DiscreteLogChaumPedersen::verify(&params, &s, &c, &cp));
    }
}