ziskos 1.1.0-alpha

Guest runtime and entrypoint for programs targeting the ZisK zkVM
use lazy_static::lazy_static;
use num_bigint::BigUint;

use crate::zisklib::fcalls_impl::utils::{biguint_from_u64_digits, n_u64_digits_from_biguint};

use super::P;

/// Perform the inversion of a NON-ZERO field element in Fp
pub fn fcall_secp256k1_fp_inv(params: &[u64], results: &mut [u64]) -> i64 {
    // Get the input
    let a: &[u64; 4] = &params[0..4].try_into().unwrap();

    // Perform the inversion using fp inversion
    let inv = secp256k1_fp_inv(a);

    // Store the result
    results[0..4].copy_from_slice(&inv);

    4
}

fn secp256k1_fp_inv(a: &[u64; 4]) -> [u64; 4] {
    let a_big = biguint_from_u64_digits(a);
    let inv = a_big.modinv(&P);
    match inv {
        Some(inverse) => n_u64_digits_from_biguint(&inverse),
        None => panic!("Inverse does not exist"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn secp256k1_fp_mul(a: &[u64; 4], b: &[u64; 4]) -> [u64; 4] {
        let a_big = biguint_from_u64_digits(a);
        let b_big = biguint_from_u64_digits(b);
        let ab_big = (a_big * b_big) % &*P;
        n_u64_digits_from_biguint::<4>(&ab_big)
    }

    #[test]
    fn test_inv_one() {
        let x = [1, 0, 0, 0];
        let expected_inv = [1, 0, 0, 0];

        let mut results = [0; 4];
        fcall_secp256k1_fp_inv(&x, &mut results);
        assert_eq!(results, expected_inv);
    }

    #[test]
    fn test_inv() {
        let x = [0xf9ee4256a589409f, 0xa21a3985f17502d0, 0xb3eb393d00dc480c, 0x142def02c537eced];
        let expected_inv =
            [0xc198809f72408ac9, 0xa8726302e84e0c65, 0xde970a9a3b70d025, 0xf70d37bc0fece9b8];

        let mut results = [0; 4];
        fcall_secp256k1_fp_inv(&x, &mut results);
        assert_eq!(results, expected_inv);
        assert_eq!(secp256k1_fp_mul(&x, &results), [1, 0, 0, 0]);

        let x = [0xffffffffbfffff0c, 0xffffffffffffffff, 0xffffffffffffffff, 0x3fffffffffffffff];
        let expected_inv =
            [0x0000000000000004, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000];

        let mut results = [0; 4];
        fcall_secp256k1_fp_inv(&x, &mut results);
        assert_eq!(results, expected_inv);
        assert_eq!(secp256k1_fp_mul(&x, &results), [1, 0, 0, 0]);
    }
}