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
use crate::prelude::*;

use curve25519_dalek::constants;
use curve25519_dalek::ristretto::RistrettoPoint;
use curve25519_dalek::scalar::Scalar;
use curve25519_dalek::traits::MultiscalarMul;
use digest::Digest;
use digest::generic_array::typenum::U64;
use rand_core::{CryptoRng, RngCore};

use crate::traits::{KeyImageGen, Link, Sign, Verify};

/// Dual Linkable Spontaneous Anonymous Group Signature for Ad Hoc Groups
///
/// [DLSAG: Non-Interactive Refund Transactions For Interoperable Payment Channels in Monero](https://eprint.iacr.org/2019/595.pdf)
///
/// This is a a novel linkable ring signature scheme that enables for the
/// first time refund transactions natively in Monero
///
/// Read the paper on how to use it to implement payment channels.
///
/// Please read tests at the bottom of the source code for this module for
/// examples on how to use it
#[derive(Clone)]
pub struct DLSAG {
    pub challenge: Scalar,
    pub responses: Vec<Scalar>,
    pub ring: Vec<(RistrettoPoint, RistrettoPoint, Scalar)>,
    pub key_image: RistrettoPoint,
    pub b: bool,
}

impl KeyImageGen<(Scalar, RistrettoPoint, Scalar), RistrettoPoint> for DLSAG {
    /// Some signature schemes require the key images to be signed as well.
    /// Use this method to generate them
    fn generate_key_image<Hash: Digest<OutputSize=U64> + Clone + Default>(
        k: (Scalar, RistrettoPoint, Scalar),
    ) -> RistrettoPoint {
        let k_point: (RistrettoPoint, RistrettoPoint, Scalar) =
            (k.0 * constants::RISTRETTO_BASEPOINT_POINT, k.1, k.2);

        let key_image: RistrettoPoint = k.2
            * k.0
            * RistrettoPoint::from_hash(Hash::default().chain(k_point.1.compress().as_bytes()));

        return key_image;
    }
}

impl KeyImageGen<(RistrettoPoint, Scalar, Scalar), RistrettoPoint> for DLSAG {
    /// Some signature schemes require the key images to be signed as well.
    /// Use this method to generate them
    fn generate_key_image<Hash: Digest<OutputSize=U64> + Clone + Default>(
        k: (RistrettoPoint, Scalar, Scalar),
    ) -> RistrettoPoint {
        let k_point: (RistrettoPoint, RistrettoPoint, Scalar) =
            (k.0, k.1 * constants::RISTRETTO_BASEPOINT_POINT, k.2);

        let key_image: RistrettoPoint = k.2
            * k.1
            * RistrettoPoint::from_hash(Hash::default().chain(k_point.0.compress().as_bytes()));

        return key_image;
    }
}

impl Sign<(Scalar, RistrettoPoint, Scalar), Vec<(RistrettoPoint, RistrettoPoint, Scalar)>>
for DLSAG
{
    /// To sign you need `k` your private key, and `ring` which is the public keys of everyone
    /// except you. You are signing the `message`
    ///
    /// The private key `k` in this case is your private key, the public key of the other end of
    /// the channel and a random bitstring generated by hashing-to-scalar: the transaction ID, and
    /// output index.
    ///
    /// The ring contains public key pairs from the blockchain together with their random
    /// bitstrings as mentioned above.
    ///
    /// This implementation of `sign(...)` is for the user who has the private key for the left
    /// side of the channel
    fn sign<
        Hash: Digest<OutputSize=U64> + Clone + Default,
        CSPRNG: CryptoRng + RngCore + Default,
    >(
        k: (Scalar, RistrettoPoint, Scalar),
        mut ring: Vec<(RistrettoPoint, RistrettoPoint, Scalar)>,
        secret_index: usize,
        message: &Vec<u8>,
    ) -> DLSAG {
        let mut csprng = CSPRNG::default();

        // Provers public key
        let k_point: (RistrettoPoint, RistrettoPoint, Scalar) =
            (k.0 * constants::RISTRETTO_BASEPOINT_POINT, k.1, k.2);

        let key_image: RistrettoPoint = DLSAG::generate_key_image::<Hash>(k);

        // Ring size (at least 4 but maximum 32)
        let n = ring.len() + 1;

        ring.insert(secret_index, k_point);

        let a: Scalar = Scalar::random(&mut csprng);

        let mut rs: Vec<Scalar> = (0..n).map(|_| Scalar::random(&mut csprng)).collect();

        let mut cs: Vec<Scalar> = (0..n).map(|_| Scalar::zero()).collect();

        // Hash of message is shared by all challenges H_n(m, ....)
        let mut message_hash = Hash::default();

        message_hash.update(message);

        let mut hashes: Vec<Hash> = (0..n).map(|_| message_hash.clone()).collect();

        hashes[(secret_index + 1) % n].update(
            (a * constants::RISTRETTO_BASEPOINT_POINT)
                .compress()
                .as_bytes(),
        );
        hashes[(secret_index + 1) % n].update(
            (a * ring[secret_index].2
                * RistrettoPoint::from_hash(
                Hash::default().chain(k_point.1.compress().as_bytes()),
            ))
                .compress()
                .as_bytes(),
        );
        cs[(secret_index + 1) % n] = Scalar::from_hash(hashes[(secret_index + 1) % n].clone());

        let mut i = (secret_index + 1) % n;

        loop {
            hashes[(i + 1) % n].update(
                RistrettoPoint::multiscalar_mul(
                    &[rs[i % n], cs[i % n]],
                    &[constants::RISTRETTO_BASEPOINT_POINT, ring[i % n].0],
                )
                    .compress()
                    .as_bytes(),
            );
            hashes[(i + 1) % n].update(
                RistrettoPoint::multiscalar_mul(
                    &[rs[i % n], cs[i % n]],
                    &[
                        ring[i % n].2 * RistrettoPoint::from_hash(
                            Hash::default().chain(
                                ring[i % n].1.compress().as_bytes()
                            )
                        ),
                        key_image
                    ],
                )
                    .compress()
                    .as_bytes(),
            );
            cs[(i + 1) % n] = Scalar::from_hash(hashes[(i + 1) % n].clone());

            if secret_index >= 1 && i % n == (secret_index - 1) % n {
                break;
            } else if secret_index == 0 && i % n == n - 1 {
                break;
            } else {
                i = (i + 1) % n;
            }
        }

        rs[secret_index] = a - (cs[secret_index] * k.0);

        return DLSAG {
            challenge: cs[0],
            responses: rs,
            ring: ring,
            key_image: key_image,
            b: false,
        };
    }
}

impl Sign<(RistrettoPoint, Scalar, Scalar), Vec<(RistrettoPoint, RistrettoPoint, Scalar)>>
for DLSAG
{
    /// To sign you need `k` your private key, and `ring` which is the public keys of everyone
    /// except you. You are signing the `message`
    ///
    /// The private key `k` in this case is your private key, the public key of the other end of
    /// the channel and a random bitstring generated by hashing-to-scalar: the transaction ID, and
    /// output index.
    ///
    /// The ring contains public key pairs from the blockchain together with their random
    /// bitstrings as mentioned above.
    ///
    /// This implementation of `sign(...)` is for the user who has the private key for the right
    /// side of the channel
    fn sign<
        Hash: Digest<OutputSize=U64> + Clone + Default,
        CSPRNG: CryptoRng + RngCore + Default,
    >(
        k: (RistrettoPoint, Scalar, Scalar),
        mut ring: Vec<(RistrettoPoint, RistrettoPoint, Scalar)>,
        secret_index: usize,
        message: &Vec<u8>,
    ) -> DLSAG {
        let mut csprng = CSPRNG::default();

        // Provers public key
        let k_point: (RistrettoPoint, RistrettoPoint, Scalar) =
            (k.0, k.1 * constants::RISTRETTO_BASEPOINT_POINT, k.2);

        let key_image: RistrettoPoint = DLSAG::generate_key_image::<Hash>(k);

        // Ring size (at least 4 but maximum 32)
        let n = ring.len() + 1;

        ring.insert(secret_index, k_point);

        let a: Scalar = Scalar::random(&mut csprng);

        let mut rs: Vec<Scalar> = (0..n).map(|_| Scalar::random(&mut csprng)).collect();

        let mut cs: Vec<Scalar> = (0..n).map(|_| Scalar::zero()).collect();

        // Hash of message is shared by all challenges H_n(m, ....)
        let mut message_hash = Hash::default();

        message_hash.update(message);

        let mut hashes: Vec<Hash> = (0..n).map(|_| message_hash.clone()).collect();

        hashes[(secret_index + 1) % n].update(
            (a * constants::RISTRETTO_BASEPOINT_POINT)
                .compress()
                .as_bytes(),
        );
        hashes[(secret_index + 1) % n].update(
            (a * ring[secret_index].2
                * RistrettoPoint::from_hash(
                Hash::default().chain(k_point.0.compress().as_bytes()),
            ))
                .compress()
                .as_bytes(),
        );
        cs[(secret_index + 1) % n] = Scalar::from_hash(hashes[(secret_index + 1) % n].clone());

        let mut i = (secret_index + 1) % n;

        loop {
            hashes[(i + 1) % n].update(
                RistrettoPoint::multiscalar_mul(
                    &[rs[i % n], cs[i % n]],
                    &[
                        constants::RISTRETTO_BASEPOINT_POINT,
                        ring[i % n].1
                    ],
                )
                    .compress()
                    .as_bytes(),
            );
            hashes[(i + 1) % n].update(
                RistrettoPoint::multiscalar_mul(
                    &[rs[i % n], cs[i % n]],
                    &[
                        ring[i % n].2 * RistrettoPoint::from_hash(
                            Hash::default().chain(
                                ring[i % n].0.compress().as_bytes()
                            ),
                        ),
                        key_image
                    ],
                )
                    .compress()
                    .as_bytes(),
            );
            cs[(i + 1) % n] = Scalar::from_hash(hashes[(i + 1) % n].clone());

            if secret_index >= 1 && i % n == (secret_index - 1) % n {
                break;
            } else if secret_index == 0 && i % n == n - 1 {
                break;
            } else {
                i = (i + 1) % n;
            }
        }

        rs[secret_index] = a - (cs[secret_index] * k.1);

        return DLSAG {
            challenge: cs[0],
            responses: rs,
            ring: ring,
            key_image: key_image,
            b: true,
        };
    }
}

impl Verify for DLSAG {
    /// To verify a `signature` you need the `message` too
    fn verify<Hash: Digest<OutputSize=U64> + Clone + Default>(
        signature: DLSAG,
        message: &Vec<u8>,
    ) -> bool {
        let mut reconstructed_c: Scalar = signature.challenge;
        let n = signature.ring.len();
        for j in 0..n {
            let mut h: Hash = Hash::default();
            h.update(message);
            if signature.b {
                h.update(
                    RistrettoPoint::multiscalar_mul(
                        &[signature.responses[j], reconstructed_c],
                        &[
                            constants::RISTRETTO_BASEPOINT_POINT,
                            signature.ring[j].1
                        ],
                    )
                        .compress()
                        .as_bytes(),
                );

                h.update(
                    RistrettoPoint::multiscalar_mul(
                        &[signature.responses[j], reconstructed_c],
                        &[
                            signature.ring[j].2 * RistrettoPoint::from_hash(
                            Hash::default().chain(
                                    signature.ring[j].0.compress().as_bytes()
                                ),
                            ),
                            signature.key_image
                        ]
                    )
                        .compress()
                        .as_bytes(),
                );
            } else {
                h.update(
                    RistrettoPoint::multiscalar_mul(
                        &[signature.responses[j], reconstructed_c],
                        &[
                            constants::RISTRETTO_BASEPOINT_POINT,
                            signature.ring[j].0
                        ]
                    )
                        .compress()
                        .as_bytes(),
                );

                h.update(
                    RistrettoPoint::multiscalar_mul(
                        &[signature.responses[j], reconstructed_c],
                        &[
                            signature.ring[j].2 * RistrettoPoint::from_hash(
                                Hash::default().chain(
                                    signature.ring[j].1.compress().as_bytes()
                                )
                            ),
                            signature.key_image
                        ])
                        .compress()
                        .as_bytes(),
                );
            }
            reconstructed_c = Scalar::from_hash(h);
        }

        return signature.challenge == reconstructed_c;
    }
}

impl Link for DLSAG {
    /// This is for linking two signatures and checking if they are signed by the same person
    fn link(signature_1: DLSAG, signature_2: DLSAG) -> bool {
        return signature_1.key_image == signature_2.key_image;
    }
}

#[cfg(test)]
#[cfg(feature = "std")]
mod test {
    extern crate blake2;
    extern crate rand;
    extern crate sha2;
    extern crate sha3;

    use blake2::Blake2b;
    use curve25519_dalek::ristretto::RistrettoPoint;
    use curve25519_dalek::scalar::Scalar;
    use rand::rngs::OsRng;
    use sha2::Sha512;
    use sha3::Keccak512;

    use super::*;

    #[test]
    fn dlsag() {
        let mut csprng = OsRng::default();
        let k: (Scalar, RistrettoPoint, Scalar) = (
            Scalar::random(&mut csprng),         // The prover's private key
            RistrettoPoint::random(&mut csprng), // The public key of the other end of the channel
            // According to the paper this should be a random
            // bitstring generated by hashing transaction ID, and output index.
            // It is simulated here using a random bitstring
            Scalar::random(&mut csprng),
        );

        let other_k: (RistrettoPoint, Scalar, Scalar) = (k.1, k.0, k.2);
        let secret_index = 1;
        let n = 2;
        // Simulate randomly chosen Public keys (Prover will insert her public key here later)
        let ring: Vec<(RistrettoPoint, RistrettoPoint, Scalar)> = (0..(n - 1)) // Prover is going to add her key into this mix
            .map(|_| {
                (
                    RistrettoPoint::random(&mut csprng),
                    RistrettoPoint::random(&mut csprng),
                    Scalar::random(&mut csprng),
                )
            })
            .collect();
        let message: Vec<u8> = b"This is the message".iter().cloned().collect();

        {
            let signature = DLSAG::sign::<Sha512, OsRng>(k, ring.clone(), secret_index, &message);
            let result = DLSAG::verify::<Sha512>(signature, &message);
            assert!(result);
        }

        {
            let signature =
                DLSAG::sign::<Keccak512, OsRng>(k, ring.clone(), secret_index, &message);
            let result = DLSAG::verify::<Keccak512>(signature, &message);
            assert!(result);
        }

        {
            let signature = DLSAG::sign::<Blake2b, OsRng>(k, ring.clone(), secret_index, &message);
            let result = DLSAG::verify::<Blake2b>(signature, &message);
            assert!(result);
        }

        // Tests for signatures using the other end of the channel
        {
            let signature =
                DLSAG::sign::<Sha512, OsRng>(other_k, ring.clone(), secret_index, &message);
            let result = DLSAG::verify::<Sha512>(signature, &message);
            assert!(result);
        }

        {
            let signature =
                DLSAG::sign::<Keccak512, OsRng>(other_k, ring.clone(), secret_index, &message);
            let result = DLSAG::verify::<Keccak512>(signature, &message);
            assert!(result);
        }

        {
            let signature =
                DLSAG::sign::<Blake2b, OsRng>(other_k, ring.clone(), secret_index, &message);
            let result = DLSAG::verify::<Blake2b>(signature, &message);
            assert!(result);
        }

        let another_ring: Vec<(RistrettoPoint, RistrettoPoint, Scalar)> = (0..(n - 1)) // Prover is going to add her key into this mix
            .map(|_| {
                (
                    RistrettoPoint::random(&mut csprng),
                    RistrettoPoint::random(&mut csprng),
                    Scalar::random(&mut csprng),
                )
            })
            .collect();
        let another_message: Vec<u8> = b"This is another message".iter().cloned().collect();
        let signature_1 =
            DLSAG::sign::<Blake2b, OsRng>(k, another_ring.clone(), secret_index, &another_message);
        let signature_2 = DLSAG::sign::<Blake2b, OsRng>(k, ring.clone(), secret_index, &message);
        let signature_3 =
            DLSAG::sign::<Blake2b, OsRng>(other_k, ring.clone(), secret_index, &message);
        let result_1 = DLSAG::link(signature_1.clone(), signature_2);
        assert!(result_1);
        let result_2 = DLSAG::link(signature_1.clone(), signature_3);
        assert!(result_2);
    }
}