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
use p256k1::{
    point::{Point, G},
    scalar::Scalar,
};
use rand_core::{CryptoRng, OsRng, RngCore};
use sha3::{Digest, Sha3_256};

fn hash_to_scalar(hasher: &mut Sha3_256) -> Scalar {
    let h = hasher.clone();
    let hash = h.finalize();
    let mut hash_bytes: [u8; 32] = [0; 32];
    hash_bytes.clone_from_slice(hash.as_slice());

    Scalar::from(hash_bytes)
}

#[allow(non_snake_case)]
struct SchnorrProof {
    X: Point,
    r: Scalar,
    V: Point,
}

impl SchnorrProof {
    #[allow(non_snake_case)]
    pub fn new<T: RngCore + CryptoRng>(x: &Scalar, rng: &mut T) -> Self {
        let X = Point::from(x);
        let v = Scalar::random(rng);
        let V = Point::from(&v);
        let mut hasher = Sha3_256::new();

        hasher.update(G.compress().as_bytes());
        hasher.update(X.compress().as_bytes());
        hasher.update(V.compress().as_bytes());

        let c = hash_to_scalar(&mut hasher);
        let r = v - &c * x;

        SchnorrProof { X, r, V }
    }

    #[allow(non_snake_case)]
    pub fn verify(&self) -> bool {
        let mut hasher = Sha3_256::new();

        hasher.update(G.compress().as_bytes());
        hasher.update(self.X.compress().as_bytes());
        hasher.update(self.V.compress().as_bytes());

        let c = hash_to_scalar(&mut hasher);

        self.V == &self.r * &G + &c * &self.X
    }
}

#[allow(non_snake_case)]
fn main() {
    let mut rng = OsRng::default();
    let x = Scalar::random(&mut rng);
    let proof = SchnorrProof::new(&x, &mut rng);
    println!("SchnorrProof verify {}", proof.verify());
}