Skip to main content

ethrex_crypto/
native.rs

1use crate::provider::{Crypto, CryptoError};
2
3/// Native crypto implementation using system libraries.
4///
5/// Most method bodies live as defaults on the [`Crypto`] trait itself. The
6/// P-256 (secp256r1) verify is overridden here to use the assembly-optimized
7/// `aws-lc-rs` backend when the `aws-lc-rs` feature is enabled, since the
8/// portable `p256` default does two constant-time scalar muls with no
9/// Shamir/basepoint optimization and is a P256VERIFY hot-path outlier. On the
10/// host the BLS12-381 (EIP-2537) defaults likewise route through the
11/// assembly-optimized `blst` backend (the `blst` feature, default-on); zkVM
12/// guest builds compile both backends out and use their own `Crypto` providers
13/// instead of this type. BN254 ECADD/ECMUL use the dedicated G1 code in
14/// [`crate::bn254`], which avoids the generic decoding, inversion and scalar
15/// multiplication paths of the trait defaults. This
16/// struct exists so callers outside zkVM contexts have a concrete type to
17/// instantiate.
18#[derive(Debug)]
19pub struct NativeCrypto;
20
21impl Crypto for NativeCrypto {
22    #[cfg(feature = "aws-lc-rs")]
23    fn secp256r1_verify(&self, msg: &[u8; 32], sig: &[u8; 64], pk: &[u8; 64]) -> bool {
24        crate::p256_awslc::secp256r1_verify(msg, sig, pk)
25    }
26
27    fn bn254_g1_add(&self, p1: &[u8], p2: &[u8]) -> Result<[u8; 64], CryptoError> {
28        crate::bn254::g1_add(p1, p2)
29    }
30
31    fn bn254_g1_mul(&self, point: &[u8], scalar: &[u8]) -> Result<[u8; 64], CryptoError> {
32        crate::bn254::g1_mul(point, scalar)
33    }
34
35    fn bn254_pairing_check(&self, pairs: &[(&[u8], &[u8])]) -> Result<bool, CryptoError> {
36        crate::bn254::pairing_check(pairs)
37    }
38
39    /// Odd moduli of up to 128 bytes take the fixed-width Montgomery path;
40    /// everything else uses the arbitrary-precision default.
41    #[cfg(feature = "std")]
42    fn modexp(
43        &self,
44        base: &[u8],
45        exp: &[u8],
46        modulus: &[u8],
47    ) -> Result<Vec<u8>, crate::provider::CryptoError> {
48        match crate::modexp_montgomery::modexp(base, exp, modulus) {
49            Some(result) => Ok(result),
50            None => crate::provider::modexp_arbitrary_precision(base, exp, modulus),
51        }
52    }
53}