This repository has been archived by the owner on Nov 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathlib.rs
275 lines (230 loc) · 7.22 KB
/
lib.rs
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Copyright (c) DUSK NETWORK. All rights reserved.
mod error;
use crate::error::Error;
use dusk_plonk::bls12_381::BlsScalar as Scalar;
use dusk_plonk::jubjub::{
JubJubAffine as AffinePoint, JubJubExtended as ExtendedPoint, JubJubScalar as Fr,
GENERATOR_EXTENDED,
};
use poseidon252::perm_uses::fixed_hash::two_outputs;
use poseidon252::sponge::sponge::sponge_hash;
use rand::{CryptoRng, Rng};
use std::io;
use std::io::{Read, Write};
#[derive(Default, Clone, Copy, Debug)]
pub struct Message(pub Scalar);
/// An EdDSA secret key, consisting of two JubJub scalars.
#[derive(Clone, Copy, Debug)]
pub struct SecretKey {
p1: Fr,
p2: Fr,
}
impl SecretKey {
/// This will create a new [`SecretKey`] from a scalar
/// of the Field Fr.
pub fn new<T>(rand: &mut T) -> SecretKey
where
T: Rng + CryptoRng,
{
let scalar = Fr::random(rand);
let sk = two_outputs(scalar.into());
let p1 = Fr::from_raw(*sk[0].reduce().internal_repr());
let p2 = Fr::from_raw(*sk[1].reduce().internal_repr());
SecretKey { p1, p2 }
}
/// Returns the [`PublicKey`] of the [`SecretKey`].
pub fn to_public(&self) -> PublicKey {
let point = AffinePoint::from(GENERATOR_EXTENDED * &self.p1);
PublicKey(point)
}
/// Sign a [`Message`] with the [`SecretKey`], outputting a [`Signature`].
#[allow(non_snake_case)]
pub fn sign(&self, m: &Message) -> Signature {
let pk = PublicKey::from_secret(self);
let r = sponge_hash(&[self.p2.into(), m.0]);
let r_j = Fr::from_raw(*r.reduce().internal_repr());
let R = AffinePoint::from(GENERATOR_EXTENDED * r_j);
let h = sponge_hash(&[R.get_x(), R.get_y(), pk.0.get_x(), pk.0.get_y(), m.0]);
let h_j = Fr::from_raw(*h.reduce().internal_repr());
let h_pk = h_j * self.p1;
let s = h_pk + r_j;
Signature { s, R }
}
}
/// An EdDSA public key, internally represented by a point
/// on the JubJub curve.
#[derive(Clone, Copy, Debug)]
pub struct PublicKey(AffinePoint);
impl From<&SecretKey> for PublicKey {
fn from(sk: &SecretKey) -> Self {
PublicKey::from_secret(sk)
}
}
impl PublicKey {
/// This will create a new [`PublicKey`] from a [`SecretKey`].
pub fn from_secret(secret: &SecretKey) -> PublicKey {
let point = AffinePoint::from(GENERATOR_EXTENDED * secret.p1);
PublicKey(point)
}
/// This creates a new random [`PublicKey`].
/// Note that this function does not return the [`SecretKey`]
/// associated to this public key.
pub fn new<T>(rand: &mut T) -> Result<PublicKey, Error>
where
T: Rng + CryptoRng,
{
let sk = SecretKey::new(rand);
let pk = SecretKey::to_public(&sk);
Ok(pk)
}
}
/// A [`KeyPair`] contains both the [`SecretKey`] and the
/// associated [`PublicKey`].
#[derive(Clone, Copy, Debug)]
pub struct KeyPair {
pub secret_key: SecretKey,
pub public_key: PublicKey,
}
impl From<SecretKey> for KeyPair {
fn from(sk: SecretKey) -> Self {
KeyPair::new_from_secret(sk)
}
}
impl KeyPair {
// This function generates a new KeyPair
// from a secret and private key
pub fn new<T>(rand: &mut T) -> Result<Self, Error>
where
T: Rng + CryptoRng,
{
let sk = SecretKey::new(rand);
let pk = SecretKey::to_public(&sk);
Ok(KeyPair {
secret_key: sk,
public_key: pk,
})
}
pub fn new_from_secret(sk: SecretKey) -> Self {
let pk = SecretKey::to_public(&sk);
KeyPair {
secret_key: sk,
public_key: pk,
}
}
pub fn sign(&self, m: &Message) -> Signature {
self.secret_key.sign(m)
}
}
/// An EdDSA signature, produced by signing a [`Message`] with a
/// [`SecretKey`].
#[allow(non_snake_case)]
#[derive(Clone, Copy, Debug)]
pub struct Signature {
s: Fr,
R: AffinePoint,
}
impl Signature {
/// Verify the correctness of a [`Signature`], given a [`Message`]
/// and a [`PublicKey`].
pub fn verify(&self, m: &Message, pk: &PublicKey) -> Result<(), Error> {
let h = sponge_hash(&[
self.R.get_x(),
self.R.get_y(),
pk.0.get_x(),
pk.0.get_y(),
m.0,
]);
let h_j = Fr::from_raw(*h.reduce().internal_repr());
let p1 = GENERATOR_EXTENDED * self.s;
let h_pk = AffinePoint::from(ExtendedPoint::from(pk.0) * h_j);
let p2 = ExtendedPoint::from(self.R) + ExtendedPoint::from(h_pk);
match p1.eq(&p2) {
true => Ok(()),
false => Err(Error::InvalidSignature),
}
}
pub fn to_bytes(&self) -> [u8; 64] {
let mut buf = [0u8; 64];
buf[0..32].copy_from_slice(&self.s.to_bytes());
buf[32..].copy_from_slice(&self.R.to_bytes());
buf
}
#[allow(non_snake_case)]
pub fn from_bytes(buf: [u8; 64]) -> Result<Signature, Error> {
let mut s_buf = [0u8; 32];
s_buf.copy_from_slice(&buf[..32]);
let mut R_buf = [0u8; 32];
R_buf.copy_from_slice(&buf[32..]);
let s = Fr::from_bytes(&s_buf);
if s.is_none().unwrap_u8() == 1 {
return Err(Error::InvalidData);
}
let R = AffinePoint::from_bytes(R_buf);
if R.is_none().unwrap_u8() == 1 {
return Err(Error::InvalidData);
}
let sig = Signature {
s: s.unwrap(),
R: R.unwrap(),
};
Ok(sig)
}
}
impl Read for Signature {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let mut n = 0;
buf.chunks_mut(32)
.next()
.ok_or(Error::Generic)
.map_err::<io::Error, _>(|e| e.into())?;
n += 32;
buf.copy_from_slice(&self.s.to_bytes());
buf.chunks_mut(32)
.next()
.ok_or(Error::Generic)
.map_err::<io::Error, _>(|e| e.into())?;
n += 32;
buf.copy_from_slice(&self.R.to_bytes());
Ok(n)
}
}
#[allow(non_snake_case)]
impl Write for Signature {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let mut n = 0;
let s_buf = buf
.chunks(32)
.next()
.ok_or(Error::Generic)
.map_err::<io::Error, _>(|e| e.into())?;
n += 32;
let mut s_arr = [0u8; 32];
s_arr.copy_from_slice(&s_buf);
let s = Fr::from_bytes(&s_arr);
if s.is_none().unwrap_u8() == 1 {
return Err(Error::Generic.into());
}
let R_buf = buf
.chunks(32)
.next()
.ok_or(Error::Generic)
.map_err::<io::Error, _>(|e| e.into())?;
n += 32;
let mut R_arr = [0u8; 32];
R_arr.copy_from_slice(&R_buf);
let R = AffinePoint::from_bytes(R_arr);
if R.is_none().unwrap_u8() == 1 {
return Err(Error::Generic.into());
}
self.s = s.unwrap();
self.R = R.unwrap();
Ok(n)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}