-
Notifications
You must be signed in to change notification settings - Fork 100
Expand file tree
/
Copy pathcrypto.rs
More file actions
378 lines (340 loc) · 12.3 KB
/
crypto.rs
File metadata and controls
378 lines (340 loc) · 12.3 KB
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
//! Crypto contains functions for cryptographic functions.
use crate::{
env::internal::{self, BytesObject},
unwrap::UnwrapInfallible,
Bytes, BytesN, ConversionError, Env, IntoVal, Symbol, TryFromVal, TryIntoVal, Val, Vec, U256,
};
pub mod bls12_381;
pub mod bn254;
pub(crate) mod poseidon2_params;
pub mod poseidon2_sponge;
pub(crate) mod poseidon_params;
pub mod poseidon_sponge;
pub(crate) mod utils;
pub use bn254::Fr as BnScalar;
pub use poseidon2_sponge::{Poseidon2Config, Poseidon2Sponge};
pub use poseidon_sponge::{PoseidonConfig, PoseidonSponge};
/// A `BytesN<N>` generated by a cryptographic hash function.
///
/// The `Hash<N>` type contains a `BytesN<N>` and can only be constructed in
/// contexts where the value has been generated by a secure cryptographic
/// function. As a result, the type is only found as a return value of calling
/// [`sha256`][Crypto::sha256], [`keccak256`][Crypto::keccak256], or via
/// implementing [`CustomAccountInterface`][crate::auth::CustomAccountInterface]
/// since the `__check_auth` is guaranteed to receive a hash from a secure
/// cryptographic hash function as its first parameter.
///
/// **__Note:_** A Hash should not be used with storage, since no guarantee can
/// be made about the Bytes stored as to whether they were in fact from a secure
/// cryptographic hash function.
#[derive(Clone)]
#[repr(transparent)]
pub struct Hash<const N: usize>(BytesN<N>);
impl<const N: usize> Hash<N> {
/// Constructs a new `Hash` from a fixed-length bytes array.
///
/// This is intended for test-only, since `Hash` type is only meant to be
/// constructed via secure manners.
#[cfg(test)]
pub(crate) fn from_bytes(bytes: BytesN<N>) -> Self {
Self(bytes)
}
/// Returns a [`BytesN`] containing the bytes in this hash.
#[inline(always)]
pub fn to_bytes(&self) -> BytesN<N> {
self.0.clone()
}
/// Returns an array containing the bytes in this hash.
#[inline(always)]
pub fn to_array(&self) -> [u8; N] {
self.0.to_array()
}
pub fn as_val(&self) -> &Val {
self.0.as_val()
}
pub fn to_val(&self) -> Val {
self.0.to_val()
}
pub fn as_object(&self) -> &BytesObject {
self.0.as_object()
}
pub fn to_object(&self) -> BytesObject {
self.0.to_object()
}
}
impl<const N: usize> IntoVal<Env, Val> for Hash<N> {
fn into_val(&self, e: &Env) -> Val {
self.0.into_val(e)
}
}
impl<const N: usize> IntoVal<Env, BytesN<N>> for Hash<N> {
fn into_val(&self, _e: &Env) -> BytesN<N> {
self.0.clone()
}
}
impl<const N: usize> From<Hash<N>> for Bytes {
fn from(v: Hash<N>) -> Self {
v.0.into()
}
}
impl<const N: usize> From<Hash<N>> for BytesN<N> {
fn from(v: Hash<N>) -> Self {
v.0
}
}
impl<const N: usize> Into<[u8; N]> for Hash<N> {
fn into(self) -> [u8; N] {
self.0.into()
}
}
#[allow(deprecated)]
impl<const N: usize> crate::TryFromValForContractFn<Env, Val> for Hash<N> {
type Error = ConversionError;
fn try_from_val_for_contract_fn(env: &Env, v: &Val) -> Result<Self, Self::Error> {
Ok(Hash(BytesN::<N>::try_from_val(env, v)?))
}
}
/// Crypto provides access to cryptographic functions.
pub struct Crypto {
env: Env,
}
impl Crypto {
pub(crate) fn new(env: &Env) -> Crypto {
Crypto { env: env.clone() }
}
pub fn env(&self) -> &Env {
&self.env
}
/// Returns the SHA-256 hash of the data.
pub fn sha256(&self, data: &Bytes) -> Hash<32> {
let env = self.env();
let bin = internal::Env::compute_hash_sha256(env, data.into()).unwrap_infallible();
unsafe { Hash(BytesN::unchecked_new(env.clone(), bin)) }
}
/// Returns the Keccak-256 hash of the data.
pub fn keccak256(&self, data: &Bytes) -> Hash<32> {
let env = self.env();
let bin = internal::Env::compute_hash_keccak256(env, data.into()).unwrap_infallible();
unsafe { Hash(BytesN::unchecked_new(env.clone(), bin)) }
}
/// Verifies an ed25519 signature.
///
/// The signature is verified as a valid signature of the message by the
/// ed25519 public key.
///
/// ### Panics
///
/// If the signature verification fails.
pub fn ed25519_verify(&self, public_key: &BytesN<32>, message: &Bytes, signature: &BytesN<64>) {
let env = self.env();
let _ = internal::Env::verify_sig_ed25519(
env,
public_key.to_object(),
message.to_object(),
signature.to_object(),
);
}
/// Recovers the ECDSA secp256k1 public key.
///
/// The public key returned is the SEC-1-encoded ECDSA secp256k1 public key
/// that produced the 64-byte signature over a given 32-byte message digest,
/// for a given recovery_id byte.
pub fn secp256k1_recover(
&self,
message_digest: &Hash<32>,
signature: &BytesN<64>,
recorvery_id: u32,
) -> BytesN<65> {
let env = self.env();
CryptoHazmat::new(env).secp256k1_recover(&message_digest.0, signature, recorvery_id)
}
/// Verifies the ECDSA secp256r1 signature.
///
/// The SEC-1-encoded public key is provided along with the message,
/// verifies the 64-byte signature.
pub fn secp256r1_verify(
&self,
public_key: &BytesN<65>,
message_digest: &Hash<32>,
signature: &BytesN<64>,
) {
let env = self.env();
CryptoHazmat::new(env).secp256r1_verify(public_key, &message_digest.0, signature)
}
/// Get a [Bls12_381][bls12_381::Bls12_381] for accessing the bls12-381
/// functions.
pub fn bls12_381(&self) -> bls12_381::Bls12_381 {
bls12_381::Bls12_381::new(self.env())
}
/// Get a [Bn254][bn254::Bn254] for accessing the bn254
/// functions.
pub fn bn254(&self) -> bn254::Bn254 {
bn254::Bn254::new(self.env())
}
/// Computes a Poseidon hash matching circom's
/// [implementation](https://github.com/iden3/circomlib/blob/35e54ea21da3e8762557234298dbb553c175ea8d/circuits/poseidon.circom)
/// for input lengths up to 5 (`t ≤ 6`).
///
/// Internally it picks the state size `t` to match the input length, i.e.
/// `t = N + 1` (rate = N, capacity = 1). For example, hashing 2 elements
/// uses t=3.
///
/// Note: use [`poseidon_sponge::hash`] with a pre-constructed
/// [`PoseidonConfig`] directly if:
/// - You want to repeatedly hash with the same input size. Pre-constructing
/// the config saves the cost of re-initialization.
/// - You want to hash larger input sizes. The sponge will repeatedly
/// permute and absorb until the entire input is consumed. This is a valid
/// (and secure) sponge operation, even though it may not match circom's
/// output, which always picks a larger state size (N+1) to hash inputs in
/// one shot (up to t=17). If you need parameter support for larger `t`,
/// please file an issue.
pub fn poseidon_hash(&self, field_type: Symbol, inputs: &Vec<U256>) -> U256 {
let config = PoseidonConfig::new(&self.env, field_type, inputs.len() as u32);
poseidon_sponge::hash(&self.env, inputs, config)
}
/// Computes a Poseidon2 hash matching noir's
/// [implementation](https://github.com/noir-lang/noir/blob/abfee1f54b20984172ba23482f4af160395cfba5/noir_stdlib/src/hash/poseidon2.nr).
///
/// Internally it always initializes the state with `t = 4`, regardless of
/// input length. It alternates between absorbing and permuting until all
/// input elements are consumed.
///
/// Note: use [`poseidon2_sponge::hash`] with a pre-constructed
/// [`Poseidon2Config`] directly if:
/// - You need to hash multiple times. Pre-constructing the config saves the
/// cost of re-initialization.
/// - You want to use a different state size (`t ≤ 4`).
pub fn poseidon2_hash(&self, field_type: Symbol, inputs: &Vec<U256>) -> U256 {
const INTERNAL_RATE: u32 = 3;
let config = Poseidon2Config::new(&self.env, field_type, INTERNAL_RATE);
poseidon2_sponge::hash(&self.env, inputs, config)
}
}
/// # ⚠️ Hazardous Materials
///
/// Cryptographic functions under [CryptoHazmat] are low-leveled which can be
/// insecure if misused. They are not generally recommended. Using them
/// incorrectly can introduce security vulnerabilities. Please use [Crypto] if
/// possible.
#[cfg_attr(any(test, feature = "hazmat-crypto"), visibility::make(pub))]
#[cfg_attr(feature = "docs", doc(cfg(feature = "hazmat-crypto")))]
pub(crate) struct CryptoHazmat {
env: Env,
}
impl CryptoHazmat {
pub(crate) fn new(env: &Env) -> CryptoHazmat {
CryptoHazmat { env: env.clone() }
}
pub fn env(&self) -> &Env {
&self.env
}
/// Recovers the ECDSA secp256k1 public key.
///
/// The public key returned is the SEC-1-encoded ECDSA secp256k1 public key
/// that produced the 64-byte signature over a given 32-byte message digest,
/// for a given recovery_id byte.
///
/// WARNING: The `message_digest` must be produced by a secure cryptographic
/// hash function on the message, otherwise the attacker can potentially
/// forge signatures.
pub fn secp256k1_recover(
&self,
message_digest: &BytesN<32>,
signature: &BytesN<64>,
recorvery_id: u32,
) -> BytesN<65> {
let env = self.env();
let bytes = internal::Env::recover_key_ecdsa_secp256k1(
env,
message_digest.to_object(),
signature.to_object(),
recorvery_id.into(),
)
.unwrap_infallible();
unsafe { BytesN::unchecked_new(env.clone(), bytes) }
}
/// Verifies the ECDSA secp256r1 signature.
///
/// The SEC-1-encoded public key is provided along with a 32-byte message
/// digest, verifies the 64-byte signature.
///
/// WARNING: The `message_digest` must be produced by a secure cryptographic
/// hash function on the message, otherwise the attacker can potentially
/// forge signatures.
pub fn secp256r1_verify(
&self,
public_key: &BytesN<65>,
message_digest: &BytesN<32>,
signature: &BytesN<64>,
) {
let env = self.env();
let _ = internal::Env::verify_sig_ecdsa_secp256r1(
env,
public_key.to_object(),
message_digest.to_object(),
signature.to_object(),
)
.unwrap_infallible();
}
/// Performs a Poseidon permutation on the input state vector.
///
/// WARNING: This is a low-level permutation function. Most users should use
/// the higher-level `poseidon_hash` function instead.
pub fn poseidon_permutation(
&self,
input: &Vec<U256>,
field: Symbol,
t: u32,
d: u32,
rounds_f: u32,
rounds_p: u32,
mds: &Vec<Vec<U256>>,
round_constants: &Vec<Vec<U256>>,
) -> Vec<U256> {
let env = self.env();
let result = internal::Env::poseidon_permutation(
env,
input.to_object(),
field.to_symbol_val(),
t.into(),
d.into(),
rounds_f.into(),
rounds_p.into(),
mds.to_object(),
round_constants.to_object(),
)
.unwrap_infallible();
result.try_into_val(env).unwrap_infallible()
}
/// Performs a Poseidon2 permutation on the input state vector.
///
/// WARNING: This is a low-level permutation function. Most users should use
/// the higher-level `poseidon2_hash` function instead.
pub fn poseidon2_permutation(
&self,
input: &Vec<U256>,
field: Symbol,
t: u32,
d: u32,
rounds_f: u32,
rounds_p: u32,
mat_internal_diag_m_1: &Vec<U256>,
round_constants: &Vec<Vec<U256>>,
) -> Vec<U256> {
let env = self.env();
let result = internal::Env::poseidon2_permutation(
env,
input.to_object(),
field.to_symbol_val(),
t.into(),
d.into(),
rounds_f.into(),
rounds_p.into(),
mat_internal_diag_m_1.to_object(),
round_constants.to_object(),
)
.unwrap_infallible();
result.try_into_val(env).unwrap_infallible()
}
}