1#[cfg(not(feature = "std"))]
2use alloc::{
3 string::{String, ToString},
4 vec,
5 vec::Vec,
6};
7
8use ethereum_types::Address;
9use sha2::Digest as _;
10
11#[derive(Debug, thiserror::Error)]
13pub enum CryptoError {
14 #[error("invalid signature")]
15 InvalidSignature,
16 #[error("invalid recovery id")]
17 InvalidRecoveryId,
18 #[error("recovery failed")]
19 RecoveryFailed,
20 #[error("invalid point: {0}")]
21 InvalidPoint(&'static str),
22 #[error("invalid input: {0}")]
23 InvalidInput(&'static str),
24 #[error("verification failed")]
25 VerificationFailed,
26 #[error("unsupported: {0}")]
27 Unsupported(&'static str),
28 #[error("{0}")]
29 Other(String),
30}
31
32#[cfg(not(feature = "blst"))]
37const BLS_UNSUPPORTED: &str =
38 "bls12_381 requires the `blst` feature (host/L1) or a zkVM provider override";
39
40pub trait Crypto: Send + Sync + core::fmt::Debug {
71 #[cfg(feature = "secp256k1")]
77 fn secp256k1_ecrecover(
78 &self,
79 sig: &[u8; 64],
80 recid: u8,
81 msg: &[u8; 32],
82 ) -> Result<[u8; 32], CryptoError> {
83 let recovery_id = secp256k1::ecdsa::RecoveryId::try_from(recid as i32)
84 .map_err(|_| CryptoError::InvalidRecoveryId)?;
85
86 let recoverable_sig =
87 secp256k1::ecdsa::RecoverableSignature::from_compact(sig, recovery_id)
88 .map_err(|_| CryptoError::InvalidSignature)?;
89
90 let message = secp256k1::Message::from_digest(*msg);
91
92 let public_key = recoverable_sig
93 .recover(&message)
94 .map_err(|_| CryptoError::RecoveryFailed)?;
95
96 let hash = crate::keccak::keccak_hash(&public_key.serialize_uncompressed()[1..]);
97 Ok(hash)
98 }
99
100 #[cfg(not(feature = "secp256k1"))]
101 fn secp256k1_ecrecover(
102 &self,
103 sig: &[u8; 64],
104 recid: u8,
105 msg: &[u8; 32],
106 ) -> Result<[u8; 32], CryptoError> {
107 use k256::{
108 AffinePoint, ProjectivePoint, Scalar,
109 elliptic_curve::{
110 PrimeField,
111 group::prime::PrimeCurveAffine,
112 ops::{Invert, LinearCombination, Reduce},
113 point::DecompressPoint,
114 sec1::ToEncodedPoint,
115 },
116 };
117
118 let r_bytes = k256::FieldBytes::from_slice(&sig[..32]);
120 let s_bytes = k256::FieldBytes::from_slice(&sig[32..]);
121 let r: Option<Scalar> = Scalar::from_repr(*r_bytes).into();
122 let s: Option<Scalar> = Scalar::from_repr(*s_bytes).into();
123
124 let (Some(r), Some(s)) = (r, s) else {
125 return Err(CryptoError::InvalidSignature);
126 };
127
128 if r.is_zero().into() || s.is_zero().into() {
129 return Err(CryptoError::InvalidSignature);
130 }
131
132 let y_is_odd = (recid & 1) != 0;
137 let r_point: Option<AffinePoint> =
138 AffinePoint::decompress(r_bytes, u8::from(y_is_odd).into()).into();
139 let Some(r_point) = r_point else {
140 return Err(CryptoError::RecoveryFailed);
141 };
142
143 let r_proj = ProjectivePoint::from(r_point);
145 let z = <Scalar as Reduce<k256::U256>>::reduce_bytes(k256::FieldBytes::from_slice(msg));
146 let r_inv: Option<Scalar> = r.invert_vartime().into();
147 let Some(r_inv) = r_inv else {
148 return Err(CryptoError::RecoveryFailed);
149 };
150 let u1 = -(r_inv * z);
151 let u2 = r_inv * s;
152 let pk = ProjectivePoint::lincomb(&ProjectivePoint::GENERATOR, &u1, &r_proj, &u2);
153
154 let pk_affine = pk.to_affine();
155 if bool::from(pk_affine.is_identity()) {
156 return Err(CryptoError::RecoveryFailed);
157 }
158 let uncompressed = pk_affine.to_encoded_point(false);
159 let hash = crate::keccak::keccak_hash(&uncompressed.as_bytes()[1..]);
160 Ok(hash)
161 }
162
163 fn recover_signer(&self, sig: &[u8; 65], msg: &[u8; 32]) -> Result<Address, CryptoError> {
166 const SECP256K1_N_HALF: [u8; 32] =
168 hex_literal::hex!("7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0");
169 if sig[32..64] > SECP256K1_N_HALF[..] {
170 return Err(CryptoError::InvalidSignature);
171 }
172
173 let hash = self.secp256k1_ecrecover(
174 sig[..64]
175 .try_into()
176 .map_err(|_| CryptoError::InvalidSignature)?,
177 sig[64],
178 msg,
179 )?;
180 Ok(Address::from_slice(&hash[12..]))
181 }
182
183 fn keccak256(&self, input: &[u8]) -> [u8; 32] {
187 crate::keccak::keccak_hash(input)
188 }
189
190 fn sha256(&self, input: &[u8]) -> [u8; 32] {
192 sha2::Sha256::digest(input).into()
193 }
194
195 fn ripemd160(&self, input: &[u8]) -> [u8; 32] {
197 let mut hasher = ripemd::Ripemd160::new();
198 hasher.update(input);
199 let result = hasher.finalize();
200
201 let mut output = [0u8; 32];
202 output[12..].copy_from_slice(&result);
203 output
204 }
205
206 fn bn254_g1_add(&self, p1: &[u8], p2: &[u8]) -> Result<[u8; 64], CryptoError> {
214 use ark_bn254::Fq;
215 use ark_ec::CurveGroup;
216 use ark_ff::{BigInteger, PrimeField as _, Zero};
217
218 let parse_point = |bytes: &[u8]| -> Result<ark_bn254::G1Affine, CryptoError> {
219 if bytes.len() < 64 {
220 return Err(CryptoError::InvalidInput("G1 point must be 64 bytes"));
221 }
222 let x = Fq::from_be_bytes_mod_order(&bytes[..32]);
223 let y = Fq::from_be_bytes_mod_order(&bytes[32..64]);
224
225 if x.is_zero() && y.is_zero() {
226 return Ok(ark_bn254::G1Affine::identity());
227 }
228
229 let point = ark_bn254::G1Affine::new_unchecked(x, y);
230 if !point.is_on_curve() {
231 return Err(CryptoError::InvalidPoint("G1 point not on curve"));
232 }
233 Ok(point)
234 };
235
236 let pt1 = parse_point(p1)?;
237 let pt2 = parse_point(p2)?;
238
239 #[allow(clippy::arithmetic_side_effects)]
240 let sum = (pt1 + pt2).into_affine();
241
242 let mut out = [0u8; 64];
243 out[..32].copy_from_slice(&sum.x.into_bigint().to_bytes_be());
244 out[32..].copy_from_slice(&sum.y.into_bigint().to_bytes_be());
245 Ok(out)
246 }
247
248 fn bn254_g1_mul(&self, point: &[u8], scalar: &[u8]) -> Result<[u8; 64], CryptoError> {
254 use ark_bn254::{Fq, Fr as FrArk};
255 use ark_ec::CurveGroup;
256 use ark_ff::{BigInteger, PrimeField as _, Zero};
257 use core::ops::Mul as _;
258
259 if point.len() < 64 || scalar.len() < 32 {
260 return Err(CryptoError::InvalidInput("invalid input length"));
261 }
262
263 let x = Fq::from_be_bytes_mod_order(&point[..32]);
264 let y = Fq::from_be_bytes_mod_order(&point[32..64]);
265
266 if x.is_zero() && y.is_zero() {
267 return Ok([0u8; 64]);
268 }
269
270 let pt = ark_bn254::G1Affine::new_unchecked(x, y);
271 if !pt.is_on_curve() {
272 return Err(CryptoError::InvalidPoint("G1 point not on curve"));
273 }
274
275 let s = FrArk::from_be_bytes_mod_order(scalar);
276 if s.is_zero() {
277 return Ok([0u8; 64]);
278 }
279
280 let result = pt.mul(s).into_affine();
281
282 let mut out = [0u8; 64];
283 out[..32].copy_from_slice(&result.x.into_bigint().to_bytes_be());
284 out[32..].copy_from_slice(&result.y.into_bigint().to_bytes_be());
285 Ok(out)
286 }
287
288 fn bn254_pairing_check(&self, pairs: &[(&[u8], &[u8])]) -> Result<bool, CryptoError> {
294 use ark_bn254::{Bn254, Fq, G1Affine, G2Affine};
295 use ark_ec::pairing::Pairing;
296 use ark_ff::{One, PrimeField as _, QuadExtField, Zero};
297
298 let mut g1_points = Vec::with_capacity(pairs.len());
299 let mut g2_points = Vec::with_capacity(pairs.len());
300
301 for (g1_bytes, g2_bytes) in pairs {
302 if g1_bytes.len() < 64 {
303 return Err(CryptoError::InvalidInput("G1 must be 64 bytes"));
304 }
305 let g1x = Fq::from_be_bytes_mod_order(&g1_bytes[..32]);
306 let g1y = Fq::from_be_bytes_mod_order(&g1_bytes[32..64]);
307
308 let g1 = if g1x.is_zero() && g1y.is_zero() {
309 G1Affine::identity()
310 } else {
311 let p = G1Affine::new_unchecked(g1x, g1y);
312 if !p.is_on_curve() || !p.is_in_correct_subgroup_assuming_on_curve() {
313 return Err(CryptoError::InvalidPoint("G1 not on BN254 curve"));
314 }
315 p
316 };
317 g1_points.push(g1);
318
319 if g2_bytes.len() < 128 {
320 return Err(CryptoError::InvalidInput("G2 must be 128 bytes"));
321 }
322
323 let g2_x_im = Fq::from_be_bytes_mod_order(&g2_bytes[..32]);
324 let g2_x_re = Fq::from_be_bytes_mod_order(&g2_bytes[32..64]);
325 let g2_y_im = Fq::from_be_bytes_mod_order(&g2_bytes[64..96]);
326 let g2_y_re = Fq::from_be_bytes_mod_order(&g2_bytes[96..128]);
327
328 let g2 =
329 if g2_x_im.is_zero() && g2_x_re.is_zero() && g2_y_im.is_zero() && g2_y_re.is_zero()
330 {
331 G2Affine::identity()
332 } else {
333 let p = G2Affine::new_unchecked(
334 QuadExtField::new(g2_x_re, g2_x_im),
335 QuadExtField::new(g2_y_re, g2_y_im),
336 );
337 if !p.is_on_curve() || !p.is_in_correct_subgroup_assuming_on_curve() {
338 return Err(CryptoError::InvalidPoint("G2 not on BN254 curve"));
339 }
340 p
341 };
342 g2_points.push(g2);
343 }
344
345 Ok(Bn254::multi_pairing(g1_points, g2_points).0 == QuadExtField::one())
346 }
347
348 #[cfg(feature = "std")]
353 fn modexp(&self, base: &[u8], exp: &[u8], modulus: &[u8]) -> Result<Vec<u8>, CryptoError> {
354 modexp_arbitrary_precision(base, exp, modulus)
355 }
356
357 #[cfg(not(feature = "std"))]
358 fn modexp(&self, base: &[u8], exp: &[u8], modulus: &[u8]) -> Result<Vec<u8>, CryptoError> {
359 use num_bigint::BigUint;
360
361 let base_nat = BigUint::from_bytes_be(base);
362 let exp_nat = BigUint::from_bytes_be(exp);
363 let mod_nat = BigUint::from_bytes_be(modulus);
364
365 let result = if mod_nat == BigUint::ZERO {
366 BigUint::ZERO
367 } else if exp_nat == BigUint::ZERO {
368 BigUint::from(1_u8) % &mod_nat
369 } else {
370 base_nat.modpow(&exp_nat, &mod_nat)
371 };
372
373 let res_bytes = result.to_bytes_be();
374 pad_modexp_output(res_bytes, modulus.len())
375 }
376
377 fn mulmod256(&self, a: &[u8; 32], b: &[u8; 32], m: &[u8; 32]) -> [u8; 32] {
382 let a = ethereum_types::U256::from_big_endian(a);
383 let b = ethereum_types::U256::from_big_endian(b);
384 let m = ethereum_types::U256::from_big_endian(m);
385
386 crate::u256_div::mul_mod(a, b, m).to_big_endian()
387 }
388
389 fn blake2_compress(&self, rounds: u32, h: &mut [u64; 8], m: [u64; 16], t: [u64; 2], f: bool) {
393 #[allow(clippy::as_conversions)]
394 crate::blake2f::blake2b_f(rounds as usize, h, &m, &t, f);
395 }
396
397 fn secp256r1_verify(&self, msg: &[u8; 32], sig: &[u8; 64], pk: &[u8; 64]) -> bool {
401 use p256::{
402 EncodedPoint,
403 ecdsa::{Signature as P256Signature, signature::hazmat::PrehashVerifier},
404 elliptic_curve::bigint::U256 as P256Uint,
405 };
406
407 let r = P256Uint::from_be_slice(&sig[..32]);
408 let s = P256Uint::from_be_slice(&sig[32..]);
409
410 const P256_N: P256Uint = P256Uint::from_be_hex(
411 "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551",
412 );
413
414 if r == P256Uint::ZERO || r >= P256_N || s == P256Uint::ZERO || s >= P256_N {
415 return false;
416 }
417
418 let x_bytes: &[u8; 32] = match pk[..32].try_into() {
419 Ok(b) => b,
420 Err(_) => return false,
421 };
422 let y_bytes: &[u8; 32] = match pk[32..].try_into() {
423 Ok(b) => b,
424 Err(_) => return false,
425 };
426
427 let Ok(verifier) = p256::ecdsa::VerifyingKey::from_encoded_point(
428 &EncodedPoint::from_affine_coordinates(x_bytes.into(), y_bytes.into(), false),
429 ) else {
430 return false;
431 };
432
433 let r_arr: [u8; 32] = sig[..32].try_into().unwrap_or([0u8; 32]);
434 let s_arr: [u8; 32] = sig[32..].try_into().unwrap_or([0u8; 32]);
435
436 let Ok(signature) = P256Signature::from_scalars(r_arr, s_arr) else {
437 return false;
438 };
439
440 verifier.verify_prehash(msg, &signature).is_ok()
441 }
442
443 #[cfg(feature = "c-kzg")]
447 fn verify_kzg_proof(
448 &self,
449 z: &[u8; 32],
450 y: &[u8; 32],
451 commitment: &[u8; 48],
452 proof: &[u8; 48],
453 ) -> Result<(), CryptoError> {
454 let c_kzg_settings = c_kzg::ethereum_kzg_settings(crate::kzg::KZG_PRECOMPUTE);
455 c_kzg_settings
456 .verify_kzg_proof(
457 &(*commitment).into(),
458 &(*z).into(),
459 &(*y).into(),
460 &(*proof).into(),
461 )
462 .map_err(|e| CryptoError::Other(e.to_string()))
463 .and_then(|valid| {
464 if valid {
465 Ok(())
466 } else {
467 Err(CryptoError::VerificationFailed)
468 }
469 })
470 }
471
472 #[cfg(not(feature = "c-kzg"))]
473 fn verify_kzg_proof(
474 &self,
475 z: &[u8; 32],
476 y: &[u8; 32],
477 commitment: &[u8; 48],
478 proof: &[u8; 48],
479 ) -> Result<(), CryptoError> {
480 crate::kzg::verify_kzg_proof(*commitment, *z, *y, *proof)
481 .map_err(|e| CryptoError::Other(e.to_string()))
482 .and_then(|valid| {
483 if valid {
484 Ok(())
485 } else {
486 Err(CryptoError::VerificationFailed)
487 }
488 })
489 }
490
491 #[cfg(feature = "c-kzg")]
493 fn verify_blob_kzg_proof(
494 &self,
495 blob: &[u8],
496 commitment: &[u8; 48],
497 proof: &[u8; 48],
498 ) -> Result<bool, CryptoError> {
499 use crate::kzg::BYTES_PER_BLOB;
500
501 let blob_arr: [u8; BYTES_PER_BLOB] = blob
502 .try_into()
503 .map_err(|_| CryptoError::InvalidInput("blob must be 131072 bytes"))?;
504
505 let c_kzg_settings = c_kzg::ethereum_kzg_settings(crate::kzg::KZG_PRECOMPUTE);
506 c_kzg_settings
507 .verify_blob_kzg_proof(&blob_arr.into(), &(*commitment).into(), &(*proof).into())
508 .map_err(|e| CryptoError::Other(e.to_string()))
509 }
510
511 #[cfg(not(feature = "c-kzg"))]
512 fn verify_blob_kzg_proof(
513 &self,
514 blob: &[u8],
515 commitment: &[u8; 48],
516 proof: &[u8; 48],
517 ) -> Result<bool, CryptoError> {
518 use crate::kzg::BYTES_PER_BLOB;
519
520 let blob_arr: [u8; BYTES_PER_BLOB] = blob
521 .try_into()
522 .map_err(|_| CryptoError::InvalidInput("blob must be 131072 bytes"))?;
523
524 crate::kzg::verify_blob_kzg_proof(blob_arr, *commitment, *proof)
525 .map_err(|e| CryptoError::Other(e.to_string()))
526 }
527
528 fn bls12_381_g1_add(
540 &self,
541 a: ([u8; 48], [u8; 48]),
542 b: ([u8; 48], [u8; 48]),
543 ) -> Result<[u8; 96], CryptoError> {
544 #[cfg(feature = "blst")]
545 {
546 crate::bls_blst::g1_add(a, b)
547 }
548 #[cfg(not(feature = "blst"))]
549 {
550 let _ = (a, b);
551 Err(CryptoError::Unsupported(BLS_UNSUPPORTED))
552 }
553 }
554
555 #[allow(clippy::type_complexity)]
557 fn bls12_381_g1_msm(
558 &self,
559 pairs: &[(([u8; 48], [u8; 48]), [u8; 32])],
560 ) -> Result<[u8; 96], CryptoError> {
561 #[cfg(feature = "blst")]
562 {
563 crate::bls_blst::g1_msm(pairs)
564 }
565 #[cfg(not(feature = "blst"))]
566 {
567 let _ = pairs;
568 Err(CryptoError::Unsupported(BLS_UNSUPPORTED))
569 }
570 }
571
572 fn bls12_381_g2_add(
574 &self,
575 a: ([u8; 48], [u8; 48], [u8; 48], [u8; 48]),
576 b: ([u8; 48], [u8; 48], [u8; 48], [u8; 48]),
577 ) -> Result<[u8; 192], CryptoError> {
578 #[cfg(feature = "blst")]
579 {
580 crate::bls_blst::g2_add(a, b)
581 }
582 #[cfg(not(feature = "blst"))]
583 {
584 let _ = (a, b);
585 Err(CryptoError::Unsupported(BLS_UNSUPPORTED))
586 }
587 }
588
589 #[allow(clippy::type_complexity)]
591 fn bls12_381_g2_msm(
592 &self,
593 pairs: &[(([u8; 48], [u8; 48], [u8; 48], [u8; 48]), [u8; 32])],
594 ) -> Result<[u8; 192], CryptoError> {
595 #[cfg(feature = "blst")]
596 {
597 crate::bls_blst::g2_msm(pairs)
598 }
599 #[cfg(not(feature = "blst"))]
600 {
601 let _ = pairs;
602 Err(CryptoError::Unsupported(BLS_UNSUPPORTED))
603 }
604 }
605
606 #[allow(clippy::type_complexity)]
608 fn bls12_381_pairing_check(
609 &self,
610 pairs: &[(
611 ([u8; 48], [u8; 48]),
612 ([u8; 48], [u8; 48], [u8; 48], [u8; 48]),
613 )],
614 ) -> Result<bool, CryptoError> {
615 #[cfg(feature = "blst")]
616 {
617 crate::bls_blst::pairing_check(pairs)
618 }
619 #[cfg(not(feature = "blst"))]
620 {
621 let _ = pairs;
622 Err(CryptoError::Unsupported(BLS_UNSUPPORTED))
623 }
624 }
625
626 fn bls12_381_fp_to_g1(&self, fp: &[u8; 48]) -> Result<[u8; 96], CryptoError> {
628 #[cfg(feature = "blst")]
629 {
630 crate::bls_blst::fp_to_g1(fp)
631 }
632 #[cfg(not(feature = "blst"))]
633 {
634 let _ = fp;
635 Err(CryptoError::Unsupported(BLS_UNSUPPORTED))
636 }
637 }
638
639 fn bls12_381_fp2_to_g2(&self, fp2: ([u8; 48], [u8; 48])) -> Result<[u8; 192], CryptoError> {
641 #[cfg(feature = "blst")]
642 {
643 crate::bls_blst::fp2_to_g2(fp2)
644 }
645 #[cfg(not(feature = "blst"))]
646 {
647 let _ = fp2;
648 Err(CryptoError::Unsupported(BLS_UNSUPPORTED))
649 }
650 }
651}
652
653fn pad_modexp_output(res_bytes: Vec<u8>, modulus_len: usize) -> Result<Vec<u8>, CryptoError> {
657 let mut out = vec![0u8; modulus_len];
658 if res_bytes.len() <= modulus_len {
659 let offset = modulus_len - res_bytes.len();
660 out[offset..].copy_from_slice(&res_bytes);
661 } else {
662 out.copy_from_slice(&res_bytes[res_bytes.len() - modulus_len..]);
663 }
664 Ok(out)
665}
666
667#[cfg(feature = "std")]
673pub(crate) fn modexp_arbitrary_precision(
674 base: &[u8],
675 exp: &[u8],
676 modulus: &[u8],
677) -> Result<Vec<u8>, CryptoError> {
678 use malachite::base::num::arithmetic::traits::ModPow as _;
679 use malachite::base::num::basic::traits::Zero as _;
680 use malachite::{Natural, base::num::conversion::traits::*};
681
682 let base_nat = Natural::from_power_of_2_digits_desc(8u64, base.iter().cloned())
683 .ok_or(CryptoError::InvalidInput("base"))?;
684 let exp_nat = Natural::from_power_of_2_digits_desc(8u64, exp.iter().cloned())
685 .ok_or(CryptoError::InvalidInput("exponent"))?;
686 let mod_nat = Natural::from_power_of_2_digits_desc(8u64, modulus.iter().cloned())
687 .ok_or(CryptoError::InvalidInput("modulus"))?;
688
689 let result = if mod_nat == Natural::ZERO {
690 Natural::ZERO
691 } else if exp_nat == Natural::ZERO {
692 Natural::from(1_u8) % &mod_nat
693 } else {
694 let base_mod = base_nat % &mod_nat;
695 base_mod.mod_pow(&exp_nat, &mod_nat)
696 };
697
698 let res_bytes: Vec<u8> = result.to_power_of_2_digits_desc(8);
699 pad_modexp_output(res_bytes, modulus.len())
700}