1use core::fmt;
11use core::str::FromStr;
12
13use curve25519_dalek::edwards::{CompressedEdwardsY, EdwardsPoint};
14use curve25519_dalek::scalar::Scalar;
15use curve25519_dalek::traits::VartimeMultiscalarMul;
16use zeroize::Zeroizing;
17
18use crate::ed25519::{self, ExpandedKey};
19use crate::hex::{self, ParseHexError};
20use crate::key::{PrivateKey, PublicKey};
21
22const SUITE: u8 = 0x03;
24
25const IDENTITY: [u8; 32] = {
27 let mut bytes = [0; 32];
28 bytes[0] = 1;
29 bytes
30};
31
32#[derive(Clone, PartialEq, Eq, Debug)]
34pub struct VrfProof {
35 pub gamma: [u8; 32],
36 pub verification_hash: [u8; 16],
37 pub scalar: [u8; 32],
38}
39
40#[derive(Clone, Copy, PartialEq, Eq)]
42pub struct ProofHash(pub [u8; 64]);
43
44impl ProofHash {
45 pub fn generation_hash(&self) -> GenerationHash {
47 GenerationHash(self.0[..32].try_into().expect("half of 64 bytes"))
48 }
49}
50
51impl fmt::Display for ProofHash {
52 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53 f.write_str(&hex::encode(&self.0))
54 }
55}
56
57impl fmt::Debug for ProofHash {
58 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 write!(f, "ProofHash({self})")
60 }
61}
62
63#[derive(Clone, Copy, PartialEq, Eq, Hash)]
65pub struct GenerationHash(pub [u8; 32]);
66
67impl fmt::Display for GenerationHash {
68 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69 f.write_str(&hex::encode(&self.0))
70 }
71}
72
73impl fmt::Debug for GenerationHash {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 write!(f, "GenerationHash({self})")
76 }
77}
78
79impl FromStr for GenerationHash {
80 type Err = ParseHexError;
81
82 fn from_str(text: &str) -> Result<Self, Self::Err> {
83 hex::decode(text).map(Self)
84 }
85}
86
87pub fn prove(private_key: &PrivateKey, alpha: &[u8]) -> Option<VrfProof> {
92 let key = ExpandedKey::new(private_key.as_bytes());
93 let public_key = key.public_key().to_bytes();
94 let h = map_to_point(&public_key, alpha)?;
95 let gamma = scalar_mult(&key.scalar, &h);
97 if gamma == EdwardsPoint::default().compress().to_bytes() {
98 return None;
99 }
100 let k = Zeroizing::new(Scalar::from_bytes_mod_order_wide(&ed25519::sha512([
102 &key.prefix[..],
103 &h[..],
104 ])));
105 let k_times_b = EdwardsPoint::mul_base(&k).compress().to_bytes();
106 let k_times_h = scalar_mult(&k, &h);
107 let verification_hash = challenge(&h, &gamma, &k_times_b, &k_times_h);
108 let product = Zeroizing::new(widen(&verification_hash) * *key.scalar);
110 let scalar = (*product + *k).to_bytes();
111 Some(VrfProof {
112 gamma,
113 verification_hash,
114 scalar,
115 })
116}
117
118pub fn gamma(private_key: &PrivateKey, alpha: &[u8]) -> Option<[u8; 32]> {
121 let key = ExpandedKey::new(private_key.as_bytes());
122 let h = map_to_point(&key.public_key().to_bytes(), alpha)?;
123 let gamma = scalar_mult(&key.scalar, &h);
124 (gamma != EdwardsPoint::default().compress().to_bytes()).then_some(gamma)
125}
126
127#[derive(Clone, Copy, PartialEq, Eq, Debug)]
131pub struct Checks {
132 pub public_key: bool,
135 pub gamma: bool,
138}
139
140impl Checks {
141 pub const ALL: Self = Self {
143 public_key: true,
144 gamma: true,
145 };
146 pub const NONE: Self = Self {
148 public_key: false,
149 gamma: false,
150 };
151}
152
153pub fn verify(public_key: &PublicKey, alpha: &[u8], proof: &VrfProof) -> Option<ProofHash> {
155 verify_with(public_key, alpha, proof, Checks::ALL)
156}
157
158pub fn is_valid_public_key(public_key: &PublicKey) -> bool {
161 ed25519::decode(&public_key.0).is_some() && !is_neutral(&public_key.0)
162}
163
164fn is_neutral(bytes: &[u8; 32]) -> bool {
166 bytes[0] == 1 && bytes[1..31].iter().all(|&byte| byte == 0) && bytes[31] & 0x7F == 0
167}
168
169pub fn verify_with(
171 public_key: &PublicKey,
172 alpha: &[u8],
173 proof: &VrfProof,
174 checks: Checks,
175) -> Option<ProofHash> {
176 if !ed25519::is_canonical(&proof.gamma) || decompress(&proof.gamma).is_none() {
178 return None;
179 }
180 let h = map_to_point(&public_key.0, alpha)?;
181 let s = Option::<Scalar>::from(Scalar::from_canonical_bytes(proof.scalar))?;
183 let c = widen(&proof.verification_hash);
184 let u = match ed25519::decode(&public_key.0) {
187 Some(y) => EdwardsPoint::vartime_double_scalar_mul_basepoint(&c, &-y, &s)
188 .compress()
189 .to_bytes(),
190 None if checks.public_key => return None,
191 None => [0; 32],
192 };
193 if checks.gamma && is_neutral(&public_key.0) {
195 return None;
196 }
197 let h_point = decompress(&h).expect("a compressed point");
202 let s_times_h = EdwardsPoint::vartime_multiscalar_mul([s], [h_point]);
203 let c_times_gamma = match ed25519::decode(&proof.gamma) {
204 Some(gamma) => EdwardsPoint::vartime_multiscalar_mul([c], [gamma]),
205 None if checks.gamma => return None,
206 None => decompress(&[0; 32]).expect("a compressed point"),
207 };
208 if checks.gamma && c_times_gamma.compress().to_bytes() == IDENTITY {
209 return None;
210 }
211 let v = (s_times_h - c_times_gamma).compress().to_bytes();
212 (challenge(&h, &proof.gamma, &u, &v) == proof.verification_hash)
213 .then(|| proof_hash(&proof.gamma))
214}
215
216pub fn proof_hash(gamma: &[u8; 32]) -> ProofHash {
218 let gamma_times_eight = decompress(gamma)
219 .map(|point| point.mul_by_cofactor().compress().to_bytes())
220 .unwrap_or([0; 32]);
221 let hash = ed25519::sha512([&[SUITE, 0x03][..], &gamma_times_eight[..]]);
222 ProofHash(*hash)
223}
224
225fn map_to_point(public_key: &[u8; 32], alpha: &[u8]) -> Option<[u8; 32]> {
228 (0..=u8::MAX).find_map(|counter| {
229 let hash = ed25519::sha512([&[SUITE, 0x01][..], &public_key[..], alpha, &[counter]]);
230 let candidate: [u8; 32] = hash[..32].try_into().expect("32 of 64 bytes");
231 if !ed25519::is_canonical(&candidate) {
232 return None;
233 }
234 decompress(&candidate).map(|point| point.mul_by_cofactor().compress().to_bytes())
235 })
236}
237
238fn challenge(h: &[u8; 32], gamma: &[u8; 32], u: &[u8; 32], v: &[u8; 32]) -> [u8; 16] {
240 let hash = ed25519::sha512([&[SUITE, 0x02][..], &h[..], &gamma[..], &u[..], &v[..]]);
241 hash[..16].try_into().expect("16 of 64 bytes")
242}
243
244fn widen(verification_hash: &[u8; 16]) -> Scalar {
246 let mut bytes = [0; 32];
247 bytes[..16].copy_from_slice(verification_hash);
248 Scalar::from_bytes_mod_order(bytes)
249}
250
251fn scalar_mult(multiplier: &Scalar, point: &[u8; 32]) -> [u8; 32] {
254 match ed25519::decode(point) {
255 Some(point) => (multiplier * point).compress().to_bytes(),
256 None => [0; 32],
257 }
258}
259
260fn decompress(bytes: &[u8; 32]) -> Option<EdwardsPoint> {
262 CompressedEdwardsY(*bytes).decompress()
263}
264
265#[cfg(test)]
266mod tests {
267 use super::*;
268 use curve25519_dalek::constants::EIGHT_TORSION;
269
270 fn bytes<const N: usize>(text: &str) -> [u8; N] {
271 hex::decode(text).unwrap()
272 }
273
274 fn alpha(text: &str) -> Vec<u8> {
275 (0..text.len())
276 .step_by(2)
277 .map(|index| u8::from_str_radix(&text[index..index + 2], 16).unwrap())
278 .collect()
279 }
280
281 const DRAFT_05: [[&str; 6]; 3] = [
284 [
285 "9D61B19DEFFD5A60BA844AF492EC2CC44449C5697B326919703BAC031CAE7F60",
286 "",
287 "9275DF67A68C8745C0FF97B48201EE6DB447F7C93B23AE24CDC2400F52FDB08A",
288 "1A6AC7EC71BF9C9C76E96EE4675EBFF6",
289 "0625AF28718501047BFD87B810C2D2139B73C23BD69DE66360953A642C2A330A",
290 "A64C292EC45F6B252828AFF9A02A0FE88D2FCC7F5FC61BB328F03F4C6C0657A9\
291 D26EFB23B87647FF54F71CD51A6FA4C4E31661D8F72B41FF00AC4D2EEC2EA7B3",
292 ],
293 [
294 "4CCD089B28FF96DA9DB6C346EC114E0F5B8A319F35ABA624DA8CF6ED4FB8A6FB",
295 "72",
296 "84A63E74ECA8FDD64E9972DCDA1C6F33D03CE3CD4D333FD6CC789DB12B5A7B9D",
297 "03F1CB6B2BF7CD81A2A20BACF6E1C04E",
298 "59F2FA16D9119C73A45A97194B504FB9A5C8CF37F6DA85E03368D6882E511008",
299 "CDDAA399BB9C56D3BE15792E43A6742FB72B1D248A7F24FD5CC585B232C26C93\
300 4711393B4D97284B2BCCA588775B72DC0B0F4B5A195BC41F8D2B80B6981C784E",
301 ],
302 [
303 "C5AA8DF43F9F837BEDB7442F31DCB7B166D38535076F094B85CE3A2E0B4458F7",
304 "AF82",
305 "ACA8ADE9B7F03E2B149637629F95654C94FC9053C225EC21E5838F193AF2B727",
306 "B84AD849B0039AD38B41513FE5A66CDD",
307 "2367737A84B488D62486BD2FB110B4801A46BFCA770AF98E059158AC563B690F",
308 "D938B2012F2551B0E13A49568612EFFCBDCA2AED5D1D3A13F47E180E01218916\
309 E049837BD246F66D5058E56D3413DBBBAD964F5E9F160A81C9A1355DCD99B453",
310 ],
311 ];
312
313 fn valid() -> (PublicKey, Vec<u8>, VrfProof) {
315 let private_key = PrivateKey::from_bytes(&[7; 32]);
316 let public_key = PublicKey::from_private_key(&private_key);
317 let alpha = b"heika".to_vec();
318 let proof = prove(&private_key, &alpha).unwrap();
319 assert!(verify(&public_key, &alpha, &proof).is_some());
320 (public_key, alpha, proof)
321 }
322
323 #[test]
324 fn proves_and_verifies_like_draft_05() {
325 for [secret, input, gamma, c, s, beta] in DRAFT_05 {
326 let private_key = PrivateKey::from_bytes(&bytes(secret));
327 let public_key = PublicKey::from_private_key(&private_key);
328 let input = alpha(input);
329 let proof = prove(&private_key, &input).unwrap();
330 assert_eq!(
331 proof,
332 VrfProof {
333 gamma: bytes(gamma),
334 verification_hash: bytes(c),
335 scalar: bytes(s),
336 },
337 "{secret}"
338 );
339 let beta = ProofHash(bytes(beta));
340 assert_eq!(verify(&public_key, &input, &proof), Some(beta), "{secret}");
341 for checks in [
342 Checks::NONE,
343 Checks {
344 public_key: true,
345 gamma: false,
346 },
347 ] {
348 assert_eq!(
349 verify_with(&public_key, &input, &proof, checks),
350 Some(beta),
351 "{secret}"
352 );
353 }
354 assert_eq!(proof_hash(&proof.gamma), beta, "{secret}");
355 }
356 }
357
358 #[test]
359 fn generation_hash_is_the_first_half() {
360 let hash = ProofHash(core::array::from_fn(|index| index as u8));
361 assert_eq!(
362 hash.generation_hash(),
363 GenerationHash(core::array::from_fn(|index| index as u8))
364 );
365 }
366
367 #[test]
368 fn rejects_another_key_or_alpha() {
369 let (_, alpha, proof) = valid();
370 let other = PublicKey::from_private_key(&PrivateKey::from_bytes(&[8; 32]));
371 assert_eq!(verify(&other, &alpha, &proof), None);
372 let (public_key, _, proof) = valid();
373 assert_eq!(verify(&public_key, b"heika!", &proof), None);
374 }
375
376 #[test]
377 fn rejects_a_changed_verification_hash_or_scalar() {
378 let (public_key, alpha, mut proof) = valid();
379 proof.verification_hash[0] ^= 1;
380 assert_eq!(verify(&public_key, &alpha, &proof), None);
381 let (public_key, alpha, mut proof) = valid();
382 proof.scalar[0] ^= 1;
383 assert_eq!(verify(&public_key, &alpha, &proof), None);
384 }
385
386 #[test]
387 fn rejects_a_scalar_not_less_than_the_group_order() {
388 let (public_key, alpha, mut proof) = valid();
390 let order: [u8; 32] = [
391 0xED, 0xD3, 0xF5, 0x5C, 0x1A, 0x63, 0x12, 0x58, 0xD6, 0x9C, 0xF7, 0xA2, 0xDE, 0xF9,
392 0xDE, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10,
393 ];
394 let mut carry = 0;
395 for (byte, add) in proof.scalar.iter_mut().zip(order) {
396 let sum = u16::from(*byte) + u16::from(add) + carry;
397 *byte = sum as u8;
398 carry = sum >> 8;
399 }
400 assert_eq!(verify(&public_key, &alpha, &proof), None);
401 }
402
403 #[test]
404 fn rejects_a_gamma_off_the_curve() {
405 let (public_key, alpha, mut proof) = valid();
406 proof.gamma = (0..=u8::MAX)
407 .map(|low| {
408 let mut gamma = [0; 32];
409 gamma[0] = low;
410 gamma
411 })
412 .find(|gamma| decompress(gamma).is_none())
413 .unwrap();
414 assert_eq!(verify(&public_key, &alpha, &proof), None);
415 }
416
417 #[test]
418 fn rejects_a_gamma_outside_the_main_subgroup() {
419 let (public_key, alpha, mut proof) = valid();
421 let gamma = decompress(&proof.gamma).unwrap() + EIGHT_TORSION[4];
422 proof.gamma = gamma.compress().to_bytes();
423 assert!(ed25519::decode(&proof.gamma).is_none());
424 assert_eq!(verify(&public_key, &alpha, &proof), None);
425 }
426
427 #[test]
428 fn gamma_is_the_gamma_of_the_proof() {
429 let key = PrivateKey::from_bytes(&[7; 32]);
430 for alpha in [&b""[..], &[1; 32], &[0xFF; 64]] {
431 assert_eq!(
432 gamma(&key, alpha),
433 prove(&key, alpha).map(|proof| proof.gamma)
434 );
435 }
436 }
437
438 #[test]
439 fn proof_hash_ignores_the_small_order_part_of_gamma() {
440 let (_, _, proof) = valid();
442 let shifted = (decompress(&proof.gamma).unwrap() + EIGHT_TORSION[1])
443 .compress()
444 .to_bytes();
445 assert_eq!(proof_hash(&shifted), proof_hash(&proof.gamma));
446 }
447
448 #[test]
449 fn round_trips_a_generation_hash_through_hex() {
450 let hash = GenerationHash([0xAB; 32]);
451 assert_eq!(hash.to_string().parse(), Ok(hash));
452 }
453
454 #[test]
455 fn strict_check_rejects_keys_that_are_not_points() {
456 let private_key = PrivateKey::from_bytes(&[7; 32]);
457 let alpha = [0x5A; 32];
458 let proof = prove(&private_key, &alpha).unwrap();
459 let not_on_curve = (0u8..=255)
461 .map(|byte| [byte; 32])
462 .find(|bytes| ed25519::is_canonical(bytes) && decompress(bytes).is_none())
463 .unwrap();
464 for key in [[0; 32], [0xFF; 32], not_on_curve] {
465 assert!(ed25519::decode(&key).is_none());
466 assert_eq!(
467 verify_with(
468 &PublicKey(key),
469 &alpha,
470 &proof,
471 Checks {
472 public_key: true,
473 gamma: false,
474 },
475 ),
476 None
477 );
478 assert_eq!(verify(&PublicKey(key), &alpha, &proof), None);
479 }
480 }
481
482 #[test]
483 fn gamma_check_rejects_the_neutral_public_key() {
484 let neutral = PublicKey(IDENTITY);
486 let alpha = [0x5A; 32];
487 let h = map_to_point(&neutral.0, &alpha).unwrap();
488 let k = Scalar::from_bytes_mod_order([0x42; 32]);
489 let u = EdwardsPoint::mul_base(&k).compress().to_bytes();
490 let v = (k * decompress(&h).unwrap()).compress().to_bytes();
491 let proof = VrfProof {
492 gamma: IDENTITY,
493 verification_hash: challenge(&h, &IDENTITY, &u, &v),
494 scalar: k.to_bytes(),
495 };
496 assert!(ed25519::decode(&neutral.0).is_some());
498 for checks in [
499 Checks::NONE,
500 Checks {
501 public_key: true,
502 gamma: false,
503 },
504 ] {
505 assert!(verify_with(&neutral, &alpha, &proof, checks).is_some());
506 }
507 for checks in [
508 Checks::ALL,
509 Checks {
510 public_key: false,
511 gamma: true,
512 },
513 ] {
514 assert_eq!(verify_with(&neutral, &alpha, &proof, checks), None);
515 }
516 assert_eq!(verify(&neutral, &alpha, &proof), None);
517 }
518
519 #[test]
520 fn valid_public_keys_are_points_in_the_subgroup_other_than_the_neutral_one() {
521 let (public_key, _, _) = valid();
522 assert!(is_valid_public_key(&public_key));
523 let mut negative_neutral = IDENTITY;
524 negative_neutral[31] |= 0x80;
525 let outside = (decompress(&public_key.0).unwrap() + EIGHT_TORSION[4])
526 .compress()
527 .to_bytes();
528 for key in [IDENTITY, negative_neutral, [0; 32], [0xFF; 32], outside] {
529 assert!(!is_valid_public_key(&PublicKey(key)), "{key:02X?}");
530 }
531 }
532}