voprf 0.6.0-pre.1

An implementation of a verifiable oblivious pseudorandom function (VOPRF)
Documentation
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
// Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is dual-licensed under either the MIT license found in the
// LICENSE-MIT file in the root directory of this source tree or the Apache
// License, Version 2.0 found in the LICENSE-APACHE file in the root directory
// of this source tree. You may select, at your option, one of the above-listed
// licenses.

//! Contains the main POPRF API

#[cfg(feature = "alloc")]
use alloc::vec::Vec;
use core::iter::{self, Map, Repeat, Zip};

use derive_where::derive_where;
use digest::{Digest, Output, OutputSizeUser};
use generic_array::typenum::Unsigned;
use generic_array::{ArrayLength, GenericArray};
use rand_core::{TryCryptoRng, TryRngCore};

use crate::common::{
    derive_keypair, deterministic_blind_unchecked, generate_proof, hash_to_group, i2osp_2,
    server_evaluate_hash_input, verify_proof, BlindedElement, Dst, EvaluationElement, Mode,
    PreparedEvaluationElement, Proof, STR_FINALIZE, STR_HASH_TO_SCALAR, STR_INFO,
};
#[cfg(feature = "serde")]
use crate::serialization::serde::{Element, Scalar};
use crate::{CipherSuite, Error, Group, Result};

////////////////////////////
// High-level API Structs //
// ====================== //
////////////////////////////

/// A client which engages with a [PoprfServer] in verifiable mode, meaning
/// that the OPRF outputs can be checked against a server public key.
#[derive_where(Clone, ZeroizeOnDrop)]
#[derive_where(Debug, Eq, Hash, Ord, PartialEq, PartialOrd; <CS::Group as Group>::Scalar, <CS::Group as Group>::Elem)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Deserialize, serde::Serialize),
    serde(bound = "")
)]
pub struct PoprfClient<CS: CipherSuite> {
    #[cfg_attr(feature = "serde", serde(with = "Scalar::<CS::Group>"))]
    pub(crate) blind: <CS::Group as Group>::Scalar,
    #[cfg_attr(feature = "serde", serde(with = "Element::<CS::Group>"))]
    pub(crate) blinded_element: <CS::Group as Group>::Elem,
}

/// A server which engages with a [PoprfClient] in verifiable mode, meaning
/// that the OPRF outputs can be checked against a server public key.
#[derive_where(Clone, ZeroizeOnDrop)]
#[derive_where(Debug, Eq, Hash, Ord, PartialEq, PartialOrd; <CS::Group as Group>::Scalar, <CS::Group as Group>::Elem)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Deserialize, serde::Serialize),
    serde(bound = "")
)]
pub struct PoprfServer<CS: CipherSuite> {
    #[cfg_attr(feature = "serde", serde(with = "Scalar::<CS::Group>"))]
    pub(crate) sk: <CS::Group as Group>::Scalar,
    #[cfg_attr(feature = "serde", serde(with = "Element::<CS::Group>"))]
    pub(crate) pk: <CS::Group as Group>::Elem,
}

/////////////////////////
// API Implementations //
// =================== //
/////////////////////////

impl<CS: CipherSuite> PoprfClient<CS> {
    /// Computes the first step for the multiplicative blinding version of
    /// DH-OPRF.
    ///
    /// # Errors
    /// [`Error::Input`] if the `input` is empty or longer than [`u16::MAX`].
    pub fn blind<R: TryRngCore + TryCryptoRng>(
        input: &[u8],
        blinding_factor_rng: &mut R,
    ) -> Result<PoprfClientBlindResult<CS>> {
        let blind = CS::Group::random_scalar(blinding_factor_rng)?;
        Self::deterministic_blind_unchecked_inner(input, blind)
    }

    /// Computes the first step for the multiplicative blinding version of
    /// DH-OPRF, taking a blinding factor scalar as input instead of sampling
    /// from an RNG.
    ///
    /// # Caution
    ///
    /// This should be used with caution, since it does not perform any checks
    /// on the validity of the blinding factor!
    ///
    /// # Errors
    /// [`Error::Input`] if the `input` is empty or longer than [`u16::MAX`].
    #[cfg(any(feature = "danger", test))]
    pub fn deterministic_blind_unchecked(
        input: &[u8],
        blind: <CS::Group as Group>::Scalar,
    ) -> Result<PoprfClientBlindResult<CS>> {
        Self::deterministic_blind_unchecked_inner(input, blind)
    }

    /// Can only fail with [`Error::Input`].
    fn deterministic_blind_unchecked_inner(
        input: &[u8],
        blind: <CS::Group as Group>::Scalar,
    ) -> Result<PoprfClientBlindResult<CS>> {
        let blinded_element = deterministic_blind_unchecked::<CS>(input, &blind, Mode::Poprf)?;
        Ok(PoprfClientBlindResult {
            state: Self {
                blind,
                blinded_element,
            },
            message: BlindedElement(blinded_element),
        })
    }

    /// Computes the third step for the multiplicative blinding version of
    /// DH-OPRF, in which the client unblinds the server's message.
    ///
    /// # Errors
    /// - [`Error::Info`] if the `info` is longer than `u16::MAX`.
    /// - [`Error::Input`] if the `input` is empty or longer than [`u16::MAX`].
    /// - [`Error::Protocol`] if the protocol fails and can't be completed.
    /// - [`Error::ProofVerification`] if the `proof` failed to verify.
    pub fn finalize(
        &self,
        input: &[u8],
        evaluation_element: &EvaluationElement<CS>,
        proof: &Proof<CS>,
        pk: <CS::Group as Group>::Elem,
        info: Option<&[u8]>,
    ) -> Result<Output<CS::Hash>>
    where
        <<CS as CipherSuite>::Hash as OutputSizeUser>::OutputSize: ArrayLength,
    {
        let clients = core::array::from_ref(self);
        let messages = core::array::from_ref(evaluation_element);

        let mut batch_result =
            Self::batch_finalize(iter::once(input), clients, messages, proof, pk, info)?;
        batch_result.next().unwrap()
    }

    /// Allows for batching of the finalization of multiple [PoprfClient]
    /// and [EvaluationElement] pairs
    ///
    /// # Errors
    /// - [`Error::Info`] if the `info` is longer than `u16::MAX`.
    /// - [`Error::Protocol`] if the protocol fails and can't be completed.
    /// - [`Error::Batch`] if the number of `inputs`, `clients` and `messages`
    ///   don't match or is longer than [`u16::MAX`].
    /// - [`Error::ProofVerification`] if the `proof` failed to verify.
    ///
    /// The resulting messages can each fail individually with [`Error::Input`]
    /// if the `input` is empty or longer than [`u16::MAX`].
    pub fn batch_finalize<'a, II: 'a + Iterator<Item = &'a [u8]> + ExactSizeIterator, IC, IM>(
        inputs: II,
        clients: &'a IC,
        messages: &'a IM,
        proof: &Proof<CS>,
        pk: <CS::Group as Group>::Elem,
        info: Option<&'a [u8]>,
    ) -> Result<PoprfClientBatchFinalizeResult<'a, CS, II, IC, IM>>
    where
        CS: 'a,
        &'a IC: 'a + IntoIterator<Item = &'a PoprfClient<CS>>,
        <&'a IC as IntoIterator>::IntoIter: ExactSizeIterator,
        &'a IM: 'a + IntoIterator<Item = &'a EvaluationElement<CS>>,
        <&'a IM as IntoIterator>::IntoIter: ExactSizeIterator,
        <<CS as CipherSuite>::Hash as OutputSizeUser>::OutputSize: ArrayLength,
    {
        let unblinded_elements = poprf_unblind(clients, messages, pk, proof, info)?;

        finalize_after_unblind::<'a, CS, _, _>(unblinded_elements, inputs, info)
    }

    /// Only used for test functions
    #[cfg(test)]
    pub fn get_blind(&self) -> <CS::Group as Group>::Scalar {
        self.blind
    }
}

impl<CS: CipherSuite> PoprfServer<CS> {
    /// Produces a new instance of a [PoprfServer] using a supplied RNG
    ///
    /// # Errors
    /// [`Error::Protocol`] if the protocol fails and can't be completed.
    pub fn new<R: TryRngCore + TryCryptoRng>(rng: &mut R) -> Result<Self> {
        let mut seed = GenericArray::<_, <CS::Group as Group>::ScalarLen>::default();
        rng.try_fill_bytes(&mut seed).map_err(|_| Error::Protocol)?;

        Self::new_from_seed(&seed, &[])
    }

    /// Produces a new instance of a [PoprfServer] using a supplied set of
    /// bytes to represent the server's private key
    ///
    /// # Errors
    /// [`Error::Deserialization`] if the private key is not a valid point on
    /// the group or zero.
    pub fn new_with_key(key: &[u8]) -> Result<Self> {
        let sk = CS::Group::deserialize_scalar(key)?;
        let pk = CS::Group::base_elem() * &sk;
        Ok(Self { sk, pk })
    }

    /// Produces a new instance of a [PoprfServer] using a supplied set of
    /// bytes which are used as a seed to derive the server's private key.
    ///
    /// Corresponds to DeriveKeyPair() function from the VOPRF specification.
    ///
    /// # Errors
    /// - [`Error::DeriveKeyPair`] if the `input` and `seed` together are longer
    ///   then `u16::MAX - 3`.
    /// - [`Error::Protocol`] if the protocol fails and can't be completed.
    pub fn new_from_seed(seed: &[u8], info: &[u8]) -> Result<Self> {
        let (sk, pk) = derive_keypair::<CS>(seed, info, Mode::Poprf)?;
        Ok(Self { sk, pk })
    }

    /// Only used for tests
    #[cfg(test)]
    pub fn get_private_key(&self) -> <CS::Group as Group>::Scalar {
        self.sk
    }

    /// Computes the second step for the multiplicative blinding version of
    /// DH-OPRF. This message is sent from the server (who holds the OPRF key)
    /// to the client.
    ///
    /// # Errors
    /// - [`Error::Info`] if the `info` is longer than `u16::MAX`.
    /// - [`Error::Protocol`] if the protocol fails and can't be completed.
    pub fn blind_evaluate<R: TryRngCore + TryCryptoRng>(
        &self,
        rng: &mut R,
        blinded_element: &BlindedElement<CS>,
        info: Option<&[u8]>,
    ) -> Result<PoprfServerEvaluateResult<CS>> {
        let PoprfServerBatchEvaluatePrepareResult {
            mut prepared_evaluation_elements,
            prepared_tweak,
        } = self.batch_blind_evaluate_prepare(iter::once(blinded_element), info)?;

        let prepared_evaluation_element = prepared_evaluation_elements.next().unwrap();
        let prepared_evaluation_elements = core::array::from_ref(&prepared_evaluation_element);

        let PoprfServerBatchEvaluateFinishResult {
            mut messages,
            proof,
        } = Self::batch_blind_evaluate_finish(
            rng,
            iter::once(blinded_element),
            prepared_evaluation_elements,
            &prepared_tweak,
        )
        .unwrap();

        Ok(PoprfServerEvaluateResult {
            message: messages.next().unwrap(),
            proof,
        })
    }

    /// Allows for batching of the evaluation of multiple [BlindedElement]
    /// messages from a [PoprfClient]
    ///
    /// # Errors
    /// - [`Error::Info`] if the `info` is longer than `u16::MAX`.
    /// - [`Error::Protocol`] if the protocol fails and can't be completed.
    #[cfg(feature = "alloc")]
    pub fn batch_blind_evaluate<'a, R: TryRngCore + TryCryptoRng, IE>(
        &self,
        rng: &mut R,
        blinded_elements: &'a IE,
        info: Option<&[u8]>,
    ) -> Result<PoprfServerBatchEvaluateResult<CS>>
    where
        CS: 'a,
        &'a IE: 'a + IntoIterator<Item = &'a BlindedElement<CS>>,
        <&'a IE as IntoIterator>::IntoIter: ExactSizeIterator,
    {
        let PoprfServerBatchEvaluatePrepareResult {
            prepared_evaluation_elements,
            prepared_tweak,
        } = self.batch_blind_evaluate_prepare(blinded_elements.into_iter(), info)?;

        let prepared_evaluation_elements: Vec<_> = prepared_evaluation_elements.collect();

        // This can't fail because we know the size of the inputs.
        let PoprfServerBatchEvaluateFinishResult { messages, proof } =
            Self::batch_blind_evaluate_finish::<_, _, Vec<_>>(
                rng,
                blinded_elements.into_iter(),
                &prepared_evaluation_elements,
                &prepared_tweak,
            )
            .unwrap();

        let messages: Vec<_> = messages.collect();

        Ok(PoprfServerBatchEvaluateResult { messages, proof })
    }

    /// Alternative version of `batch_blind_evaluate` without
    /// memory allocation. Returned [`PreparedEvaluationElement`] have to
    /// be [`collect`](Iterator::collect)ed and passed into
    /// [`batch_blind_evaluate_finish`](Self::batch_blind_evaluate_finish).
    ///
    /// # Errors
    /// - [`Error::Info`] if the `info` is longer than `u16::MAX`.
    /// - [`Error::Protocol`] if the protocol fails and can't be completed.
    pub fn batch_blind_evaluate_prepare<'a, I: Iterator<Item = &'a BlindedElement<CS>>>(
        &self,
        blinded_elements: I,
        info: Option<&[u8]>,
    ) -> Result<PoprfServerBatchEvaluatePrepareResult<CS, I>>
    where
        CS: 'a,
    {
        let tweak = compute_tweak::<CS>(self.sk, info)?;

        Ok(PoprfServerBatchEvaluatePrepareResult {
            prepared_evaluation_elements: blinded_elements.zip(iter::repeat(tweak)).map(
                |(blinded_element, tweak)| {
                    PreparedEvaluationElement(EvaluationElement(
                        blinded_element.0 * &CS::Group::invert_scalar(tweak),
                    ))
                },
            ),
            prepared_tweak: PoprfPreparedTweak(tweak),
        })
    }

    /// See [`batch_blind_evaluate_prepare`](Self::batch_blind_evaluate_prepare)
    /// for more details.
    ///
    /// # Errors
    /// [`Error::Batch`] if the number of `blinded_elements` and
    /// `prepared_evaluation_elements` don't match or is longer then
    /// [`u16::MAX`]
    pub fn batch_blind_evaluate_finish<
        'a,
        'b,
        R: TryRngCore + TryCryptoRng,
        IB: Iterator<Item = &'a BlindedElement<CS>> + ExactSizeIterator,
        IE,
    >(
        rng: &mut R,
        blinded_elements: IB,
        prepared_evaluation_elements: &'b IE,
        prepared_tweak: &PoprfPreparedTweak<CS>,
    ) -> Result<PoprfServerBatchEvaluateFinishResult<'b, CS, IE>>
    where
        CS: 'a,
        &'b IE: IntoIterator<Item = &'b PreparedEvaluationElement<CS>>,
        <&'b IE as IntoIterator>::IntoIter: ExactSizeIterator,
    {
        let g = CS::Group::base_elem();
        let tweak = prepared_tweak.0;
        let tweaked_key = g * &tweak;

        let proof = generate_proof(
            rng,
            tweak,
            g,
            tweaked_key,
            prepared_evaluation_elements
                .into_iter()
                .map(|element| element.0 .0),
            blinded_elements.map(|element| element.0),
            Mode::Poprf,
        )?;

        let messages = prepared_evaluation_elements.into_iter().map(<fn(
            &PreparedEvaluationElement<CS>,
        ) -> _>::from(
            |element| EvaluationElement(element.0 .0),
        ));

        Ok(PoprfServerBatchEvaluateFinishResult { messages, proof })
    }

    /// Computes the output of the VOPRF on the server side
    ///
    /// # Errors
    /// [`Error::Input`]  if the `input` is longer then [`u16::MAX`].
    pub fn evaluate(
        &self,
        input: &[u8],
        info: Option<&[u8]>,
    ) -> Result<Output<<CS as CipherSuite>::Hash>> {
        let input_element = hash_to_group::<CS>(input, Mode::Poprf)?;
        if CS::Group::is_identity_elem(input_element).into() {
            return Err(Error::Input);
        };

        let tweak = compute_tweak::<CS>(self.sk, info)?;

        let evaluated_element = input_element * &CS::Group::invert_scalar(tweak);

        let issued_element = CS::Group::serialize_elem(evaluated_element);

        server_evaluate_hash_input::<CS>(input, info, issued_element)
    }

    /// Retrieves the server's public key
    pub fn get_public_key(&self) -> <CS::Group as Group>::Elem {
        self.pk
    }
}

impl<CS: CipherSuite> BlindedElement<CS> {
    /// Creates a [BlindedElement] from a raw group element.
    ///
    /// # Caution
    ///
    /// This should be used with caution, since it does not perform any checks
    /// on the validity of the value itself!
    #[cfg(feature = "danger")]
    pub fn from_value_unchecked(value: <CS::Group as Group>::Elem) -> Self {
        Self(value)
    }

    /// Exposes the internal value
    #[cfg(feature = "danger")]
    pub fn value(&self) -> <CS::Group as Group>::Elem {
        self.0
    }
}

impl<CS: CipherSuite> EvaluationElement<CS> {
    /// Creates an [EvaluationElement] from a raw group element.
    ///
    /// # Caution
    ///
    /// This should be used with caution, since it does not perform any checks
    /// on the validity of the value itself!
    #[cfg(feature = "danger")]
    pub fn from_value_unchecked(value: <CS::Group as Group>::Elem) -> Self {
        Self(value)
    }

    /// Exposes the internal value
    #[cfg(feature = "danger")]
    pub fn value(&self) -> <CS::Group as Group>::Elem {
        self.0
    }
}

/////////////////////////
// Convenience Structs //
//==================== //
/////////////////////////

/// Contains the fields that are returned by a verifiable client blind
#[derive_where(Debug; <CS::Group as Group>::Scalar, <CS::Group as Group>::Elem)]
pub struct PoprfClientBlindResult<CS: CipherSuite> {
    /// The state to be persisted on the client
    pub state: PoprfClient<CS>,
    /// The message to send to the server
    pub message: BlindedElement<CS>,
}

/// Concrete return type for [`PoprfClient::batch_finalize`].
pub type PoprfClientBatchFinalizeResult<'a, CS, II, IC, IM> =
    FinalizeAfterUnblindResult<'a, CS, PoprfUnblindResult<'a, CS, IC, IM>, II>;

/// Contains the fields that are returned by a verifiable server evaluate
#[derive_where(Debug; <CS::Group as Group>::Scalar, <CS::Group as Group>::Elem)]
pub struct PoprfServerEvaluateResult<CS: CipherSuite> {
    /// The message to send to the client
    pub message: EvaluationElement<CS>,
    /// The proof for the client to verify
    pub proof: Proof<CS>,
}

/// Contains the fields that are returned by a verifiable server batch evaluate
#[derive_where(Debug; <CS::Group as Group>::Scalar, <CS::Group as Group>::Elem)]
#[cfg(feature = "alloc")]
pub struct PoprfServerBatchEvaluateResult<CS: CipherSuite> {
    /// The messages to send to the client
    pub messages: Vec<EvaluationElement<CS>>,
    /// The proof for the client to verify
    pub proof: Proof<CS>,
}

/// Concrete type of [`EvaluationElement`]s in
/// [`PoprfServerBatchEvaluatePrepareResult`].
pub type PoprfServerBatchEvaluatePreparedEvaluationElements<CS, I> = Map<
    Zip<I, Repeat<<<CS as CipherSuite>::Group as Group>::Scalar>>,
    fn(
        (
            &BlindedElement<CS>,
            <<CS as CipherSuite>::Group as Group>::Scalar,
        ),
    ) -> PreparedEvaluationElement<CS>,
>;

/// Prepared tweak by a partially verifiable server batch evaluate prepare.
#[derive_where(Clone, ZeroizeOnDrop)]
#[derive_where(Debug, Eq, Hash, Ord, PartialEq, PartialOrd; <CS::Group as Group>::Scalar)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Deserialize, serde::Serialize),
    serde(bound = "")
)]
pub struct PoprfPreparedTweak<CS: CipherSuite>(
    #[cfg_attr(feature = "serde", serde(with = "Scalar::<CS::Group>"))]
    <CS::Group as Group>::Scalar,
);

/// Contains the fields that are returned by a partially verifiable server batch
/// evaluate prepare
#[derive_where(Debug; I, <CS::Group as Group>::Scalar)]
pub struct PoprfServerBatchEvaluatePrepareResult<CS: CipherSuite, I> {
    /// Prepared [`EvaluationElement`].
    pub prepared_evaluation_elements: PoprfServerBatchEvaluatePreparedEvaluationElements<CS, I>,
    /// Prepared tweak.
    pub prepared_tweak: PoprfPreparedTweak<CS>,
}

/// Concrete type of [`EvaluationElement`]s in
/// [`PoprfServerBatchEvaluateFinishResult`].
pub type PoprfServerBatchEvaluateFinishedMessages<'a, CS, I> = Map<
    <&'a I as IntoIterator>::IntoIter,
    fn(&PreparedEvaluationElement<CS>) -> EvaluationElement<CS>,
>;

/// Contains the fields that are returned by a verifiable server batch evaluate
/// finish.
#[derive_where(Debug; <&'a I as IntoIterator>::IntoIter, <CS::Group as Group>::Scalar)]
pub struct PoprfServerBatchEvaluateFinishResult<'a, CS: 'a + CipherSuite, I>
where
    &'a I: IntoIterator<Item = &'a PreparedEvaluationElement<CS>>,
{
    /// The [`EvaluationElement`]s to send to the client
    pub messages: PoprfServerBatchEvaluateFinishedMessages<'a, CS, I>,
    /// The proof for the client to verify
    pub proof: Proof<CS>,
}

/////////////////////
// Inner functions //
// =============== //
/////////////////////

/// Inner function for POPRF blind. Computes the tweaked key from the server
/// public key and info.
///
/// Can only fail with [`Error::Info`] or [`Error::Protocol`]
fn compute_tweaked_key<CS: CipherSuite>(
    pk: <CS::Group as Group>::Elem,
    info: Option<&[u8]>,
) -> Result<<CS::Group as Group>::Elem> {
    // None for info is treated the same as empty bytes
    let info = info.unwrap_or_default();

    // framedInfo = "Info" || I2OSP(len(info), 2) || info
    // m = G.HashToScalar(framedInfo)
    // T = G.ScalarBaseMult(m)
    // tweakedKey = T + pkS
    // if tweakedKey == G.Identity():
    //   raise InvalidInputError
    let info_len = i2osp_2(info.len()).map_err(|_| Error::Info)?;
    let framed_info = [STR_INFO.as_slice(), &info_len, info];

    let dst = Dst::new::<CS, _, _>(STR_HASH_TO_SCALAR, Mode::Poprf);
    // This can't fail, the size of the `input` is known.
    let m = CS::Group::hash_to_scalar::<CS::Hash>(&framed_info, &dst.as_dst()).unwrap();

    let t = CS::Group::base_elem() * &m;
    let tweaked_key = t + &pk;

    // Check if resulting element
    match bool::from(CS::Group::is_identity_elem(tweaked_key)) {
        true => Err(Error::Protocol),
        false => Ok(tweaked_key),
    }
}

/// Inner function for POPRF evaluate. Computes the tweak from the server
/// private key and info.
///
/// Can only fail with [`Error::Info`] and [`Error::Protocol`].
fn compute_tweak<CS: CipherSuite>(
    sk: <CS::Group as Group>::Scalar,
    info: Option<&[u8]>,
) -> Result<<CS::Group as Group>::Scalar> {
    // None for info is treated the same as empty bytes
    let info = info.unwrap_or_default();

    // framedInfo = "Info" || I2OSP(len(info), 2) || info
    // m = G.HashToScalar(framedInfo)
    // t = skS + m
    // if t == 0:
    //   raise InverseError
    let info_len = i2osp_2(info.len()).map_err(|_| Error::Info)?;
    let framed_info = [STR_INFO.as_slice(), &info_len, info];

    let dst = Dst::new::<CS, _, _>(STR_HASH_TO_SCALAR, Mode::Poprf);
    // This can't fail, the size of the `input` is known.
    let m = CS::Group::hash_to_scalar::<CS::Hash>(&framed_info, &dst.as_dst()).unwrap();

    let t = sk + &m;

    // Check if resulting element is equal to zero
    match bool::from(CS::Group::is_zero_scalar(t)) {
        true => Err(Error::Protocol),
        false => Ok(t),
    }
}

type PoprfUnblindResult<'a, CS, IC, IM> = Map<
    Zip<
        Map<
            <&'a IC as IntoIterator>::IntoIter,
            fn(&PoprfClient<CS>) -> <<CS as CipherSuite>::Group as Group>::Scalar,
        >,
        <&'a IM as IntoIterator>::IntoIter,
    >,
    fn(
        (
            <<CS as CipherSuite>::Group as Group>::Scalar,
            &'a EvaluationElement<CS>,
        ),
    ) -> <<CS as CipherSuite>::Group as Group>::Elem,
>;

/// Can only fail with [`Error::Info`], [`Error::Protocol`], [`Error::Batch] or
/// [`Error::ProofVerification`].
fn poprf_unblind<'a, CS: 'a + CipherSuite, IC, IM>(
    clients: &'a IC,
    messages: &'a IM,
    pk: <CS::Group as Group>::Elem,
    proof: &Proof<CS>,
    info: Option<&[u8]>,
) -> Result<PoprfUnblindResult<'a, CS, IC, IM>>
where
    &'a IC: 'a + IntoIterator<Item = &'a PoprfClient<CS>>,
    <&'a IC as IntoIterator>::IntoIter: ExactSizeIterator,
    &'a IM: 'a + IntoIterator<Item = &'a EvaluationElement<CS>>,
    <&'a IM as IntoIterator>::IntoIter: ExactSizeIterator,
{
    let info = info.unwrap_or_default();
    let tweaked_key = compute_tweaked_key::<CS>(pk, Some(info))?;

    let g = CS::Group::base_elem();

    let blinds = clients
        .into_iter()
        // Convert to `fn` pointer to make a return type possible.
        .map(<fn(&PoprfClient<CS>) -> _>::from(|x| x.blind));
    let evaluation_elements = messages.into_iter().map(|element| element.0);
    let blinded_elements = clients.into_iter().map(|client| client.blinded_element);

    verify_proof(
        g,
        tweaked_key,
        evaluation_elements,
        blinded_elements,
        proof,
        Mode::Poprf,
    )?;

    Ok(blinds
        .zip(messages)
        .map(|(blind, x)| x.0 * &CS::Group::invert_scalar(blind)))
}

type FinalizeAfterUnblindResult<'a, CS, IE, II> = Map<
    Zip<Zip<IE, II>, Repeat<&'a [u8]>>,
    fn(
        ((<<CS as CipherSuite>::Group as Group>::Elem, &[u8]), &[u8]),
    ) -> Result<Output<<CS as CipherSuite>::Hash>>,
>;

/// Can only fail with [`Error::Batch`] and returned values can only fail with
/// [`Error::Info`] or [`Error::Input`] individually.
fn finalize_after_unblind<
    'a,
    CS: CipherSuite,
    IE: 'a + Iterator<Item = <CS::Group as Group>::Elem> + ExactSizeIterator,
    II: 'a + Iterator<Item = &'a [u8]> + ExactSizeIterator,
>(
    unblinded_elements: IE,
    inputs: II,
    info: Option<&'a [u8]>,
) -> Result<FinalizeAfterUnblindResult<'a, CS, IE, II>>
where
    <<CS as CipherSuite>::Hash as OutputSizeUser>::OutputSize: ArrayLength,
{
    if unblinded_elements.len() != inputs.len() {
        return Err(Error::Batch);
    }

    let info = info.unwrap_or_default();

    Ok(unblinded_elements.zip(inputs).zip(iter::repeat(info)).map(
        |((unblinded_element, input), info)| {
            let elem_len = <CS::Group as Group>::ElemLen::U16.to_be_bytes();

            // hashInput = I2OSP(len(input), 2) || input ||
            //             I2OSP(len(info), 2) || info ||
            //             I2OSP(len(unblindedElement), 2) || unblindedElement ||
            //             "Finalize"
            // return Hash(hashInput)
            let output = CS::Hash::new()
                .chain_update(i2osp_2(input.as_ref().len()).map_err(|_| Error::Input)?)
                .chain_update(input.as_ref())
                .chain_update(i2osp_2(info.as_ref().len()).map_err(|_| Error::Info)?)
                .chain_update(info.as_ref())
                .chain_update(elem_len)
                .chain_update(CS::Group::serialize_elem(unblinded_element))
                .chain_update(STR_FINALIZE)
                .finalize();

            Ok(output)
        },
    ))
}

///////////
// Tests //
// ===== //
///////////

#[cfg(test)]
mod tests {
    use core::ptr;

    use rand::rngs::OsRng;

    use super::*;
    use crate::common::STR_HASH_TO_GROUP;
    use crate::Group;

    fn prf<CS: CipherSuite>(
        input: &[u8],
        key: <CS::Group as Group>::Scalar,
        info: &[u8],
        mode: Mode,
    ) -> Output<CS::Hash> {
        let t = compute_tweak::<CS>(key, Some(info)).unwrap();

        let dst = Dst::new::<CS, _, _>(STR_HASH_TO_GROUP, mode);
        let point = CS::Group::hash_to_curve::<CS::Hash>(&[input], &dst.as_dst()).unwrap();

        // evaluatedElement = G.ScalarInverse(t) * blindedElement
        let res = point * &CS::Group::invert_scalar(t);

        finalize_after_unblind::<CS, _, _>(iter::once(res), iter::once(input), Some(info))
            .unwrap()
            .next()
            .unwrap()
            .unwrap()
    }

    fn verifiable_retrieval<CS: CipherSuite>() {
        let input = b"input";
        let info = b"info";
        let mut rng = OsRng;
        let server = PoprfServer::<CS>::new(&mut rng).unwrap();
        let client_blind_result = PoprfClient::<CS>::blind(input, &mut rng).unwrap();
        let server_result = server
            .blind_evaluate(&mut rng, &client_blind_result.message, Some(info))
            .unwrap();
        let client_finalize_result = client_blind_result
            .state
            .finalize(
                input,
                &server_result.message,
                &server_result.proof,
                server.get_public_key(),
                Some(info),
            )
            .unwrap();
        let res2 = prf::<CS>(input, server.get_private_key(), info, Mode::Poprf);
        assert_eq!(client_finalize_result, res2);
    }

    fn verifiable_bad_public_key<CS: CipherSuite>() {
        let input = b"input";
        let info = b"info";
        let mut rng = OsRng;
        let server = PoprfServer::<CS>::new(&mut rng).unwrap();
        let client_blind_result = PoprfClient::<CS>::blind(input, &mut rng).unwrap();
        let server_result = server
            .blind_evaluate(&mut rng, &client_blind_result.message, Some(info))
            .unwrap();
        let wrong_pk = {
            let dst = Dst::new::<CS, _, _>(STR_HASH_TO_GROUP, Mode::Oprf);
            // Choose a group element that is unlikely to be the right public key
            CS::Group::hash_to_curve::<CS::Hash>(&[b"msg"], &dst.as_dst()).unwrap()
        };
        let client_finalize_result = client_blind_result.state.finalize(
            input,
            &server_result.message,
            &server_result.proof,
            wrong_pk,
            Some(info),
        );
        assert!(client_finalize_result.is_err());
    }

    fn verifiable_server_evaluate<CS: CipherSuite>() {
        let input = b"input";
        let info = Some(b"info".as_slice());
        let mut rng = OsRng;
        let client_blind_result = PoprfClient::<CS>::blind(input, &mut rng).unwrap();
        let server = PoprfServer::<CS>::new(&mut rng).unwrap();
        let server_result = server
            .blind_evaluate(&mut rng, &client_blind_result.message, info)
            .unwrap();

        let client_finalize = client_blind_result
            .state
            .finalize(
                input,
                &server_result.message,
                &server_result.proof,
                server.get_public_key(),
                info,
            )
            .unwrap();

        // We expect the outputs from client and server to be equal given an identical
        // input
        let server_evaluate = server.evaluate(input, info).unwrap();
        assert_eq!(client_finalize, server_evaluate);

        // We expect the outputs from client and server to be different given different
        // inputs
        let wrong_input = b"wrong input";
        let server_evaluate = server.evaluate(wrong_input, info).unwrap();
        assert!(client_finalize != server_evaluate);
    }

    fn zeroize_verifiable_client<CS: CipherSuite>() {
        let input = b"input";
        let mut rng = OsRng;
        let client_blind_result = PoprfClient::<CS>::blind(input, &mut rng).unwrap();

        let mut state = client_blind_result.state;
        unsafe { ptr::drop_in_place(&mut state) };
        assert!(state.serialize().iter().all(|&x| x == 0));

        let mut message = client_blind_result.message;
        unsafe { ptr::drop_in_place(&mut message) };
        assert!(message.serialize().iter().all(|&x| x == 0));
    }

    fn zeroize_verifiable_server<CS: CipherSuite>() {
        let input = b"input";
        let info = b"info";
        let mut rng = OsRng;
        let server = PoprfServer::<CS>::new(&mut rng).unwrap();
        let client_blind_result = PoprfClient::<CS>::blind(input, &mut rng).unwrap();
        let server_result = server
            .blind_evaluate(&mut rng, &client_blind_result.message, Some(info))
            .unwrap();

        let mut state = server;
        unsafe { ptr::drop_in_place(&mut state) };
        assert!(state.serialize().iter().all(|&x| x == 0));

        let mut message = server_result.message;
        unsafe { ptr::drop_in_place(&mut message) };
        assert!(message.serialize().iter().all(|&x| x == 0));

        let mut proof = server_result.proof;
        unsafe { ptr::drop_in_place(&mut proof) };
        assert!(proof.serialize().iter().all(|&x| x == 0));
    }

    #[test]
    fn test_functionality() -> Result<()> {
        use p256::NistP256;
        use p384::NistP384;
        use p521::NistP521;

        #[cfg(feature = "ristretto255")]
        {
            use crate::Ristretto255;

            verifiable_retrieval::<Ristretto255>();
            verifiable_bad_public_key::<Ristretto255>();
            verifiable_server_evaluate::<Ristretto255>();

            zeroize_verifiable_client::<Ristretto255>();
            zeroize_verifiable_server::<Ristretto255>();
        }

        verifiable_retrieval::<NistP256>();
        verifiable_bad_public_key::<NistP256>();
        verifiable_server_evaluate::<NistP256>();

        zeroize_verifiable_client::<NistP256>();
        zeroize_verifiable_server::<NistP256>();

        verifiable_retrieval::<NistP384>();
        verifiable_bad_public_key::<NistP384>();
        verifiable_server_evaluate::<NistP384>();

        zeroize_verifiable_client::<NistP384>();
        zeroize_verifiable_server::<NistP384>();

        verifiable_retrieval::<NistP521>();
        verifiable_bad_public_key::<NistP521>();
        verifiable_server_evaluate::<NistP521>();

        zeroize_verifiable_client::<NistP521>();
        zeroize_verifiable_server::<NistP521>();

        Ok(())
    }
}