revm_precompile/kzg_point_evaluation/
arkworks.rs1use crate::{
3 bls12_381::arkworks::pairing_check, bls12_381_const::TRUSTED_SETUP_TAU_G2_BYTES,
4 PrecompileError,
5};
6use ark_bls12_381::{Fr, G1Affine, G2Affine};
7use ark_ec::{AffineRepr, CurveGroup};
8use ark_ff::{BigInteger, PrimeField};
9use ark_serialize::CanonicalDeserialize;
10use core::ops::Neg;
11use primitives::OnceLock;
12
13#[inline]
18pub fn verify_kzg_proof(
19 commitment: &[u8; 48],
20 z: &[u8; 32],
21 y: &[u8; 32],
22 proof: &[u8; 48],
23) -> bool {
24 let Ok(commitment_point) = parse_g1_compressed(commitment) else {
26 return false;
27 };
28
29 let Ok(proof_point) = parse_g1_compressed(proof) else {
31 return false;
32 };
33
34 let Ok(z_fr) = read_scalar_canonical(z) else {
37 return false;
38 };
39 let Ok(y_fr) = read_scalar_canonical(y) else {
40 return false;
41 };
42
43 let tau_g2 = get_trusted_setup_g2();
45
46 let g1 = get_g1_generator();
48 let g2 = get_g2_generator();
49
50 let y_g1 = p1_scalar_mul(&g1, &y_fr);
52 let p_minus_y = p1_sub_affine(&commitment_point, &y_g1);
53
54 let z_g2 = p2_scalar_mul(&g2, &z_fr);
56 let x_minus_z = p2_sub_affine(tau_g2, &z_g2);
57
58 let neg_g2 = p2_neg(&g2);
61
62 pairing_check(&[(p_minus_y, neg_g2), (proof_point, x_minus_z)])
63}
64
65fn get_trusted_setup_g2() -> &'static G2Affine {
68 static TAU_G2: OnceLock<G2Affine> = OnceLock::new();
69 TAU_G2.get_or_init(|| {
70 G2Affine::deserialize_compressed_unchecked(&TRUSTED_SETUP_TAU_G2_BYTES[..])
73 .expect("Failed to parse trusted setup G2 point")
74 })
75}
76
77fn parse_g1_compressed(bytes: &[u8; 48]) -> Result<G1Affine, PrecompileError> {
79 G1Affine::deserialize_compressed(&bytes[..]).map_err(|_| PrecompileError::KzgInvalidG1Point)
80}
81
82fn read_scalar_canonical(bytes: &[u8; 32]) -> Result<Fr, PrecompileError> {
84 let fr = Fr::from_be_bytes_mod_order(bytes);
85
86 let bytes_roundtrip = fr.into_bigint().to_bytes_be();
88
89 if bytes_roundtrip.as_slice() != bytes {
90 return Err(PrecompileError::NonCanonicalFp);
91 }
92
93 Ok(fr)
94}
95
96#[inline]
98fn get_g1_generator() -> G1Affine {
99 G1Affine::generator()
100}
101
102#[inline]
104fn get_g2_generator() -> G2Affine {
105 G2Affine::generator()
106}
107
108#[inline]
110fn p1_scalar_mul(point: &G1Affine, scalar: &Fr) -> G1Affine {
111 point.mul_bigint(scalar.into_bigint()).into_affine()
112}
113
114#[inline]
116fn p2_scalar_mul(point: &G2Affine, scalar: &Fr) -> G2Affine {
117 point.mul_bigint(scalar.into_bigint()).into_affine()
118}
119
120#[inline]
122fn p1_sub_affine(a: &G1Affine, b: &G1Affine) -> G1Affine {
123 (a.into_group() - b.into_group()).into_affine()
124}
125
126#[inline]
128fn p2_sub_affine(a: &G2Affine, b: &G2Affine) -> G2Affine {
129 (a.into_group() - b.into_group()).into_affine()
130}
131
132#[inline]
134fn p2_neg(p: &G2Affine) -> G2Affine {
135 p.neg()
136}