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
use crate::{
    CryptoMaterialError, HashValue, PrivateKey, PublicKey, Uniform,
    VRFPrivateKey, VRFProof, VRFPublicKey, ValidCryptoMaterial,
    ValidCryptoMaterialStringExt,
};
use anyhow::{anyhow, Result};
use diem_crypto_derive::{
    DeserializeKey, SerializeKey, SilentDebug, SilentDisplay,
};
use lazy_static::lazy_static;
use openssl::{ec, nid::Nid};
use parking_lot::Mutex;
use std::{
    convert::TryFrom,
    fmt::{self, Formatter},
};
use vrf::{
    openssl::{CipherSuite, ECVRF},
    VRF,
};

// TODO(lpl): Choose a curve;
lazy_static! {
    /// VRF Cipher context. Mutex is needed because functions require `&mut self`.
    pub static ref VRF_CONTEXT: Mutex<ECVRF> = Mutex::new(
        ECVRF::from_suite(CipherSuite::SECP256K1_SHA256_TAI)
            .expect("VRF context initialization error")
    );
}

/// Elliptic Curve VRF private key
#[derive(
    DeserializeKey,
    Clone,
    SerializeKey,
    SilentDebug,
    SilentDisplay,
    Eq,
    PartialEq,
)]
pub struct EcVrfPrivateKey(Vec<u8>);

/// Elliptic Curve VRF public key
#[derive(DeserializeKey, Clone, SerializeKey, Debug)]
pub struct EcVrfPublicKey(Vec<u8>);

/// Elliptic Curve VRF proof
#[derive(DeserializeKey, Clone, SerializeKey, Debug)]
pub struct EcVrfProof(Vec<u8>);

impl VRFPrivateKey for EcVrfPrivateKey {
    type ProofMaterial = EcVrfProof;
    type PublicKeyMaterial = EcVrfPublicKey;

    fn compute(&self, seed: &[u8]) -> Result<Self::ProofMaterial> {
        match VRF_CONTEXT.lock().prove(&self.0, seed) {
            Ok(proof) => Ok(EcVrfProof(proof)),
            Err(e) => Err(anyhow!(e)),
        }
    }
}

impl VRFPublicKey for EcVrfPublicKey {
    type PrivateKeyMaterial = EcVrfPrivateKey;
    type ProofMaterial = EcVrfProof;
}

impl VRFProof for EcVrfProof {
    type PrivateKeyMaterial = EcVrfPrivateKey;
    type PublicKeyMaterial = EcVrfPublicKey;

    fn to_hash(&self) -> Result<HashValue> {
        match VRF_CONTEXT.lock().proof_to_hash(&self.0) {
            Ok(h) => HashValue::from_slice(&h).map_err(|e| anyhow!(e)),
            Err(e) => Err(anyhow!(e)),
        }
    }

    fn verify(
        &self, seed: &[u8], public_key: &Self::PublicKeyMaterial,
    ) -> Result<HashValue> {
        match VRF_CONTEXT.lock().verify(&public_key.0, &self.0, seed) {
            Ok(h) => HashValue::from_slice(&h).map_err(|e| anyhow!(e)),
            Err(e) => Err(anyhow!(e)),
        }
    }
}

impl PrivateKey for EcVrfPrivateKey {
    type PublicKeyMaterial = EcVrfPublicKey;
}

impl PublicKey for EcVrfPublicKey {
    type PrivateKeyMaterial = EcVrfPrivateKey;
}

impl fmt::Display for EcVrfPublicKey {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_encoded_string().map_err(|_| fmt::Error)?)
    }
}

impl From<Vec<u8>> for EcVrfPublicKey {
    fn from(raw: Vec<u8>) -> Self { EcVrfPublicKey(raw) }
}

impl From<&EcVrfPrivateKey> for EcVrfPublicKey {
    fn from(private_key: &EcVrfPrivateKey) -> Self {
        EcVrfPublicKey(
            VRF_CONTEXT
                .lock()
                .derive_public_key(&private_key.0)
                .expect("VRF derive public key error"),
        )
    }
}

impl TryFrom<&[u8]> for EcVrfPrivateKey {
    type Error = CryptoMaterialError;

    /// Deserialize an EcVrfPrivateKey. This method will also check for key
    /// validity.
    fn try_from(
        bytes: &[u8],
    ) -> std::result::Result<EcVrfPrivateKey, CryptoMaterialError> {
        // TODO(lpl): Check validation.
        Ok(EcVrfPrivateKey(bytes.to_vec()))
    }
}

impl TryFrom<&[u8]> for EcVrfPublicKey {
    type Error = CryptoMaterialError;

    /// Deserialize an EcVrfPrivateKey. This method will also check for key
    /// validity.
    fn try_from(
        bytes: &[u8],
    ) -> std::result::Result<EcVrfPublicKey, CryptoMaterialError> {
        // TODO(lpl): Check validation
        Ok(EcVrfPublicKey(bytes.to_vec()))
    }
}

impl TryFrom<&[u8]> for EcVrfProof {
    type Error = CryptoMaterialError;

    /// Deserialize an EcVrfPrivateKey. This method will also check for key
    /// validity.
    fn try_from(
        bytes: &[u8],
    ) -> std::result::Result<EcVrfProof, CryptoMaterialError> {
        // TODO(lpl): Check validation
        Ok(EcVrfProof(bytes.to_vec()))
    }
}

impl std::hash::Hash for EcVrfPublicKey {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        let encoded_pubkey = self.to_bytes();
        state.write(&encoded_pubkey);
    }
}

impl PartialEq for EcVrfPublicKey {
    fn eq(&self, other: &EcVrfPublicKey) -> bool {
        self.to_bytes() == other.to_bytes()
    }
}

impl std::hash::Hash for EcVrfProof {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        let encoded_pubkey = ValidCryptoMaterial::to_bytes(self);
        state.write(&encoded_pubkey);
    }
}

impl PartialEq for EcVrfProof {
    fn eq(&self, other: &EcVrfProof) -> bool {
        self.to_bytes() == other.to_bytes()
    }
}

impl fmt::Display for EcVrfProof {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_encoded_string().map_err(|_| fmt::Error)?)
    }
}

impl Eq for EcVrfPublicKey {}

impl Eq for EcVrfProof {}

impl ValidCryptoMaterial for EcVrfPrivateKey {
    fn to_bytes(&self) -> Vec<u8> { self.0.clone() }
}

impl ValidCryptoMaterial for EcVrfPublicKey {
    fn to_bytes(&self) -> Vec<u8> { self.0.clone() }
}

impl ValidCryptoMaterial for EcVrfProof {
    fn to_bytes(&self) -> Vec<u8> { self.0.clone() }
}

// TODO(lpl): Double check the correctness of key generation.
// Reuse ec group in VRF_CONTEXT?
impl Uniform for EcVrfPrivateKey {
    fn generate<R>(_rng: &mut R) -> Self
    where R: ::rand::RngCore + ::rand::CryptoRng {
        let ec_group = ec::EcGroup::from_curve_name(Nid::SECP256K1).unwrap();
        Self(
            ec::EcKey::generate(&ec_group)
                .unwrap()
                .private_key()
                .to_vec(),
        )
    }
}

#[cfg(any(test, feature = "fuzzing"))]
use crate::test_utils::{self, KeyPair};

/// Produces a uniformly random bls keypair from a seed
#[cfg(any(test, feature = "fuzzing"))]
pub fn keypair_strategy(
) -> impl Strategy<Value = KeyPair<EcVrfPrivateKey, EcVrfPublicKey>> {
    test_utils::uniform_keypair_strategy::<EcVrfPrivateKey, EcVrfPublicKey>()
}

#[cfg(any(test, feature = "fuzzing"))]
use proptest::prelude::*;

#[cfg(any(test, feature = "fuzzing"))]
impl proptest::arbitrary::Arbitrary for EcVrfPublicKey {
    type Parameters = ();
    type Strategy = BoxedStrategy<Self>;

    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
        crate::test_utils::uniform_keypair_strategy::<
            EcVrfPrivateKey,
            EcVrfPublicKey,
        >()
        .prop_map(|v| v.public_key)
        .boxed()
    }
}